55
Exercise 1: Solving problems such as temperature conversion, student grading, income tax calculation, etc., which expose students to use basic C operators Temperature conversion Algorithm: Step1: start Step2: read Fahrenheit value Step3: c=f-32*5/9 Step4: print/write c Step5: stop Program: #include<stdio.h> main( ) { float f, c; clrscr( ); printf(“enter Fahrenheit value”); scanf(“%f”,&f); c=f-32*5/9; printf(“centigrade value is %f”,c); getch( ); } Student grading Algorithm : Step1:start Step2:read marks of the student m1,m2,m3…… step3: if m1>30 and m2>30 and m3>30……

C Programming Lab Manual

Embed Size (px)

Citation preview

Page 1: C Programming Lab Manual

Exercise 1:

Solving problems such as temperature conversion, student grading, income tax calculation, etc., which expose students to use basic C operators

Temperature conversion

Algorithm:Step1: startStep2: read Fahrenheit valueStep3: c=f-32*5/9Step4: print/write cStep5: stop

Program:#include<stdio.h>main( ) { float f, c; clrscr( ); printf(“enter Fahrenheit value”); scanf(“%f”,&f); c=f-32*5/9; printf(“centigrade value is %f”,c); getch( ); }

Student grading

Algorithm:

Step1:startStep2:read marks of the student m1,m2,m3……step3: if m1>30 and m2>30 and m3>30……Step4:add the marks of the student m=m1+m2+m3…..Step5:find the percentage of the marks p=(m/(n*100))*100Step6:if percentage is in between 70 to 100 p<=100 && p>=70Step7:print / write first class

Page 2: C Programming Lab Manual

Step8:if percentage is in between 50 to 69 p<=69 && p>=50Step9:write second classStep10:if percentage 40 to 49 p<=49 && p>=40Step11:write third classStep12:if percentage <40Step13:passStep14:stop

Program:

#include<stdio.h>#include<conio.h>main( ){ int m1,m2,m3; float sum=0,p; clrscr( ); printf(“enter marks for 3 subjects”); scanf(“%d%d%d”,&m1,&m2,&m3); if(m1>30 && m2>30 && m3>30) { sum=m1+m2+m3; p=sum/300*100; if(p<=100 && p>=70) printf(“first class”); if(p<=69 && p>=50) printf(“second class”); if(p<=49 && p>=40) printf(“third class”); if(p>40) printf(“pass”); } else printf(“fail”);}

Page 3: C Programming Lab Manual

Exercise 2

2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C program to find the 2’s complement of a binary number.

Algorithm:Step1:startStep2:read binary valueStep3:if binary value is 1 Step4:if next value is 1 change to 0Step5:if next value is 0 change to 1Step6:stop

Program:

#include<stdio.h>#include<conio.h>main(){int a[20],n,i,count=0,j,k,l;clrscr();printf("enter number of digits in binary value");scanf("%d",&n);for(i=0;i<n;i++){scanf("%d",&a[i]);}printf("before 2's compliment ");for(l=0;l<n;l++){printf("%d",a[l]);}for(j=n;j>0;j--){if(a[j]==1)count++;if(count>=1){if(a[j-1]==0)

Page 4: C Programming Lab Manual

a[j-1]=1;elsea[j-1]=0;}}printf("\nafter 2's complement ");for(k=0;k<n;k++){printf("%d",a[k]);}getch();}

Exercise 3

a) Write a C program to find the sum of individual digits of a positive integer. b) A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.c) Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user.d) Write a program which checks a given integer is Fibonacci number or not.

a) Algorithm:

Step1:startStep2:read n value, assign sum=0Step3:while n>0Step4:r=n%10Step5:sum=sum+rStep6: n=n/10Step7:print/write sumStep8:stop

Program:

#include<stdio.h>#include<conio.h>main()

Page 5: C Programming Lab Manual

{int n,sum=0,r;clrscr();printf("enter n value");scanf("%d",&n);while(n>0) { r=n%10; sum=sum+r; n=n/10; }printf("%d",sum);getch();}

b)

Algorithm:

Step1:startStep2:read n valueStep3:f1=0,f2=1Step4: for i=0 to nStep5:f3=f1+f2Step6:print f3Step7:f1=f2Step8:f2=f3Step9:print f3Step10:stop

Program:

#include<stdio.h>void main(){int i,f1=0,f2=1,f3,n;clrscr();printf("enter n value");scanf("%d",&n);printf("\n %d \n %d",f1,f2);

Page 6: C Programming Lab Manual

