Programming in C
Programming in C
1
Write a program to add, subtract, multiply, and divide two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, c;
float d;
printf("Enter two numbers:\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("\nSum = %d", c);
c = a - b;
printf("\nDifference = %d", c);
c = a * b;
printf("\nMultiplication = %d", c);
d = (float)a / b;
printf("\nDivision = %f", d);
getch();
}
2
Write a program to find square root of a given number.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
float n, s;
printf("Enter a number:");
scanf("%f", &n);
s = sqrt(n);
printf("Square root of %f is %f", n, s);
getch();
}
3
#include<conio.h>
void main()
{
clrscr();
float l, b, a, p;
printf("Enter length and breadth:\n");
scanf("%f%f", &l, &b);
a = l * b;
p = 2 * (l + b);
printf("Area = %f\n",a);
printf("Perimeter = %f",p);
getch();
}
Write a program to find price of n mangos given the price of a dozen mangos.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float pricedozen, pricen;
int n;
printf("Enter price of a dozen mangos:");
scanf("%f", &pricedozen);
printf("Enter number of mangos:");
scanf("%d", &n);
pricen = pricedozen / 12 * n;
printf("Price of %d mangos is % f", n, pricen);
getch();
}
4
clrscr();
float d, cr, r;
printf("Enter dollars:");
scanf("%f", &d);
printf("Enter conversion rate:");
scanf("%f", &cr);
r = d * cr;
printf("Rupees = %f", r);
getch();
}
Write a program to express a length given in millimeters in meters, centimeters, and millimeters.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float mm, m, cm;
printf("Enter milimeters:");
scanf("%f", &mm);
cm = mm / 10;
m = cm / 100;
printf("Meter = %f\n", m);
printf("Centimeter = %f\n", cm);
printf("Millimeter = %f", mm);
getch();
}
Control Structures
Write a program to calculate discount. If purchased amount is greater than or equal to 1000,
discount is 5% .
#include<stdio.h>
#include<conio.h>
void main()
{
float pa, d = 0;
clrscr();
printf("Enter purchased amount:");
scanf("%f", &pa);
if(pa >= 1000)
d = pa * 0.05;
printf("Discount = %f", d);
getch();
}
6
if(num % 2 == 0)
printf("%d is even", num);
else
printf("%d us odd", num);
getch();
}
7
printf("Not eligible");
getch();
}
8
Write a program to print the largest number among three numbers input by the user.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, largest;
clrscr();
printf("Enter three numbers:\n");
scanf("%d%d%d", &a, &b, &c);
largest = a;
if(b > largest)
largest = b;
if(c > largest)
largest = c;
printf("Largest number is %d", largest);
getch();
}
Given marks in five subjects. Write a program (a) to display “PASS” or “FAIL” if assumed pass marks
is 45 in each subject, (b) to find percentage of marks obtained, and (c) to find division for “PASS”
students assuming that 80% and above for “DISTINCTION”, 60% and above for “FIRST DIVISION”
9
otherwise “SECOND DIVISION”.
#include<stdio.h>
#include<conio.h>
void main()
{
int m1, m2, m3, m4, m5, t;
float p;
clrscr();
printf("Enter marks in five subjects:\n");
scanf("%d%d%d%d%d", &m1, &m2, &m3, &m4, &m5);
if(m1 >= 45 && m2 >= 45 && m3 >= 45 && m4 >= 45 && m5 >= 45)
printf("Result = PASS");
else
printf("Result = FAIL");
t = m1 + m2 + m3 + m4 + m5;
p = (float)t / 5;
printf("\nPercentage = %f\n", p);
if(m1 >= 45 && m2 >= 45 && m3 >= 45 && m4 >= 45 && m5 >= 45)
if(p >= 80)
printf("DISTINCTION");
else if(p >= 60)
printf("FIRST DIVISION");
else
printf("SECOND DIVISION");
getch();
}
Write a program using switch statement to develop a simple calculator for +, -, *, /, and % operators
.
#include<stdio.h>
#include<conio.h>
void main()
{
char op;
int a, b, c;
float d;
clrscr();
printf("Enter two numbers:\n");
scanf("%d%d", &a, &b);
printf("Enter an operator(+, -, *, /, or %):");
scanf(" %c", &op);
switch(op)
{
case '+':
c = a + b;
printf("Sum = %d", c);
break;
case '-':
c = a - b;
printf("Difference = %d", c);
10
break;
case '*':
c = a * b;
printf("Product = %d", c);
break;
case '/':
d = (float)a / b;
printf("Division = %f", d);
break;
case '%':
c = (int)a % (int)b;
printf("Remainder = %d", c);
break;
default:
printf("Wrong operator");
}
getch();
}
Looping Structures
Write a program to display your name 10 times using all the three looping statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i = 0; i < 10; i++)
printf("Siddhanath\n");
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 0;
clrscr();
while(i < 10)
{
printf("Siddhanath \n");
i++;
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 0;
clrscr();
do
11
{
printf("Siddhanath \n");
i++;
}while(i < 10);
getch();
}
Write a program to display first n natural numbers, their sum, and their average using all the
three looping statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, sum = 0;
float avg;
clrscr();
printf("Enter n:");
scanf("%d", &n);
printf("First %d natural numbers are:", n);
for(i = 1; i <= n; i++)
{
printf("\n%d", i);
sum = sum + i; //sum += i;
}
avg = (float)sum / n;
printf("\nSum = %d", sum);
printf("\nAverage = %f", avg);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i = 1, sum = 0;
float avg;
clrscr();
printf("Enter n:");
scanf("%d", &n);
printf("First %d natural numbers are:", n);
while(i <= n)
{
printf("\n%d", i);
sum = sum + i; //sum += i;
i++;
}
avg = (float)sum / n;
printf("\nSum = %d", sum);
printf("\nAverage = %f", avg);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
12
{
int n, i = 1, sum = 0;
float avg;
clrscr();
printf("Enter n:");
scanf("%d", &n);
printf("First %d natural numbers are:", n);
do
{
printf("\n%d", i);
sum = sum + i; //sum += i;
i++;
}while(i <= n);
avg = (float)sum / n;
printf("\nSum = %d", sum);
printf("\nAverage = %f", avg);
getch();
}
Write a program to display the temperatures from 0 degrees Celsius to 100 degrees Celsius and
their Fahrenheit equivalent.
#include<stdio.h>
#include<conio.h>
void main()
{
int c;
float f;
clrscr();
for(c = 0; c <= 100; c++)
{
f = (float)c * 9 / 5 + 32;
printf("\n%f", f);
}
getch();
}
Write a program to find out sum of all numbers completely divisible by 5 among n numbers given
by the user.
#include<stdio.h>
#include<conio.h>
void main()
13
{
int n, sum = 0, i;
clrscr();
printf("Enter n:");
scanf("%d", &n);
for(i = 5; i <= n; i = i + 5)
sum = sum + i;
printf("Sum = %d", sum);
getch();
}
Write a program to determine the sum of the harmonic series (1+ 1/2 + 1/3 + 1/4 + … + 1/n) for a
given value of n.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i;
float sum = 0;
clrscr();
printf("Enter n:");
scanf("%d", &n);
for(i = 1; i <= n; i = i + 1)
sum = sum + 1.0 / i;
printf("Sum = %f", sum);
getch();
}
Write a program to calculate the sequence 1/1! + 2/2! + 3/3! +…..+ n/n! where n is the number of
input by the user.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, j, facto;
float sum = 0;
clrscr();
printf("Enter n:");
14
scanf("%d", &n);
for(i = 1; i <= n; i++)
{
facto = 1;
for(j = 1; j <= i; j++)
facto = facto * j;
sum = sum + (float)i / facto;
}
printf("Sum = %f", sum);
getch();
}
Write a program to display sum of the following series up to n terms: Sum = x - x2 + x3 - x4 +…….
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x, n, sum = 0, i;
clrscr();
printf("Enter values of x and n:\n");
scanf("%d%d", &x, &n);
for(i = 1; i <= n; i++)
{
if(i%2 == 0)
sum = sum - pow(x, i);
else
sum = sum + pow(x, i);
}
printf("Sum = %d", sum);
getch();
}
Write a program to find X of the following series for the given value of a and N.
X = a – a2/2 + a3/3 – a4/4………………up to N
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a, n, i;
float x = 0;
clrscr();
printf("Enter values of a and n:\n");
scanf("%d%d", &a, &n);
for(i = 1; i <= n; i++)
{
if(i%2 == 0)
x = x - pow(a, i) / i;
else
x = x + pow(a, i) / i;
}
printf("X = %f", x);
getch();
15
}
Write a program to compute the sum of the digits of the given integer number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, num, digit, sum = 0;
clrscr();
printf("Enter value of n:");
scanf("%d", &n);
num = n;
while(num != 0)
{
digit = num % 10;
sum = sum + digit;
num = num / 10;
}
printf("Sum = %d", sum);
getch();
}
16
rev = (rev * 10) + digit;
num = num / 10;
}
if(n == rev)
printf("Palindrome");
else
printf("Not a palindrome");
getch();
}
17
for(j = 2; j < i; j++)
{
if(i % j == 0)
{
prime = 0;
break;
}
}
if(prime)
printf("%d\n", i);
}
getch();
}
Write a program to display all the leap years starting from 1900 to 2000.
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Leap years starting from 1900 to 2000:\n");
for(year = 1900; year <= 2000; year++)
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
printf("%d\n", year);
getch();
}
Write a program using function to calculate and return sum of following series up to n terms; where
x and n are supposed as passed by main program; sum = x-x2+x3-x4+…..
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x, n, s;
int sum(int, int);
clrscr();
printf("Enter values of x and n:\n");
scanf("%d%d", &x, &n);
s = sum(x, n);
printf("Sum = %d", s);
getch();
}
int sum(int x, int n)
{
int i, s = 0;
for(i = 1; i <= n; i++)
{
if(i%2 == 0)
s = s - pow(x, i);
else
s = s + pow(x, i);
}
20
return s;
}
A five digit positive integer is entered through the keyboard; write program using function to
calculate the sum of the digits of the number. The function should receive the integer from main ()
and output also be printed through main ().
#include<stdio.h>
#include<conio.h>
void main()
{
int n, s;
int sum(int);
clrscr();
printf("Enter a five digit positive integer:");
scanf("%d", &n);
s = sum(n);
printf("Sum = %d", s);
getch();
}
int sum(int n)
{
int num, digit, s = 0;
num = n;
while(num != 0)
{
digit = num % 10;
s = s + digit;
num = num / 10;
}
return s;
}
Write a program to calculate factorial of a number using recursive function and the same program
without using recursive function.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long facto;
long factorial(int);
printf("Enter value of n:");
scanf("%d", &n);
facto = factorial(n);
printf("%d! = %ld", n, facto);
getch();
}
long factorial(int n)
{
if(n == 0)
21
return 1;
else
return n * factorial(n - 1);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long facto;
long factorial(int);
printf("Enter value of n:");
scanf("%d", &n);
facto = factorial(n);
printf("%d! = %ld", n, facto);
getch();
}
long factorial(int n)
{
long facto = 1;
int i;
if(n==0)
facto = 1;
else
for(i=1;i<=n;i++)
facto=facto*i;
return facto;
}
Write a program to find product of first n natural numbers using recursive function.
#include<stdio.h>
#include<conio.h>
void main()
{
23
int n;
long p;
long prod(int);
clrscr();
printf("Enter the value of n:");
scanf("%d", &n);
p = prod(n);
printf("Product of first %d natural numbers = %ld", n, p);
getch();
}
long prod(int n)
{
if(n == 1)
return 1;
else
return n * prod(n - 1);
}
24
printf("Fibonacci series up to %d terms:\n", n);
for(i = 1; i <= n; i++)
{
f = fibo(i);
printf("%d\n", f);
}
getch();
}
int fibo(int i)
{
if(i == 1 || i == 2)
return 1;
else
return fibo(i - 1) + fibo(i - 2);
}
Write macros to compute area and circumference of circle and make a program to use this macro.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define PI 3.1415
#define area(r) PI*pow(r,2)
#define circum(r) 2*PI*r
void main(void)
{
float r,a,c;
clrscr();
printf("Enter radius:");
scanf("%f",&r);
a = area(r);
c = circum(r);
printf("Area = %f\n", a);
printf("Circumference = %f", c);
getch();
}
25
printf("Perimeter = %d", p);
getch();
}
Write a program to count number of times a function executes using static local variable.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int count;
int test();
clrscr();
count = test();
printf("%d\n", count); //1
count = test();
printf("%d\n", count); //2
count = test();
printf("%d", count); //3
getch();
}
int test()
{
static int count = 0;
count++;
return count;
}
Write a program to display largest and smallest number among 10 numbers stored in an array.
#include<stdio.h>
#include<conio.h>
#define SIZE 5
void main()
{
float a[SIZE],smallest,largest;
int i;
clrscr();
printf("Enter 10 numbers:\n");
for(i=0;i<SIZE;i++)
scanf("%f",&a[i]);
smallest=largest=a[0];
for(i=1;i<SIZE;i++)
{
if(a[i]<smallest)
smallest=a[i];
if(a[i]>largest)
largest=a[i];
}
printf("Largest number=%f\n",largest);
printf("Smallest number=%f",smallest);
getch();
}
27
#include<conio.h>
void main()
{
int a[]={45,32,78,50,8,10,31,25,27,43},i,n;
clrscr();
printf("Enter element to search:");
scanf("%d",&n);
for(i=0;i<10;i++)
if(n==a[i])
{
printf("Found at index %d",i);
break;
}
if(i==10)
printf("Not found");
getch();
}
Write a program to search an element in array using binary search.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={8,10,25,32,43,45,50,55,63,78},n,low,hi,mid;
clrscr();
printf("Enter element to search:");
scanf("%d",&n);
low=0;
hi=9;
while(low<=hi)
{
mid=(low+hi)/2;
if(n==a[mid])
{
printf("Found at index %d",mid);
break;
}
else if(n<a[mid])
hi=mid-1;
else
low=mid+1;
}
if(low>hi)
printf("Not found");
getch();
}
Write a program to sort numbers stored in an array using bubble sort in ascending order.
#include<stdio.h>
#include<conio.h>
#define SIZE 100
28
void main()
{
int a[SIZE],n,i,j,temp;
clrscr();
printf("How many numbers?");
scanf("%d",&n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Sorted list is:\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
Write a program to sort numbers stored in an array using bubble sort in descending order.
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
int a[SIZE],n,i,j,temp;
clrscr();
printf("How many numbers?");
scanf("%d",&n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Sorted list is:\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
29
Write a program to read name list of 50 students and display them in alphabetical form.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 50
void main()
{
char names[N][20],temp[20];
int i,j;
clrscr();
printf("Enter name list of 50 students:\n");
for(i=0;i<N;i++)
gets(names[i]);
for(i=0;i<N-1;i++)
for(j=0;j<N-1-i;j++)
if(strcmp(names[j],names[j+1])>0)
{
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
printf("Sorted list is:\n");
for(i=0;i<N;i++)
printf("%s\n",names[i]);
getch();
}
Write a program to read a string and count the number of vowels and consonants in it.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
int i=0,v=0,c=0;
clrscr();
printf("Enter a string:");
gets(str);
while(str[i]!='\0')
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
v++;
else
c++;
i++;
}
printf("Number of vowels=%d\n",v);
printf("Number of consonents=%d",c);
getch();
}
30
Write a program to read a line of text and delete all the vowels from it.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50];
int i=0,j;
clrscr();
printf("Enter a string:");
gets(str);
while(str[i]!='\0')
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
{
j=i;
while(str[j] != '\0')
{
str[j]=str[j+1];
j++;
}
i--;
}
i++;
}
puts(str);
getch();
}
Write a program to add two 3×2 matrices and print the result in matrix form.
31
#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 2
void main()
{
int a[ROW][COL],b[ROW][COL],i,j,sum;
clrscr();
printf("Enter elements of first matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",&a[i][j]);
printf("\n");
}
printf("Enter elements of second matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",&b[i][j]);
printf("\n");
}
printf("Addition matrix is:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
sum=a[i][j]+b[i][j];
printf("%d\t",sum);
}
printf("\n");
}
getch();
}
Write a program that accepts the elements of 3 × 3 matrix and calculate the sum of all elements of
the matrix.
#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 3
void main()
{
int a[ROW][COL],i,j,sum=0;
clrscr();
printf("Enter elements of matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
32
scanf("%d",&a[i][j]);
sum=sum+a[i][j];
}
printf("\n");
}
printf("Sum=%d",sum);
getch();
}
Write a program to read two-dimensional matrix and display its transposed form.
#include<stdio.h>
#include<conio.h>
#define ROW 2
#define COL 3
void main()
{
int a[ROW][COL],i,j;
clrscr();
printf("Enter elements of matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",&a[i][j]);
printf("\n");
33
}
printf("Original matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("Transpose matrix:\n");
for(i=0;i<COL;i++)
{
for(j=0;j<ROW;j++)
printf("%d\t",a[j][i]);
printf("\n");
}
getch();
}
Write a program to convert a 4×4 matrix to upper triangular and display the result in matrix form.
#include<stdio.h>
#include<conio.h>
#define ROW 4
#define COL 4
void main()
{
int a[ROW][COL],i,j;
clrscr();
printf("Enter elements of matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",&a[i][j]);
printf("\n");
}
printf("Original matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
for(i=1;i<ROW;i++)
for(j=0;j<i;j++)
a[i][j]=0;
printf("Upper traingular matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n");
34
}
getch();
}
Write a program to convert a 4×4 matrix to lower triangular and display the result in matrix form.
#include<stdio.h>
#include<conio.h>
#define ROW 4
#define COL 4
void main()
{
int a[ROW][COL],i,j;
clrscr();
printf("Enter elements of matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d",&a[i][j]);
printf("\n");
}
printf("Original matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
for(j=1;j<COL;j++)
for(i=0;i<j;i++)
a[i][j]=0;
printf("Lower traingular matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
getch();
}
Write a program to multiply two rectangular matrices and display the resultant matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3],b[3][2],i,j,k,mul;
clrscr();
printf("Enter elements of first matrix:\n");
for(i=0;i<2;i++)
{
35
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\n");
}
printf("Enter elements of second matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
printf("\n");
}
printf("First matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("Second matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("Multiplication matrix:\n");
for(i=0;i<2;i++){
for(j=0;j<2;j++) {
mul=0;
for(k=0;k<3;k++)
mul += a[i][k] * b[k][j];
printf("%d\t",mul);
}
printf("\n");
}
getch();
}
Write a program to read n numbers in an array and display their sum and average. Use functions
to read input and find sum and average.
#include<stdio.h>
#include<conio.h>
#define SIZE 100
int i;
void main()
{
float a[SIZE], s, av;
int n;
void input(float a[], int);
float sum(float a[], int);
36
float avg(float a[], int);
clrscr();
printf("How many numbers?");
scanf("%d", &n);
printf("Enter numbers:\n");
input(a, n);
s = sum(a, n);
av = avg(a, n);
printf("Sum = %f\n", s);
printf("Average = %f", av);
getch();
}
void input(float a[], int n)
{
for(i=0;i<n;i++)
scanf("%f",&a[i]);
}
float sum(float a[], int n)
{
float s = 0;
for(i=0;i<n;i++)
s = s + a[i];
return s;
}
float avg(float a[], int n)
{
float av;
av = sum(a, n) / n;
return av;
}
Write a program to add two 3 × 4 matrices and print the result in matrix form. Use separate
functions to take input and to add and display the result.
#include<stdio.h>
#include<conio.h>
int i, j, c;
void main()
{
int a[3][4], b[3][4];
void input(int a[][4]);
void add(int a[][4], int b[][4]);
clrscr();
printf("Input first matrix:\n");
input(a);
printf("Input second matrix:\n");
input(b);
printf("Addition matrix is:\n");
add(a, b);
getch();
}
37
void input(int a[][4])
{
for(i=0;i<3;i++)
for(j=0;j<4;j++)
scanf("%d", &a[i][j]);
}
void add(int a[][4],int b[][4])
{
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
c = a[i][j] + b[i][j];
printf("%d\t", c);
}
printf("\n");
}
}
Pointers
Write a program to swap two numbers using a function and by passing arguments as references.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
void swap(int*, int*);
clrscr();
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
swap(&a, &b);
printf("a = %d\tb = %d", a, b);
getch();
}
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
Write a program to read n numbers in an array and display their sum and average. Use the concept of
pointer to access array elements.
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
float a[SIZE], sum=0, avg;
int n, i;
38
clrscr();
printf("How many numbers?");
scanf("%d", &n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
{
scanf("%f", (a+i));
sum=sum + *(a+i);
}
avg = sum / n;
printf("Sum=%f\n", sum);
printf("Average=%f", avg);
getch();
}
Using pointer write a program to get n integer number and display them in ascending order (use malloc or
calloc to reserve memory).
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *a, n, i, j, *temp;
clrscr();
printf("How many numbers?");
scanf("%d", &n);
a = (int*)malloc(n * sizeof(int));
//a = (int*)calloc(n, sizeof(int));
printf("Enter numbers:\n");
for(i = 0; i < n; i++)
scanf("%d", (a+i));
for(i = 0; i < n-1; i++)
for(j = 0; j <n-1-i; j++)
if(*(a+j) > *(a+j+1))
{
*temp = *(a+j);
*(a+j) = *(a+j+1);
*(a+j+1) = *temp;
}
printf("Sorted list is:\n");
for(i=0;i<n;i++)
printf("%d\n",*(a+i));
getch();
}
Using pointer write a program to add two 3 × 2 matrices and print the result in matrix form.
#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 2
void main()
{
int a[ROW][COL],b[ROW][COL],i,j,sum;
clrscr();
39
printf("Enter elements of first matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d", (*(a+i)+j));
printf("\n");
}
printf("Enter elements of second matrix:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
scanf("%d", (*(b+i)+j));
printf("\n");
}
printf("Addition matrix is:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
sum = *(*(a+i)+j)+*(*(b+i)+j);
printf("%d\t",sum);
}
printf("\n");
}
getch();
}
Write a program to search the given name among the list of names of n students using pointer.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define LENGTH 20
void main()
{
char **names, name[LENGTH];
int n, i;
clrscr();
printf("Enter value of n:");
scanf("%d",&n);
printf("Enter names:\n");
for(i=0;i<n;i++)
{
*(names+i)=(char*)malloc(LENGTH);
scanf("%s",*(names+i));
}
printf("Enter name to search:");
scanf("%s", name);
for(i=0;i<n;i++)
{
if(strcmp(*(names+i),name) == 0)
{
printf("Found at location %d", i+1);
break;
40
}
}
if(i == n)
printf("Not found");
getch();
}
Structures and Unions
Write a program to read 100 students record with fields (roll no, name, class, and marks in 5 subjects) and
display their records along with their percentage of marks obtained.
#include<stdio.h>
#include<conio.h>
#define NUM 100
void main()
{
struct student
{
int roll_no;
char name[20];
int clas;
int marks[5];
};
struct student s[NUM];
int i, j, total;
float percentage;
clrscr();
for(i = 0; i < NUM; i++)
{
printf("Enter data for student %d:\n", i+1);
printf("Enter roll number:");
scanf("%d", &s[i].roll_no);
printf("Enter name:");
scanf("%s", s[i].name);
printf("Enter class:");
scanf("%d", &s[i].clas);
printf("Enter marks in five subjects:\n");
for(j = 0; j < 5; j++)
scanf("%d", &s[i].marks[j]);
}
for(i = 0; i < NUM; i++)
{
printf("\nStudent %d:\n", i+1);
printf("Roll number: %d\n", s[i].roll_no);
printf("Name: %s\n", s[i].name);
printf("Class: %d\n", s[i].clas);
printf("Marks in five subjects:\n");
total = 0;
for(j = 0; j < 5; j++)
{
printf("%d\n", s[i].marks[j]);
total = total + s[i].marks[j];
}
percentage = (float)total / 5;
printf("Percentage: %f\n", percentage);
41
}
getch();
}
Write a program to read 100 students record with following fields and display the record of BBA
faculty only.
Roll No. Name Faculty DOB (date of birth)
dd mm yy
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define NUM 100
void main()
{
struct dob
{
int dd;
int mm;
int yy;
};
struct student
{
int roll_no;
char name[20];
char faculty[10];
struct dob date_of_birth;
};
struct student s[NUM];
int i;
clrscr();
for(i = 0; i < NUM; i++)
{
printf("Enter data for student %d:\n", i+1);
printf("Enter roll number:");
scanf("%d", &s[i].roll_no);
printf("Enter name:");
scanf("%s", s[i].name);
printf("Enter faculty:");
scanf("%s", s[i].faculty);
printf("Enter day:");
scanf("%d", &s[i].date_of_birth.dd);
printf("Enter month:");
scanf("%d", &s[i].date_of_birth.mm);
printf("Enter year:");
scanf("%d", &s[i].date_of_birth.yy);
}
printf("\nStudent's record of BBA faculty only:\n");
for(i = 0; i < NUM; i++)
{
if(strcmp(s[i].faculty,"BBA") == 0)
{
printf("Roll number: %d\n", s[i].roll_no);
printf("Name: %s\n", s[i].name);
42
printf("Faculty: %s\n", s[i].faculty);
printf("Day: %d\n", s[i].date_of_birth.dd);
printf("Month: %d\n", s[i].date_of_birth.mm);
printf("Year: %d\n", s[i].date_of_birth.yy);
}
}
getch();
}
Create a structure to specify data on customer in a bank. The data to store is: Acc. No., Name, and
Balance in account. Assume maximum of 200 customers in the bank.
1. Write a function to print the Ac. no. and name of each customer with balance below Rs. 100.
2. If a customer gives a request for withdrawl or deposit it is given in the form: Acct. no., Amount
(1 for deposit and 2 for withdrawl)
Write a program to give a message “the balance is insufficient” for the specified withdrawl.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define TRUE 1
#define N 200
struct account
{
int acct_no;
char name[20];
float balance;
};
int count = 0, i;
void main()
{
44
{
printf("\nCustomers with balance below Rs. 100:\n");
for(i = 0; i < count; i++)
{
if(customer[i].balance < 100)
{
printf("Account number: %d\n", customer[i].acct_no);
printf("Name: %s\n", customer[i].name);
}
}
}
In a bank there are N customers with attributes name, account_no, and balance. Write a program to find
out who has the highest balance in the bank.
#include<stdio.h>
#include<conio.h>
#define N 100
void main()
{
struct account
{
int acct_no;
char name[20];
float balance;
};
struct account customer[N];
float max_balance;
int n, i, max_index;
clrscr();
printf("How many customers?");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter data for customer %d:\n", i+1);
printf("Enter account number:");
scanf("%d", &customer[i].acct_no);
printf("Enter name:");
scanf("%s", customer[i].name);
printf("Enter balance:");
scanf("%f", &customer[i].balance);
}
max_balance = customer[0].balance;
max_index = 0;
for(i = 1; i < n; i++)
{
if(customer[i].balance > max_balance)
{
max_balance = customer[i].balance;
max_index = i;
}
}
printf("\nCustomer having highest balance:\n");
printf("Account number: %d\n", customer[max_index].acct_no);
printf("Name: %s\n", customer[max_index].name);
45
printf("Balance: %f", customer[max_index].balance);
getch();
}
Write a program using structure data to read name, roll, marks in three subjects of 20 students and print
the record in the ascending order of the total marks obtained in three subjects.
#include<stdio.h>
#include<conio.h>
#define N 3
void main()
{
struct student
{
char name[20];
int roll_no;
int marks[3];
};
struct student s[N], temp;
int i, j, k, total1, total2;
clrscr();
for(i = 0; i < N; i++)
{
printf("Enter data for student %d:\n", i+1);
printf("Enter name:");
scanf("%s", s[i].name);
printf("Enter roll number:");
scanf("%d", &s[i].roll_no);
printf("Enter marks in three subjects:\n");
for(j = 0; j < 3; j++)
scanf("%d", &s[i].marks[j]);
}
for(i = 0; i < N - 1; i++)
{
for(j = 0; j < N - 1 - i; j++)
{
total1 = total2 = 0;
for(k = 0; k < 3; k++)
{
total1 += s[j].marks[k];
total2 += s[j+1].marks[k];
}
if(total1 > total2)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
printf("Sorted list is:\n");
for(i = 0; i < N; i++)
{
printf("Name: %s\n", s[i].name);
printf("Roll no: %d\n", s[i].roll_no);
printf("Marks in three subjects:\n");
46
for(j = 0; j < 3; j++)
printf("%d\n", s[i].marks[j]);
}
getch();
}
File Handling
Write a program to read all numbers from the input file “values.dat” and store the average of these
numbers in an output file named as “average.res”.
#include<stdio.h>
#include<conio.h>
#define NULL 0
void main()
{
FILE *fpin, *fpout;
float val, avg, sum = 0;
int count = 0;
fpin = fopen("values.dat", "r");
if(fpin == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
while(!feof(fpin))
{
fscanf(fpin, "%f", &val);
sum = sum + val;
count++;
}
}
avg = sum / count;
fpout = fopen("average.res", "w");
if(fpout == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
fprintf(fpout, "Average=%f", avg);
fclose(fpin);
fclose(fpout);
getch();
}
Create a file named “university.dat”. Write a program to keep the records on N colleges under
Pokhara University if a file. These records contain name, location, and no_of_faculties of the
college and display the names of colleges in Kathmandu location.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define NULL 0
void main()
{
struct record
{
char name[30];
char location[30];
int no_of_faculty;
47
};
struct record college;
FILE *fp;
char ch;
clrscr();
fp = fopen("university.dat", "w+");
if(fp == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter college information:\n");
do
{
printf("Enter name:");
scanf(" %[^\n]", college.name);
printf("Enter location:");
scanf(" %[^\n]", college.location);
printf("Enter no of faculties:");
scanf("%d", &college.no_of_faculty);
fwrite(&college,sizeof(struct record),1,fp);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
rewind(fp); //sets positon indicator to the begining
fread(&college,sizeof(struct record),1,fp);
printf("Name of colleges in Kathmandu:\n");
while(!feof(fp)) {
if(strcmp(college.location, "Kathmandu") == 0)
printf("%s\n", college.name);
fread(&college,sizeof(struct record),1,fp);
}
}
fclose(fp);
getch();
}
Create a file named “employee.dat”. Write a program to store records of N employee in a file.
These records contain name, identification number, office name, and occupation of the employee.
Also display name of those employees whose office name is “Everest Bank” and occupation is
“manager”.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define NULL 0
void main()
{
struct record
{
char name[30];
int id;
char office_name[30];
char occupation[30];
};
struct record employee;
48
FILE *fp;
char ch;
clrscr();
fp = fopen("employee.dat", "w+");
if(fp == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter employee information:\n");
do
{
printf("Enter name:");
scanf(" %[^\n]", employee.name);
printf("Enter identification number:");
scanf("%d", &employee.id);
printf("Enter office name:");
scanf(" %[^\n]", employee.office_name);
printf("Enter occupation:");
scanf(" %[^\n]", employee.occupation);
fwrite(&employee,sizeof(struct record),1,fp);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
rewind(fp); //sets positon indicator to the begining
fread(&employee,sizeof(struct record),1,fp);
printf("Name of employeees whose office name is Everest Bank and occupation is
manager:\n");
while(!feof(fp)) {
if((strcmp(employee.office_name, "Everest Bank") == 0) &&
(strcmp(employee.occupation, "manager") == 0))
printf("%s\n", employee.name);
fread(&employee,sizeof(struct record),1,fp);
}
}
fclose(fp);
getch();
}
Create a structure to specify data on customers in a bank with the parameters Acct. No., Name,
Balance in Account. Assume there are 1000 customers in the bank. Write a program to store the
data in “CUST.DAT” file and print the Acct. No. and Name of each customer with balance below Rs.
1000.
#include<stdio.h>
#include<conio.h>
#define NULL 0
void main()
{
struct account
{
int acct_no;
char name[20];
float balance;
};
struct account customer;
49
FILE *fp;
char ch;
clrscr();
fp = fopen("CUST.DAT", "w+");
if(fp == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter customer information:\n");
do
{
printf("Enter account number:");
scanf("%d", &customer.acct_no);
printf("Enter name:");
scanf(" %[^\n]", customer.name);
printf("Enter balance:");
scanf("%f", &customer.balance);
fwrite(&customer,sizeof(struct account),1,fp);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
rewind(fp); //sets positon indicator to the begining
fread(&customer,sizeof(struct account),1,fp);
printf("Acct. No. and Name of customers with balance below Rs. 100:\n");
while(!feof(fp)) {
if(customer.balance < 1000)
printf("Acct. no: %d, Name: %s\n", customer.acct_no, customer.name);
fread(&customer,sizeof(struct account),1,fp);
}
}
fclose(fp);
getch();
}
Write a program to open a file named “student.txt” to keep the records of students (roll_no, name,
course, and semester) in a write mode and perform the following operations:
1. Insert records in to the file.
2. Display all those records for which course is BBA and semester is 2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define NULL 0
void main()
{
struct record
{
int roll_no;
char name[20];
char course[10];
int semester;
};
struct record student;
FILE *fp;
char ch;
50
clrscr();
fp = fopen("student.txt", "w+");
if(fp == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter student information:\n");
do
{
printf("Enter roll number:");
scanf("%d", &student.roll_no);
printf("Enter name:");
scanf(" %[^\n]", student.name);
printf("Enter course:");
scanf(" %[^\n]", student.course);
printf("Enter semester:");
scanf("%d", &student.semester);
fwrite(&student,sizeof(struct record),1,fp);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
rewind(fp); //sets positon indicator to the begining
fread(&student,sizeof(struct record),1,fp);
printf("Students for which course is BBA and semester is 2:\n");
while(!feof(fp)) {
if((strcmp(student.course, "BBA") == 0) && (student.semester == 2))
{
printf("Roll no: %d\n", student.roll_no);
printf("Name: %s\n", student.name);
printf("Course: %s\n", student.course);
printf("Semester: %d\n", student.semester);
}
fread(&student,sizeof(struct record),1,fp);
}
}
fclose(fp);
getch();
}
Write a program that creates a file named “employee.dat” to keep the records of N employees of
a company and print the records in the ascending order of the employee_id. A typical employee
record will be employee id, name, designation, and salary.
#include<stdio.h>
#include<conio.h>
#define NULL 0
void main()
{
struct record
{
int employee_id;
char name[20];
char designation[20];
float salary;
};
51
struct record employee, t;
struct record temp[100];
FILE *fp;
char ch;
int count = 0, i, j;
clrscr();
fp = fopen("employee.dat", "w+");
if(fp == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter employee information:\n");
do
{
printf("Enter id:");
scanf("%d", &employee.employee_id);
printf("Enter name:");
scanf(" %[^\n]", employee.name);
printf("Enter designation:");
scanf(" %[^\n]", employee.designation);
printf("Enter salary:");
scanf("%f", &employee.salary);
fwrite(&employee,sizeof(struct record),1,fp);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
rewind(fp); //sets positon indicator to the begining
fread(&employee,sizeof(struct record),1,fp);
while(!feof(fp)) {
temp[count] = employee;
count++;
fread(&employee,sizeof(struct record),1,fp);
}
}
fclose(fp);
for(i = 0; i < count - 1; i++)
{
for(j = 0; j < count - 1 - i; j++)
{
if(temp[j].employee_id > temp[j+1].employee_id)
{
t = temp[j];
temp[j] = temp[j + 1];
temp[j + 1] = t;
}
}
}
printf("Sorted list is:\n");
for(i = 0; i < count; i++)
{
printf("Employee id: %d\n", temp[i].employee_id);
printf("Name: %s\n", temp[i].name);
printf("Designation: %s\n", temp[i].designation);
printf("Salary: %f\n", temp[i].salary);
52
}
getch();
}
Suppose a store has a number of items in their inventory and that each item is supplied by at most
two suppliers. Create inventory and supplier files. Find the addresses of all suppliers who supply
more than 10 different items. Discuss any changes in data structure you would suggest to simplify
solving this problem.
#include<stdio.h>
#include<conio.h>
#define NULL 0
void main()
{
struct supplier
{
int supplier_id;
char supplier_name[20];
char address[20];
};
struct item
{
int item_id;
int supplier_id;
char item_name[20];
int qty;
};
struct supplier s;
struct item i;
FILE *fs, *fi;
char ch;
clrscr();
fs = fopen("supplier.dat", "w+");
fi = fopen("item.dat", "w+");
if(fs == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
{
printf("Enter supplier information:\n");
do
{
printf("Enter supplier id:");
scanf("%d", &s.supplier_id);
printf("Enter supplier name:");
scanf(" %[^\n]", s.supplier_name);
printf("Enter address:");
scanf(" %[^\n]", s.address);
fwrite(&s,sizeof(struct supplier),1,fs);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
}
if(fi == NULL)
printf("\nERROR - Cannot open the destination file\n");
else
53
{
printf("Enter item information:\n");
do
{
printf("Enter item id:");
scanf("%d", &i.item_id);
printf("Enter supplier id:");
scanf("%d", &i.supplier_id);
printf("Enter item name:");
scanf(" %[^\n]", i.item_name);
printf("Enter quantity:");
scanf("%d", &i.qty);
fwrite(&i,sizeof(struct item),1,fi);
printf("Do you wnat to add another record?(y/n)");
scanf(" %c",&ch);
} while(ch != 'n');
}
getch();
}
54