C Programming Laboratory (13MCA16) : 1 Prepared by Prof. Suma M.G., Asst. Professor - RNSIT, Bangalore
C Programming Laboratory (13MCA16) : 1 Prepared by Prof. Suma M.G., Asst. Professor - RNSIT, Bangalore
I.A. Marks:
1.
Exam Marks: 50
Exam Hours: 3
The Process:
This Program converts the Temperature from Celsius to Fahrenheit and vice
versa. Mind you, the formula for the conversion
Celsius to Fahrenheit
Use the following formula to convert Celsius degree into the Fahrenheit
reading:
Fahrenheit to Celsius
Use the following formula to convert Fahrenheit degree into the Celsius
reading:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
float fd,cd;
clrscr();
printf("Enter a temperature in celsius\n");
scanf("%f",&cd);
fd=(float)9/5 * cd+32;
printf("Converted value from celsius to fahrenheit = %.3f",fd);
cd=(float)5/9*(fd-32);
printf("\n\nConverted value from fahrenheit to celsius = %.3f",cd);
getch();
}
Output:
1.
b) Calculate the salary of an employee given his basic pay, HRA = 10% of basic pay, TA = 5% of his
basic pay and
deductions IT = 2.5% of his basic pay.
The Process:
HRA
TA
GRS
IT
Netsalary
=
=
=
=
=
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
float hra,ta,d_it,bs,netsal,grs;
clrscr();
printf("enter the basic salary\n");
scanf("%f",&bs);
if(bs<=0.0)
{
printf("You entered wrong basic salary");
getch();
exit(0);
}
hra=(float)10/100*bs;
ta=(float)5/100*bs;
grs=bs+hra+ta;
d_it=(2.5/100)*bs;
netsal=grs-d_it;
printf("HRA\tTA\tGRS\tITDeduction\tNetSalary\n");
printf("---------------------------------------------\n");
printf("%.2f\t%.2f\t%.2f\t%.2f\t%.2f",hra,ta,grs,d_it,netsal);
getch();
}
Output:
2.
The Process:
2, 3.
1+2+3=6.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,sum=0;
clrscr();
printf("Enter a number:\n");
scanf("%d",&n);
if(n<=0)
{
printf("Wrong Input!\n");
getch();
exit(0);
}
printf("The Numbers:\n");
while(i<n)
{
if(n%i == 0)
{
sum=sum+i;
//printf("%d\n",i);
}
i++;
}
if(sum==n)
printf("The number %d is PERFECT\n",n);
else
printf("The number %d is NOT PERFECT\n",n);
}
getch();
Output:
Enter a number:
6
1
2
3
The number 6 is PERFECT
Enter a number:
5
1
The number 5 is NOT PERFECT
2. b) Write a program to find the roots of a quadratic equation with appropriate error messages.
The Process:
Every Quadratic equation has two roots. And this program is implemented to
find the roots of the entered quadratic equation.
Logic : The roots of any quadratic equation of the form,
are,
4
The same equation is computerized here. The program asks user to enter the
three coefficients a, b and c. Then it finds out numerator- which is the
discriminate, and the denominator of the equation of the roots. Then it
checks if the numerator is greater, equals or less than zero. Prints out
the results according to the situation.
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, desc,r1,r2,real,img;
clrscr();
printf("Enter the values of a,b,c:\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("\nEquation is linear and has only one root. ");
printf("\nAnd the root is %5.2f", -c/b);
getch();
return;
}
else
{
desc=b*b-4*a*c;
if(desc==0)
{
r1=-b/(2*a);
r2=-b/(2*a);
printf("\nThe roots are real and equal");
printf("\n r1 = %5.2f \t r2 = %5.2f",r1,r2);
getch();
return;
}
else if(desc>0)
{
r1=(-b+sqrt(desc))/(2*a);
r2=(-b-sqrt(desc))/(2*a);
printf("\nThe roots are real and distinct");
printf("\n r1=%5.2f\t r2=%5.2f",r1,r2);
getch();
return;
}
else
{
real=-b/(2*a);
img=sqrt(-desc)/(2*a);
printf("\nThe roots are imaginary");
printf("\n r1 = %5.2f + %5.2f i\n",real,img);
printf(" r2 = %5.2f - %5.2f i",real,img);
getch();
return;
5
}
}
Output:
3.
An Armstrong number of three digits is an integer such that the sum of the
cubes of its digits is equal to the number itself.
Example -
371
is an Armstrong number
since 33
+ 73 + 13 = 371
Program:
#include<stdio.h>
#include<conio.h>
void main()
6
int armstr=0,n,rem,t;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
t=n;
if(n<=0 || n<=99 || n>999)
{
printf("Entered value is out of range!\n");
getch();
exit(0);
}
while(n>0)
{
rem = n%10;
armstr = armstr+rem*rem*rem;
n = n/10;
}
if(t==armstr)
printf("The number %d is ArmStrong\n",t);
else
printf("The number %d is Not ArmStrong\n",t);
getch();
}
Output:
3.
Not ArmStrong
The Process:
1. Divide the "desired" base (in this case base 16) INTO the number you are
trying to convert.
2. Write the quotient (the answer) with a remainder
3. Repeat this division process using the whole number from the previous
quotient (the number in front of the remainder).
4. Continue repeating this
remainder is only zero.
division
until
the
number
in
Example:
12310 = 7B16
(a Hexadecimal Conversion)
Program:
front
of
the
4.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],n,i,j,ch,key,pos,flag;
clrscr();
printf("Enter the array size:\n");
scanf("%d",&n);
printf("Enter the array elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(;;)
8
printf("%d\t",a[i]);
}
break;
case 4:
exit(0);
default:
printf("Wrong Input:\n");
Output:
30
5.
The Process:
Encoding
#include<stdio.h>
#include<conio.h>
void main()
11
char str[50];
int i,ch,key,flag=0;
clrscr();
for(;;)
{
printf("\n1. Accept\n2. Encode\n3. Decode\n4. Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
break;
case 3:
if(flag==2)
{
printf("\nString after DECODED:");
textbackground(CYAN);
textcolor(RED+BLINK);
for(i=0;str[i]!='\0';i++)
str[i]=str[i]-key;
}
else
}
}
cprintf("%s",str);
Output:
1.
2.
3.
4.
Accept
Encode
Decode
Exit
12
Accept
Encode
Decode
Exit
6.
Write a C program to multiply two matrices that satisfy the constraint of matrix multiplication.
The Process:
You can multiply two matrices if, and only if, the number of columns in the
first matrix equals the number of rows in the second matrix. Otherwise, the
product of two matrices is undefined.
The product matrix's dimensions are
Example:
Make sure that the number of columns in the 1st one equals the number
of rows in the 2nd one.
Step 2: Multiply the elements of each row of the first matrix by the elements
of each column in the second matrix.
Step 3:
below.
ii.
iii.
iv.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int m,n,p,q,i,j,k;
int a[10][10],b[10][10],c[10][10];
clrscr();
printf("enter the size of the matrix A \n");
scanf("%d%d",&m,&n);
printf("Enter the size of the matrix B\n");
scanf("%d%d",&p,&q);
// check whether multiplication is possible or Not
if(n != p)
{
printf("Multiplication is not possible \n");
getch();
exit(0);
}
printf("\nEnter the elements of matrix A\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the elements of matrix B \n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
// multiply A and B
14
15
7.
The Process:
A saddle point is a position in the payoff matrix where the maximum of row
minima coincides with the minimum of column maxima. The payoff at the saddle
point is called the value of the game point and is denoted by
Where, v is called the value of the game. In this case, there exist optimal
strategies for the first and second players.
A necessary and sufficient condition for a saddle point to exist is the
presence of a payoff matrix element which is both a minimum of its row and a
maximum of its column. A game may have more than one saddle point, but all
must have the same value.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],rowmin[5],colmax[5],min,max,i,j,r,c;
clrscr();
printf("Enter the row and column:\n");
scanf("%d%d",&r,&c);
if(r!=c)
{
printf("Row and Column should equal!\n");
16
}
printf("Rowmin= %d\n",rowmin[i]);
}
for(j=0;j<c;j++)
{
colmax[j]=a[0][j];
for(i=0;i<r;i++)
{
if(a[i][j]>colmax[j])
colmax[j]=a[i][j];
}
printf("Colmax=%d\n",colmax[j]);
}
max=rowmin[0];
for(i=0;i<r;i++)
{
if(rowmin[i]>max)
max=rowmin[i];
}
printf("MAX= %d\n",max);
min=colmax[0];
for(j=0;j<r;j++)
{
if(colmax[j]<min)
min=colmax[j];
}
printf("MIN= %d\n",min);
17
if(max==min)
printf("The saddle point exists and the value of the game is
%d",max);
else
printf("There is no saddle point");
getch();
Output:
18
8.
The Process:
A magic square is an arrangement of numbers (usually integers) in a square
grid, where the numbers in each row, and in each column, and the numbers in
the forward and backward main diagonals, all add up to the same number. A
magic square has the same number of rows as it has columns, and in
conventional math notation, "n" stands for the number of rows (and columns)
it has. Thus, a magic square always contains n2 numbers, and its size (the
number of rows [and columns] it has) is described as being "of order n".
A magic square that contains the integers from 1 to n 2 is called a normal
magic square. It is possible to construct a normal magic square of any size
except 2 2 (that is, where n = 2), although the solution to a magic square
where n = 1 is trivial, since it consists simply of a single cell containing
the number 1. The smallest nontrivial case, shown below, is a 3 3 grid.
The constant that is the sum of every row, column and diagonal is called the
magic constant or magic sum, M. Every normal magic square has a unique
constant determined only by the value of n, which can be calculated using
this formula:
Program:
#include<stdio.h>
#include<conio.h>
void main()
19
int a[5][5],i,j,m,n,pri_diag=0,rowsum,colsum,sec_diag=0,magicSum=0;
clrscr();
printf("Enter the size of matrix:\n");
scanf("%d",&n);
if(n<=2)
{
printf("Magic Square not possible\n");
getch();
exit(0);
}
magicSum=(n*(n*n+1))/2;
printf("Enter the matrix elements:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
//Calculation for magic square matrix
for(i=0;i<n;i++)
{
rowsum=0,colsum=0;
for(j=0;j<n;j++)
{
rowsum=rowsum+a[i][j];
colsum=colsum+a[j][i];
if(i==j)
pri_diag=pri_diag+a[i][j];
}
printf("\n%d Row sum= %d\n",i+1,rowsum);
printf("\n%d Col sum= %d\n",i+1,colsum);
}
printf("\npri_diag=%d",pri_diag);
//calculation for rev pri_diag
for(i=0,j=n-1;i<n;i++,j--)
sec_diag=sec_diag+a[i][j];
printf("\nSecondary Diagonal is= %d",sec_diag);
printf("\nRequired magic sum is= %d", magicSum);
if(magicSum==rowsum && magicSum==colsum && magicSum==pri_diag &&
magicSum==sec_diag)
printf("\nEntered matrix is Magic Square\n");
else
printf("\nEntered matrix is Not Magic Square\n");
20
getch();
Output:
Enter the size of matrix:
3
Enter the matrix elements:
2
7
6
9
5
1
4
3
8
The matrix is:
2 7 6
9 5 1
4 3 8
1 Row sum= 15
1 Col sum= 15
2 Row sum= 15
2 Col sum= 15
3 Row sum= 15
3 Col sum= 15
pri_diag=15
Secondary Diagonal is= 15
Required magic sum is= 15
Entered matrix is Magic Square
21
3.
e.
f.
a.
b.
c.
d.
e.
The Process:
Program:
#include<stdio.h>
#include<conio.h>
void
void
void
void
accept();
sumofall(int,int);
sumofeven(int,int);
sumofodd(int,int);
int n,m;
void main()
{
int flag=0;
char op;
clrscr();
for(;;)
{
printf("\na.Accept\nb.Sum of all Integer\nc.Sum of all odd\n
d.Sum of even\ne. Exit\n");
printf("Enter your choice:");
fflush(stdin);
op=getchar();
clrscr();
switch(op)
{
case 'a':
22
accept();
flag=1;
break;
case 'b': if(flag==0)
printf("No Inputs!\n");
else
sumofall(n,m);
break;
case 'c': if(flag==0)
printf("No Inputs!\n");
else
sumofeven(n,m);
break;
case 'd': if(flag==0)
printf("No Inputs!\n");
else
sumofodd(n,m);
break;
case 'e': exit(0);
default: printf("Invalid option\n");
}
}
void accept()
{
9.
The Process:
a. In mathematics, the factorial of a non-negative integer n, denoted by n!,
is the product of all positive integers less than or equal to n.
For example,
The factorial function is
recursively defined by
b. Fibonacci numbers are the numbers fall on the Fibonacci series, which grows
up accord to Fibonacci rule.
The rule is, the present number in the series is the sum of past
number and the number before last. The series starts from 0 & the 2nd term
is 1. Now all other elements are generated using this rule:
Fn = Fn-1 + Fn-2
Example: 0 1 1 2 3 5 8 13 21 34 55 89 ...
Program:
#include<stdio.h>
#include<conio.h>
int fact(int);
int fibo(int);
void main()
{
int n,res,i,f=0;
char op;
clrscr();
printf("Enter the series\n");
scanf("%d", &n);
if(n<0)
{
printf("Invalid Input");
getch();
return;
}
23
}
}
res = fact(n);
printf("The Factorial of %d is: %d",n,res);
break;
case 'b': printf("The Fibonacci Series:\n");
for(i=1;i<=n;i++)
{
printf("%d\t",fibo(f));
f++;
}
break;
case 'e': exit(0);
default:
printf("Invalid Choice!\n");
120
a.Factorial
24
10. Create a structure Complex Number having real and imaginary part as properties. Write functions to
add and subtract the two complex numbers.
The Process:
Complex a + bi where a and b are real numbers and i is the square root of 1.
These programs calculate the sum of two complex numbers which will be entered
by the user and then printed their sum. User will have to enter the real and
imaginary parts of two complex numbers. Then on our program we will add real
parts and imaginary parts of complex numbers and then we add them and prints
the complex number, i is the symbol.
For example: If user entered two complex numbers as (1 + 2i) and (4 + 6i) then
output of program will be (5+8i).
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
struct comp
{
float real;
float img;
};
typedef struct comp complex;
complex add_complex(complex x1, complex x2)
{
complex z;
z.real=x1.real + x2.real;
z.img=x1.img + x2.img;
return z;
}
complex sub_complex(complex x1, complex x2)
{
complex z;
z.real=x1.real - x2.real;
z.img=x1.img - x2.img;
return z;
}
void show(complex z)
{
if(z.img>0)
printf("%5.2f + %5.2fi", z.real,z.img);
else
printf("%5.2f - %5.2fi", z.real,fabs(z.img));
}
void main()
25
complex x1,x2,z1,z2;
clrscr();
printf("Enter
scanf("%f%f",
printf("Enter
scanf("%f%f",
z1=add_complex(x1,x2);
printf("Sum of two complex numbers:");
show(z1);
z2=sub_complex(x1,x2);
printf("\nSubtract of two complex numbers: ");
show(z2);
getch();
Output:
Enter the value for first complex number
2
3
Enter the value for second complex number
3
2
Sum of two complex numbers: 5.00 + 5.00i
Subtract of two complex numbers: -1.00 + 1.00i
26
Program:
#include<stdio.h>
#include<conio.h>
struct student
{
int id;
char name[15];
char branch[4];
int total;
struct marks
{
int m1;
int m2;
int m3;
}mar;
}std[10],temp;
void main()
{
int i,j,n,ch,key,flag=0,sum=0;
float avg=0.0;
clrscr();
printf("Enter the number of student:\n");
scanf("%d",&n);
for(;;)
{
printf("1.Add new Student\n2.Delete a Student\n");
printf("3.Display the Student\n4.Best & Worst Marks list");
printf("\n5.Average Marks list\n6.Exit\n");
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
27
for(i=0;i<n;i++)
{
printf("Enter the student id: ");
scanf("%d",&std[i].id);
printf("Enter the student name: ");
fflush(stdin);
gets(std[i].name);
printf("Enter the student branch");
fflush(stdin);
gets(std[i].branch);
printf("Enter the three subject
marks:\n");
scanf("%d%d%d",&std[i].mar.m1,
}
break;
case 2:
if(n==0)
{
printf("No Records\n");
getch();
break;
}
else
{
flag=0;
printf("Enter the id for deleting the
record: ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(std[i].id==key)
{
sum=sum-std[i].total;
for(j=i;j<n-1;j++)
{
std[j]=std[j+1];
}
n--;
flag=1;
break;
}
}
if(flag==0)
printf("The entered ID %d is Not
found!\n",key);
else
printf("The Record %d is deleted\n
", key);
}
break;
case 3:
if(n==0)
{
printf("No Records\n");
getch();
break;
}
else
{
printf("The student details are:\n");
printf("---------------------------------------------------------\n");
printf("Std_Id\tStd_Name\tStd_Branch\t
Std_Marks\t Total\n");
printf("---------------------------------------------------------\n");
28
}
break;
case 4: //For sort the records based on struc elements.
if(n==0)
{
printf("No Records\n");
getch();
break;
}
else
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(std[j].total>std[j+1].total)
{
temp=std[j];
std[j]=std[j+1];
std[j+1]=temp;
}
}
}
printf("The Best Student: %s\n The Worst
Student: %s\n",std[n-1].name,std[0].name);
}
break;
}
}
case 5: if(n==0)
{
printf("No Records\n");
getch();
break;
}
else
{
avg=(float)sum/n;
printf("The average marks scored by the
student is: %f\n",avg);
}
break;
case 6:exit(0);
default:
printf("Wrong Choice!!");
break;
Output:
Enter the number of student:
2
1.Add new Student
29
12. a) Write a C Program to remove all white spaces and newline characters from a file.
The Process:
What is whitespace?
..
..
..
30
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch,fname[100];
clrscr();
printf("Enter the filename:\n");
gets(fname);
fp1=fopen(fname,"r");
if(fp1==NULL)
{
printf("\nError: Unable to open file %s\n",fname);
getch();
exit(0);
}
fp2=fopen("res.txt","w+");
while((ch=fgetc(fp1))!=EOF)
{
if(ch!=' ' && ch!='\n' && ch!='\t')
{
fputc(ch,fp2);
}
}
printf("All white spaces and newline characters are removed
successfully:\n");
fclose(fp1);
fclose(fp2);
getch();
}
Output:
Enter the filename:
pgm1a.c
Error: Unable to open file pgm1a.c
Enter the filename:
Hello.c
All white spaces and newline characters are removed successfully:
13. b) Find a given word in a file if it exists and also show the location of that word in a file.
The Process:
31
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
FILE *fp;
char fname[15],str[10],temp[10],temp1[10];
int flag=0,pos=0,len,i,j=0;
clrscr();
printf("Enter the File name:");
gets(fname);
fp=fopen(fname,"r");
if(fp == NULL)
{
printf("\nSORRY, The source file does not exist");
getch();
exit(0);
}
printf("Enter the word for search:\n");
gets(str);
while(!feof(fp))
{
j=0;
fscanf(fp,"%s",temp);
puts(temp);
len=strlen(temp);
pos=pos+(len+1);
for(i=0;i<strlen(temp);i++)
{
if(ispunct(temp[i]))break;
else
temp1[j]=temp[i];
j++;
}
temp1[j]='\0';
if(strcmp(str,temp1)==0)
{
flag=1;
break;
}
if(flag==1)
printf("\nThe %s Word found at %d position\n",temp1,pos-len);
else
printf("Word Not found\n");
fclose(fp);
32
getch();
Output:
14. Copy one file content to another file without using inbuilt function
The Process:
Program:
#include<stdio.h>
#include<conio.h>
void main()
33
FILE *fp1,*fp2;
char srcf[15],destf[15],ch;
clrscr();
printf("\nEnter the filename:");
gets(srcf);
fp1=fopen(srcf,"r");
if(fp1==NULL)
{
printf("ERROR: Unable to open file\n");
getch();
exit(0);
}
printf("Source file %s exists",srcf);
printf("\nEnter the filename:");
gets(destf);
fp2=fopen(destf,"w");
while((ch=getc(fp1))!=EOF)
putc(ch,fp2);
printf("The %s file is copied successfully to %s",srcf,destf);
getch();
}
Output:
Enter the filename:hello.c
Source file hello.c exists
Enter the filename:res.txt
The hello.c file is copied successfully to res.txt
34