for(i=3;i<=n;i++){f3=f1+f2;f1=f2;f2=f3;printf("\n %d",f3);}getch();}

c)

Algorithm:

Step1:startStep2:enter n valueStep3:for i=0 to nStep4:count=0Step6:if i%0Step5:for j=1j=0Step7:count=count+1Step8:if count<=2Step9:print iStep10:stop

Program:

#include<stdio.h>#include<conio.h>main( ){int i,j,n,count;clrscr( );printf("enter the range of numbers:");scanf("%d",&n);printf("enter the prime no. are:");for(i=0;i<=n;i++){ count=0; for(j=1;j<=i;j++)

Page 7: C Programming Lab Manual

{ if(i%j==0) count++; } if(count==2) printf("%d",i); } getch();}

d)

Algorithm:

Step1:startStep2:read n valueStep3:f1=0,f2=1Step4:for i 0 to nStep5:f3=f1+f2Step6:if f3=nStep7:Count+1Step8:f1=f2,f2=f3Step9:if count=1 Print Fibonacci numberStep10:if count!=1 Print not a Fibonacci number

Program:

#include<stdio.h>void main(){int n,count=0,f1=0,f2=1,f3,i;clrscr();printf("enter n value");scanf("%d",&n);for(i=0;i<n;i++){f3=f1+f2;if(f3==n)

Page 8: C Programming Lab Manual

{count++;break;}f1=f2;f2=f3;}if(count==1)printf("%d is fibinacci number",n);elseprintf("%d is not fibonacci number",n);getch();}

Exercise 4

a) Write a C program to calculate the following Sum:Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

b) Write a C program to find the roots of a quadratic equation.

a)

Algorithm:

Step1:startStep2:enter x valueStep3:for count ,power 0 to 10Step4:fact=1Step5:for fcoun power to 1Step6: fact =fact* fcoun;Step7:sum=sum+(-1)counter * xpower /fact

Step8:print sumStep9:stopProgram:

#include <stdio.h>#include <math.h>void main(){

Page 9: C Programming Lab Manual

int counter,f_coun;float sum=0,x,power,fact;clrscr();

printf("<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->");printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!");

printf("\n\n\n\tENTER VALUE OF X : ");scanf("%f",&x);

for(counter=0, power=0; power<=10; counter++,power=power+2){fact=1;//CALC FACTORIAL OF POWER VALUEfor(fcoun=power; fcoun>=1; fcoun--) fact *= fcoun;//EQ. FOR SUM SERIESsum=sum+(pow(-1,counter)*(pow(x,power)/fact));}printf("SUM : %f",sum);getch();}

b)Algorithm:Step1:startStep2:enter a ,b,cStep3:d=b*b-4*a*cStep4:if d>0Step5:r1=-b+sqrt(b*b-4*a*c)/(2*a)Step6:r2=-b-sqrt(b*b-4*a*c)/(2*a)Step7:print r1,r2Step8:if d=0Step9:r1=r2=-b/2*aStep10:if d<0Step11:print imaginary rootsStep12:stop

Page 10: C Programming Lab Manual

Program:

#include<stdio.h>main(){float a,b,c,r1,r2;int d;clrscr();printf("enter a,b,c values");scanf("%f%f%f",&a,&b,&c);d=b*b-4*a*c;if(d>0){r1=-b+sqrt(b*b-4*a*c)/(2*a);r2=-b-sqrt(b*b-4*a*c)/(2*a);printf("roots are \n");printf("\n r1=%f",r1);printf("\n r2=%f",r2);}else if(d==0){r1=r2=-b/(2*a);printf("roots are \n");printf("\n r1=%f",r1);printf("\n r2=%f",r2);}elseprintf("\n roots are imaginary");getch();}

Exercise 5

a) The total distance travelled by vehicle in‘t’ seconds is given by distance = ut+1/2at2

where ‘u’ and ‘a’ are the initial velocity (m/sec.) and acceleration (m/sec2). Write C program to find the distance travelled at regular intervals of time given the values of ‘u’ and ‘a’. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of ‘u’ and ‘a’.

Page 11: C Programming Lab Manual

b) Write a C program, which takes two integer operands and one operator form the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement)a)

Algorithm:Step1:startStep2:read number of time intervalsStep3:for counter 1 to time intervalStep4:read time, velocity ,accelerationStep5: distance = velocity*time + (acceleration*time*time)/2Step6:stop

Program:

#include <stdio.h>#include <math.h>void main(){int tim_intrval, counter,time;float accl, distance=0, velos;clrscr();printf("<===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>");printf("\n\n\n\t\t\tNO OF TIME INTERVALS : ");scanf("%d",&tim_intrval);

for(counter = 1; counter <= tim_intrval; counter++){ printf("\n\t\t\tAT T%d TIME(sec) : ",counter); scanf("%d",&time); printf("\t\t\tVELOCITY AT %d sec (m/sec) : ",time); scanf("%f",&velos); printf("\t\t\tACCLERATION AT %d sec (m/sec^2): ",time); scanf("%f",&accl);

distance = (velos*time + (accl*pow(time,2))/2);}

printf("\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF TIME : %f",tim_intrval,distance);

Page 12: C Programming Lab Manual

getch();}

b)

Algorithm:

Step1:startStep2:read a,b values and read one operatorStep3: case +: c=a+b addition is performed ,print cStep4: case -: c=a-b subtraction is performed ,print cStep5:case *: c=a*b multiplication is performed ,print cStep6:case %: c=a%b modulus is performed ,print cStep7:case /: c=a/b division is performed ,print cStep8:stop

Program:

#include<stdio.h> #include<conio.h>main( ) {float a,b,c;int c1;char op;clrscr( );printf("enter a,b,op values");scanf("%f%f",&a,&b);op=getche( );switch(op){ case '+':

c=a+b;printf("addition value is %f",c);break;

case '-':c=a-b;printf("subtraction value is %f",c);break;

case '*':

Page 13: C Programming Lab Manual

c=a*b;printf("multiplication value is %f",c);break;

case '%':c1=(int)a%(int)b;printf("remainder value is %d",c1);break;

case '/': c=a/b; printf("division value is %f",c); break;

default: printf("not valid"); break; }getch( );}

Exercise 6

a) Simple programming examples to manipulate strings. b) Verifying a string for its palindrome property

Algorithm:

step1:startstep2:read two strings string1,string2step3:read n valuestep4: case1:concat two strings print stringstep5: case2:compare two strings print the valuestep6: case3:copy the string2 to string1 print the string1 step7: case 4:length of the string print the lengthstep8: case 0:exitstep9: stop

Page 14: C Programming Lab Manual

Program:

#include<stdio.h>#include<string.h>main(){int i,c;char string1[50],string2[50],string3[50];clrscr();printf("\n1.string concatination \n2.compare the strings \n3.copy the string \n 4.find the length of the string \n 0.exit\n" );printf("\n enter your choice");scanf("%d",&i);switch(i){case 1: printf("enter two strings"); scanf("%s%s",&string1,&string2); strcat(string1,string2); printf("%s",string1); break;case 2: printf("enter two strings"); scanf("%s%s",&string1,&string2); c=strcmp(string1,string2); printf("%d",c); break;case 3: printf("enter two strings"); scanf("%s%s",&string1,&string2); strcpy(string1,string2); printf("%s",string1); break;case 4: printf("enter the string"); scanf("%s",string1); c=strlen(string1);

Page 15: C Programming Lab Manual

printf("%d",c); break;case 0:

exit(0);}

getch();}

b)

Algorithm:

step1:startstep2:read the string string1step3:find the reverse of the string string2step4:if string1 is equal to string2step5:print string1 is palidrome or notstep6:stop

Program:

#include<stdio.h>#include<string.h>

enum Boolean{false,true};enum Boolean IsPalindrome(char string[]){ int left,right,len=strlen(string); enum Boolean matched=true; if(len==0) return 0; left=0; right=len-1;

/* Compare the first and last letter,second & second last & so on */ while(left<right&&matched) { if(string[left]!=string[right]) matched=false;

Page 16: C Programming Lab Manual

else { left++; right--; } } return matched; }

int main(){ char string[40]; clrscr(); printf("****Program to test if the given string is a palindrome****\n"); printf("Enter a string:"); scanf("%s",string); if(IsPalindrome(string)) printf("The given string %s is a palindrome\n",string); else printf("The given string %s is not a palindrome\n",string); getch(); return 0;}

Exercise 7

Write a C program that uses functions to perform the following operations:i. To insert a sub-string in to given main string from a given position.

ii. To delete n Characters from a given position in a given string.iii. To replace a character of string either from beginning or ending or at a

specified location

Algorithm:

1. start2. Read strings first and second.3. do 4. begin5. if u select one of them.6. i.1 means insert string

Page 17: C Programming Lab Manual

7. ii. 2 means delete string.8. iii.3 means replacing character9. read integer value10.switch 11.Begin12.case 1:13.Call insert function14.Break;15.Case 2:16.Call delete function17.Break;18.Case 3:19.Call replacing character function20.Default:21.Invalid choice22.If u want to continue read character23.End of while loop24.Stop.25.Procedure for insert function26.initialize i=027.read position value for where insert substring into main string28.while i<pos29.begin30.c[i]=first[i];31.i++;32.end of while33.for j=0 to ending of second string34.c[i++]=second[j];35.for j=pos to ending of first string36.c[i]=first[j];37.print string c

procedure for delete function

Page 18: C Programming Lab Manual

38.Initailize i=0;39.Calculating string length of second string40.While i<0 to position41.C[i]=second[i];42.i++;43.end of while44.for j=(position+n) to m45.c[i++]=second[j];46.c[i]=’\0’;47.print string c

procedure for replacing character function

48.read position ,character49.first[position]=character50.print string c

Program:

#include<stdio.h>#include<conio.h>#include<string.h>void main(){int n,q,j,pos;char first[20],second[20];char ch;clrscr();printf("enter first string");gets(first);printf("enter second string");gets(second);do{printf("if u choose one of them ");printf("1.insert substring\n2.delete character\n3.replacing character");scanf("%d",&q);switch(q)

Page 19: C Programming Lab Manual

{case 1:

insert(first,second);break;case 2:

delete(second);break;case 3:replace(first);

break;}printf("u want to continue (y/n):");ch=getche();}while(ch=='y');getch();

}insert(char *first,char *second){int m,q,i,j,pos;char c[20];i=0;printf("enter given position");scanf("%d",&pos);m=strlen(second);q=strlen(first);while(i<pos){c[i]=first[i];i++;}c[i]='\0';for(j=0;second[j]!='\0';j++)c[i++]=second[j];for(m=pos;m<q;m++)

c[i++]=first[m];

Page 20: C Programming Lab Manual

c[i]='\0';puts(c);

}delete(char *second){int i,m,j,pos,n;char c[20];printf("enter where position to delete from string");scanf("%d",&pos);printf("enter how many characters to delete");scanf("%d",&n);

i=0;m=strlen(second);while(i<pos){c[i]=second[i]; i++; } for(j=(pos+n);j<m;j++) c[i++]=second[j]; c[i]='\0'; puts(c);

}

replace(char *first){int n;char ch;printf("enter position for repalcement");scanf("%d",&n);printf("enter replacing character");ch=getche(); first[strlen(first)+1]='\0'; first[n]=ch; printf("\n");puts(first);}

Page 21: C Programming Lab Manual

Exercise 8

Write a C program that uses functions to perform the following operations using Structure:

i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers

Algorithm:

1. Start2. Call procedure Read_complex_numbers()3. Call procedure write_complex_numbers()4. Call procedure Add_complex_numbers()5. Call procedure Multiply_complex_numbers()6. Stop

Algorithm for Read Complex numbers

1. Start2. Read real part and inmaginary part of first complex number3. Read real part and inmaginary part of Second complex number4. Stop

Algorithm for Write Complex numbers

1. Start2. Write real part and inmaginary part of first complex number3. Write real part and inmaginary part of Second complex number4. Stop

Algorithm for Add Complex numbers

1. Start2. Result.real_part=number1.real_part +number2.real_part3. Result.imaginary_part=number1.imaginary_part +number2.imaginary_part4. Stop

Page 22: C Programming Lab Manual

Algorithm for Write Complex numbers

1. Start2. Result.real_part=(number1.real_part *number2.real_part) – (number1.imaginary_part *number2.imaginary_part) 3. Result.imaginary_part=(number1.real_part *number2.imaginary_part) + (number2.real_part *number1.imaginary_part)4.Stop

Program:

#include<stdio.h>#include<math.h>

void arithmetic(int opern);

struct comp{ double realpart; double imgpart;};

void main(){ int opern; clrscr(); printf("\n\n \t\t\t***** MAIN MENU *****"); printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 0 : EXIT \n\n\t\t Enter your Option [ ]\b\b");

scanf("%d",&opern);

switch(opern) {

case 0: exit(0); case 1:

Page 23: C Programming Lab Manual

case 2: arithmetic(opern); default: main();

}

}

void arithmetic(int opern){

struct comp w1, w2, w;

printf("\n Enter two Complex Numbers (x+iy):\n Real Part of First Number:"); scanf("%lf",&w1.realpart); printf("\n Imaginary Part of First Number:"); scanf("%lf",&w1.imgpart); printf("\n Real Part of Second Number:"); scanf("%lf",&w2.realpart); printf("\n Imaginary Part of Second Number:"); scanf("%lf",&w2.imgpart); switch(opern) { /*addition of complex number*/ case 1:

w.realpart = w1.realpart+w2.realpart; w.imgpart = w1.imgpart+w2.imgpart; break;

/*multiplication of complex number*/ case 2:

w.realpart=(w1.realpart*w2.realpart)-(w1.imgpart*w2.imgpart); w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart); break;

} if (w.imgpart>0)

printf("\n Answer = %lf+%lfi",w.realpart,w.imgpart); else

printf("\n Answer = %lf%lfi",w.realpart,w.imgpart);

Page 24: C Programming Lab Manual

getch(); main();}Exercise 9

a) Addition of Two Matrices b) Calculating transpose of a matrix in-place manner.c) Matrix multiplication by checking compatibility

a)

Algorithm:

Matrix Addition:

1. Start the procedure2. read no. of rows and columns of the matrix A i.e m,n3. read no. of rows and columns of the matrix B i.e p,q4. if m!=p or n!=q then print “matrix addition is not possible” and goto

step (15)5. else go to next step6. read matrix A and matrix B7. for i=0 to m-1 do8. begin9. for j=0 to n-1 do10.begin11.C[i][j]= A[i][j]+B[i][j];12.end13.end14.print the resultant matrix C.15.Stop

Matrix Transpose:

1. start the procedure2. read the size of the matrix A i.e. m,n3. take a resultant matrix B.4. for i=0 to m-1 do5. begin6. for j=0 to n-1 do

Page 25: C Programming Lab Manual

7. begin8. read element a[i][j]9. end10.end11.for i=0 to m-1 do12.begin13.for j=0 to n-1 do 14.begin15.b[j][i]=a[i][j];16.end17.end18.print the resultant matrix B which is the transpose of the given matrix

A.19.stop.

Matrix Multiplication:

1. start the procedure2. read no. of rows and columns of the matrix A i.e m,n3. read no. of rows and columns of the matrix B i.e p,q4. if n!=p then print “matrix multiplication is not possible” and goto step

(15)5. else go to next step6. read matrix A and matrix B7. for i=0 to m-1 do8. begin9. for j=0 to n-1 do10.begin11.for k=0 to q-1 do12.begin13.C[i][j]= c[i][j]+A[i][k]*B[k][j];14.end15.end16.print the resultant matrix C.17.stop

Program: (Addition & Multiplication)

#include<stdio.h>

Page 26: C Programming Lab Manual

void main(){int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];clrscr();printf("************************************");printf("\n\t\tMENU");printf("\n**********************************");printf("\n[1]ADDITION OF TWO MATRICES");printf("\n[2]MULTIPLICATION OF TWO MATRICES");printf("\n[0]EXIT");printf("\n**********************************");printf("\n\tEnter your choice:\n");scanf("%d",&ch);if(ch<=2 & ch>0){ printf("Valid Choice\n");}switch(ch){ case 1: printf("Input rows and columns of A & B Matrix:"); scanf("%d%d",&r1,&c1); printf("Enter elements of matrix A:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("Enter elements of matrix B:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&b[i][j]); } printf("\n =====Matrix Addition=====\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d",a[i][j]+b[i][j]); printf("\n");

Page 27: C Programming Lab Manual

} break; case 2: printf("Input rows and columns of A matrix:"); scanf("%d%d",&m,&n); printf("Input rows and columns of B matrix:"); scanf("%d%d",&p,&q); if(n==p) { printf("matrices can be multiplied\n"); printf("resultant matrix is %d*%d\n",m,q); printf("Input A matrix\n"); read_matrix(a,m,n); printf("Input B matrix\n"); /*Function call to read the matrix*/ read_matrix(b,p,q); /*Function for Multiplication of two matrices*/ printf("\n =====Matrix Multiplication=====\n"); for(i=0;i<m;++i) for(j=0;j<q;++j) { c[i][j]=0; for(k=0;k<n;++k)

c[i][j]=c[i][j]+a[i][k]*b[k][j]; } printf("Resultant of two matrices:\n"); write_matrix(c,m,q); } /*end if*/ else { printf("Matrices cannot be multiplied."); } /*end else*/ break; case 0: printf("\n Choice Terminated"); exit(); break; default:

Page 28: C Programming Lab Manual

printf("\n Invalid Choice");}getch();}/*Function read matrix*/int read_matrix(int a[10][10],int m,int n){ int i,j; for(i=0;i<m;i++)

for(j=0;j<n;j++)scanf("%d",&a[i][j]);

return 0; } /*Function to write the matrix*/int write_matrix(int a[10][10],int m,int n) { int i,j; for(i=0;i<m;i++) {

for(j=0;j<n;j++)printf("%5d",a[i][j]);printf("\n");

} return 0; }

Program: (Transpose)

#include<stdio.h>#include<conio.h>void main(){

int a[30][30],b[30][30],m,n,i,j;clrscr();printf("\n enter size of matrix a(m,n)");scanf("%d%d",&m,&n);printf("\nenter %d elements ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++)scanf("%d",&a[i][j]);

Page 29: C Programming Lab Manual

}for(i=0;i<m;i++){

for(j=0;j<n;j++)b[j][i]=a[i][j];

}/* display the elements of matrix a*/printf("\nelements of matrix a\n");for(i=0;i<m;i++){

for(j=0;j<n;j++)printf("%4d",a[i][j]);printf("\n");

}/* display the elements of matrix b */printf("\nelements of matrix b\n");for(i=0;i<n;i++){

for(j=0;j<m;j++)printf("%4d",b[i][j]);printf("\n");

}getch();

}

Exercise 10

a)Write C programs that use both recursive and non-recursive functions for the following i) To find the factorial of a given integer. ii) To find the GCD (greatest common divisor) of two given integers.iii) To solve Towers of Hanoi problem.

a) i)

Algorithm: (Non-recursive)

1. Start the procedure2. read a number n 3. fact=factorial(n)4. print fact5. Stop

Page 30: C Programming Lab Manual

Algorithm for factorial():

1. Start the procedure2. f=13. for i=1 to n do4. begin5. f=f*i6. Stop

return f

Alogrithm: (Recursive)

1. Start the procedure2. read a number3. fact= factorial(n)4. print fact5. Stop

Algorithm for factorial():

1. start the procedure2. if n==0 return 13. else return n*factorial(n-1)4. Stop

Program:

#include<stdio.h>#include<conio.h>unsigned int recr_factorial(int n);unsigned int iter_factorial(int n);void main(){ int n,i; long fact; clrscr(); printf("Enter the number: "); scanf("%d",&n);

Page 31: C Programming Lab Manual

if(n==0) printf("Factorial of 0 is 1\n"); else { printf("Factorial of %d Using Recursive Function is %d\n",n,recr_factorial(n)); printf("Factorial of %d Using Non-Recursive Function is %d\n",n,iter_factorial(n)); } getch();}/* Recursive Function*/unsigned int recr_factorial(int n) { return n>=1 ? n * recr_factorial(n-1) : 1;}/* Non-Recursive Function*/unsigned int iter_factorial(int n) { int accu = 1; int i; for(i = 1; i <= n; i++) {

accu *= i; } return accu;}

a) ii)

Algorithm: (Non-recursive)

1. Start the procedure2. read a,b3. result=gcd(a,b)4. print result5. Stop

Algorithm for gcd(a,b):

1. start the procedure2. if a=0 then return b3. else if b=0 then return a4. else go to next step

Page 32: C Programming Lab Manual

5. if a<=b then n1=a , n2=b6. else n1=b , n2=a7. while (n2%n1)!=0 do8. begin9. t=n2%n1;10.n2=n111.n1=t12.end13.return n114.stop

Program:

#include<stdio.h>#include<conio.h>#include<math.h>unsigned int GcdRecursive(unsigned m, unsigned n);unsigned int GcdNonRecursive(unsigned p,unsigned q);int main(void){ int a,b,iGcd; clrscr(); printf("Enter the two numbers whose GCD is to be found: "); scanf("%d%d",&a,&b); printf("GCD of %d and %d Using Recursive Function is %d\n",a,b,GcdRecursive(a,b)); printf("GCD of %d and %d Using Non-Recursive Function is %d\n",a,b,GcdNonRecursive(a,b)); getch();}/* Recursive Function*/unsigned int GcdRecursive(unsigned m, unsigned n){ if(n>m) return GcdRecursive(n,m); if(n==0) return m; else return GcdRecursive(n,m%n);}

Page 33: C Programming Lab Manual

/* Non-Recursive Function*/unsigned int GcdNonRecursive(unsigned p,unsigned q){ unsigned remainder; remainder = p-(p/q*q); if(remainder==0) return q; else GcdRecursive(q,remainder);}

a) iii)

Algorithm: (Recursive)

1. Start2. Initialize sour,temp,dest3. Read n value4. Call procedure hanoi5. End

Procedure for hanoi

1. If(n!=0) then2. Call procedure hanoi3. Print n,sour and dest values4. Call procedure hanoi5. End if

Program: (Recursive)

#include<stdio.h>void main(){int n;char sour='A',temp='B',dest='C';clrscr();printf("enter n value");scanf("%d",&n);hania(n,sour,temp,dest);getch();

Page 34: C Programming Lab Manual

}hania(int n,int sour,int temp,int dest){if(n!=0){hania(n-1,sour,dest,temp);printf("\n%d disks move from %c to %c",n,sour,dest);hania(n-1,temp,sour,dest);}}

Exercise 11

a) Write a C functions to find both the largest and smallest number of an array of integers. b) Write a C function that uses functions to perform the following:

i) that displays the position/ index in the string S where the string T begins, or –1 if S doesn’t contain T.ii) to count the lines, words and characters in a given text.

a)

Algorithm:

Algorithm MIN_MAX:

1. Start2. Read the elements of array a[]3. large=largest(a,n)4. small=smallest(a,n)5. print large6. print small7. Stop

Algorithm largest:

1. Start2. max=a[0]3. for i=1 to n-1 do4. if(max<a[i]) 5. max=a[i]

Page 35: C Programming Lab Manual

6. return max7. Stop

Algorithm Smallest:

1. Start2. min=a[0]3. for i=1 to n-1 do4. if(a[i]<min)5. min=a[i]6. return min7. Stop

Program:

#include<stdio.h>int largest(int[],int);int smallest(int[],int);main(){int a[10],n,i,large,small;clrscr();printf("Enter the no. of elements in the array:");scanf("%d",&n);printf("Enter the elements of the array");for(i=0;i<n;i++)scanf("%d",&a[i]);large=largest(a,n);small=smallest(a,n);printf("The largest element of the array is %d",large);printf("\nThe smallest element of the array is %d",small);getch();}int largest(int a[],int n){int i,max=a[0];for(i=1;i<n;i++)if(max<a[i])max=a[i];return max;

Page 36: C Programming Lab Manual

}int smallest(int a[],int n){int i,min=a[0];for(i=1;i<n;i++)if(a[i]<min)min=a[i];return min;}

b) i)

Algorithm:

1. Start2. Read main string s3. Read the string to be searched t4. found=strstr(s,t)5. if(found)6. print second string is found in the first string at some position7. else8. string not found9. end if 10. Stop

Program:

#include<stdio.h>#include<string.h>#include<conio.h>void main(){ char s[30], t[20]; char *found; clrscr();/* Entering the main string */ puts("Enter the first string: "); gets(s);/* Entering the string whose position or index to be displayed */ puts("Enter the string to be searched: ");

Page 37: C Programming Lab Manual

gets(t);/*Searching string t in string s */ found=strstr(s,t); if(found)printf("Second String is found in the First String at %d position.\n",found-s); else printf("-1"); getch();}

b)ii)

Algorithm:

1. Start2. Initialize variables3. While end=0 do4. Initialize c-05. While read characters until \n then goto step 66. Line[c++]=ctr7. Line [c]=\08. If line=0 then goto step 99. Break10.Else11.Words++12.For i=0 to \0 13.If line=null or \t then14.Words++15.End else16.Lines=lines+117.Characters=characters+strlen(line)18.End while19.Print characters ,words and lines20.end

Program:

Page 38: C Programming Lab Manual

#include <stdio.h>main(){

char line[81], ctr;int i,c,

end = 0,characters = 0,words = 0,lines = 0;

printf("KEY IN THE TEXT.\n");printf("GIVE ONE SPACE AFTER EACH WORD.\n");printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n");while( end == 0){

/* Reading a line of text */c = 0;while((ctr=getchar()) != '\n')

line[c++] = ctr;line[c] = '\0';/* counting the words in a line */if(line[0] == '\0')

break ;else{

words++;for(i=0; line[i] != '\0';i++)

if(line[i] == ' ' || line[i] == '\t')words++;

}/* counting lines and characters */lines = lines +1;characters = characters + strlen(line);

}printf ("\n");printf("Number of lines = %d\n", lines);printf("Number of words = %d\n", words);printf("Number of characters = %d\n", characters);

}

Exercise 12

Page 39: C Programming Lab Manual

a) Write a C function to generate Pascal’s triangle. b) Write a C function to construct a pyramid of numbers.

a)

Algorithm:1. Start2. Initialize q=0 and bin3. Read n value4. While (q<n) do5. For i=40-3*q to 0 then goto step66. Print “ “7. For i=0 to q then8. If(i==0 || q=0) then goto step 99. Bin=110.Else 11.Bin=bin*(q-i+1)/i12.End if13.Print bin14.End for15.Print new line16.Incremetnt q by 117.End while18. Stop

Program:

#include<stdio.h>#include<conio.h>void main(){ int bin,p,q,r,x; clrscr(); bin=1; q=0; printf("Rows you want to input:"); scanf("%d",&r); printf("\nPascal's Triangle:\n");

Page 40: C Programming Lab Manual

while(q<r) { for(p=40-3*q;p>0;--p) printf(" "); for(x=0;x<=q;++x) { if((x==0)||(q==0)) bin=1; else bin=(bin*(q-x+1))/x; printf("%6d",bin); } printf("\n"); ++q; }getch();}

b)

Algorithm:

1. Start2. Initialize x=353. Read number4. For y=0 to num then5. Goto x and y location6. For i=0 to y then goto step 77. Print abs(i)8. X=x-39. End for10.Stop

Program:

#include<stdio.h>#include<conio.h>void main()

Page 41: C Programming Lab Manual

{ int num,i,y,x=35; clrscr(); printf("\nEnter the number to generate the pyramid:\n"); scanf("%d",&num); for(y=0;y<=num;y++) { gotoxy(x,y+1); for(i=0-y;i<=y;i++) printf("%3d",abs(i)); x=x-3; } getch();}

Exercise 13

Write a C function to read in two numbers, x and n, and then compute the sum of this geometric progression:1+x+x2+x3+………….+xn

Write a C function to read in two numbers, x and n(no. of terms), and then compute sin(x) and cos(x).

Algorithm:

1. Start2. Read x and n3. s_sum=14. for i=1 to n do5. s_sum=s_sum+pow(x,i)6. print s_sum7. Stop

Program:

#include<stdio.h>#include<conio.h>#include<math.h>void main(){

Page 42: C Programming Lab Manual

int s_sum,i,x,n;clrscr();printf("Enter the values for x and n:");scanf("%d %d",&x,&n);if(n<=0 || x<=0){ printf("Value is not valid\n");}else{ printf("Value is valid\n"); s_sum=1; for(i=1;i<=n;i++) { s_sum=s_sum+pow(x,i); } printf("Sum of series=%d\n",s_sum);}getch();}

Exercise 16

a) Write a C program which copies one file to another. b) Write a C program to reverse the first n characters in a file. (Note: The file name and n are specified on the command line)

a)

Algorithm:

1. start the procedure2. read a file name3. open that source file in read mode4. if the file name not exists then print ‘file does not exists’ and go to

step 9.5. else go to next step6. open a destination file in a write mode.7. repeat

Page 43: C Programming Lab Manual

8. read each character from source file and copy that character into destination file

9. until the character read is End of the File character(EOF)10.print the destination file11.stop the procedure

Program:

#include <stdio.h>#include <conio.h>#include <process.h>void main(int argc, char *argv[]){ FILE *fs,*ft; char ch; clrscr(); if(argc!=3) { puts("Invalid number of arguments."); exit(0); } fs = fopen(argv[1],"r"); if(fs==NULL) { puts("Source file cannot be opened."); exit(0); } ft = fopen(argv[2],"w"); if (ft==NULL) { puts("Target file cannot be opened."); fclose(fs); exit(0); } while(1) { ch=fgetc(fs); if (ch==EOF) break; else

Page 44: C Programming Lab Manual

fputc(ch,ft); } fclose(fs); fclose(ft); getch();}

b)

Program:

#include <stdio.h>#include <conio.h>#include <string.h>#include <process.h>void main(int argc, char *argv[]){ char a[15]; char s[20]; char n; int k; int j=0; int i; int len; FILE *fp;

if(argc!=3) { puts("Improper number of arguments."); exit(0); } fp = fopen(argv[1],"r"); if(fp == NULL) { puts("File cannot be opened."); exit(0); } k=*argv[2]-48; n = fread(a,1,k,fp); a[n]='\0';

Page 45: C Programming Lab Manual

len=strlen(a); for(i=len-1;i>=0;i--) { s[j]=a[i]; printf("%c",s[j]); j=j+1;}s[j+1]='\0';getch();}