CP LAB

1

SARADA INSTITUTE OF TECNOLOGY & SCIENCE
SARADA NAGAR, RAGHUNADHAPALEM, KHAMMAM

‘C’ PROGRAMMING & DATA STRUCTURES
LABMANUAL FOR

I YEAR B.Tech
(Common to All Branches)

Department of Computer Science & Engineering & Information Technology
SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB
COMPUTER PROGRAMMING LAB

2

Objectives:    To make the student learn a programming language. To teach the student to write programs in C solve the problems To Introduce the student to simple linear and non linear data structures such as lists, stacks, queues, trees and graphs.

Recommended Systems/Software Requirements:  

Intel based desktop PC ANSI C Compiler with Supporting Editors

Week l. 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.

Week 2. a) Write a C program to calculate the following Sum: Sum=1-x /2! +x /4!-x /6!+x /8!-x /10! b) Write a C program toe find the roots of a quadratic equation.
2 4 6 8 10

Week 3 a) Write C programs that use both recursive and non-recursive functions 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.

Week 4 a) The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at where ‘u’ and
2

‘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’. 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)

Week 5 a) Write a C program to find both the larges and smallest number in a list of integers. b) Write a C program that uses functions to perform the following: i) Addition of Two Matrices

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB
ii) Multiplication of Two Matrices

3

Week 6 a) 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. b) Write a C program to determine if the given string is a palindrome or not

Week 7 a) Write a C program that displays the position or index in the string S where the string T begins, or – 1 if S doesn’t contain T. b) Write a C program to count the lines, words and characters in a given text.

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

Week 9 Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the program computes 1+5+25+125. Print x, n, the sum Perform error checking. For example, the formula does not make sense for negative exponents – if n is less than 0. Have your program print an error message if n<0, then go back and read in the next pair of numbers of without computing the sum. Are any values of x also illegal ? If so, test for them too.

Week 10 a) 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. b) Write a C program to convert a Roman numeral to its decimal equivalent.

Week 11 Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.)

Week 12 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.)

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

Gregory forward interpolation. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . ii) Quick sort Week 23 Write C programs to implement the linear regression and polynomial regression algorithms.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways Week 15 Write C programs that implement stack (its operations) using i) Arrays ii) Pointers Week 16 Write C programs that implement Queue (its operations) using i) Arrays ii) Pointers 4 Week 17 Write a C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression Week 18 Write a C program that uses functions to perform the following: i) Creating a Binary Tree of integers ii) Traversing the above binary tree in preorder.CP LAB Week 13 Write a C program that uses functions to perform the following operations on singly linked list. inorder and postorder. Week 19 Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search ii) Binary search Week 20 Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Bubble sort Week 21 Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Insertion sort ii) Merge sort Week 22 Write C programs to implement the Lagrange interpolation and Newton. Week 24 Write C programs to implement Trapezoidal and Simpson methods.: i) Creation ii) Insertion iii) Deletion iv) Traversal Week 14 Write a C program that uses functions to perform the following operations on doubly linked list.

printf(" %d".fab.h> void main() { int num1=0. printf("\n\n\t\t%d %d". printf("\n\n\t\t\t<----FIBONACCI SERIES---->"). counter <= no-2. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .fab).CP LAB 1. num2=1. //LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS PRINTED IN ADVANCE for(counter = 1. printf("\n\n\n\t\tENTER LENGTH OF SERIES (N) : "). num2=fab.counter. Write a C program to find the sum of individual digits of a 1 positive integer.num2). } getch(). scanf("%d". clrscr().no.&no). IN SERIES=========>"). printf("<===========PROGRAM TO FIND THE FIBONACCI SERIES UP TO N NO. counter++) { fab=num1 + num2. #include <stdio. num1=num2.num1.

&no).no). printf("\n\nTHE PRIME NO. } // INCREMENT CHECK IF NO. SERIES B/W 1 TO %d : \n\n".counter1. } getch(). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . SERIES------------------------>"). scanf("%d".counter. #include <stdio. Subsequent terms are found by adding the preceding two terms in the sequence. counter1 > 1 . A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are 0 and 1. IS NOT A PRIME NO. for(counter = 1. counter <= no. printf("<-----------------------PRIME NO. break.h> void main() { int no. printf("\n\n\n\t\t\tINPUT THE VALUE OF N: "). counter1--) if(counter%counter1 == 0) { check++. counter++) { check = 0.counter). } if(check == 0) printf("%d\t". for(counter1 = counter-1. Write a C program to generate the first n terms of the sequence. OR NOT.check. clrscr().CP LAB 2 2. //THIS LOOP WILL CHECK A NO TO BE PRIME NO.

} SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . k=num/10. sum=0.CP LAB 3 3. scanf("%d". clrscr(). k=1. while(num!=0) { k=num%10. num=k.h> #include<conio.h> void main() { int num. printf("Enter the number whose digits are to be added:"). Write a C program to generate all the prime numbers between 1 and n. where n is a value supplied by the user #include<stdio. getch().&num). } printf("Sum of the digits:%d".sum). sum=sum+k.

X^6/6! + X^8/8! . getch(). f_coun>=1. clrscr(). for(counter=0.power)/fact)).X^10/10!").h> #include <math.&x). scanf("%f". //EQ. printf("\n\n\tEQUATION SERIES : 1. printf("<-----------------------PROGRAM FOR SUM OF EQ.h> void main() { int counter. } printf("SUM : %f".counter)*(pow(x. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . f_coun--) fact *= f_coun.fact. SERIES----------------------->").CP LAB 4. printf("\n\n\n\tENTER VALUE OF X : "). power<=10.power=power+2) { fact=1. float sum=0.f_coun. FOR SUM SERIES sum=sum+(pow(-1.power.sum). counter++. Write a C program to calculate the following Sum: 4 Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! #include <stdio. //CALC FACTORIAL OF POWER VALUE for(f_coun=power. power=0.x.X^2/2! + X^4/4! .

printf("\n Enter values of a. 5 #include<stdio.c. getch(). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . root2=-b-sqrt(b*b-4*a*c)/2*a.h> #include<math.CP LAB 5.&c). printf("\n root1=%f\n root2=%f".root2.root2).h> void main() { float a. Write a C program toe find the roots of a quadratic equation.&a. printf("\n*****ROOTS ARE*****\n").root1.&b.b. /*checking condition*/ if(b*b>4*a*c) { root1=-b+sqrt(b*b-4*a*c)/2*a.root1. scanf("%f%f%f".").h> #include<conio.b. clrscr().c for finding roots of a quadratic eq:\n"). } else printf("\n Imaginary Roots.

scanf("%d". } getch(). } return accu.&n). #include<stdio.h> #include<conio. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . else { printf("Factorial of %d Using Recursive Function is %d\n". Write C programs that use both recursive and non-recursive functions i) To find the factorial of a given integer. void main() { int n. i++) { accu *= i. if(n==0) printf("Factorial of 0 is 1\n"). } /* Recursive Function*/ unsigned int recr_factorial(int n) { return n>=1 ? n * recr_factorial(n-1) : 1.i. int i.h> unsigned int recr_factorial(int n). printf("Factorial of %d Using Non-Recursive Function is %d\n".recr_factorial(n)). long fact. unsigned int iter_factorial(int n).CP LAB 6 6. for(i = 1. } /* Non-Recursive Function*/ unsigned int iter_factorial(int n) { int accu = 1. i <= n.n. clrscr(). printf("Enter the number: ").n.iter_factorial(n)).

printf("GCD of %d and %d Using Non-Recursive Function is %d\n". int main(void) { int a.m%n). else return GcdRecursive(n. unsigned int GcdNonRecursive(unsigned p.b. if(n==0) return m.CP LAB 7 ii) To find the GCD (greatest common divisor) of two given integers.h> #include<math. clrscr(). printf("GCD of %d and %d Using Recursive Function is %d\n".b. getch().h> #include<conio.b. unsigned n). } /* Non-Recursive Function*/ unsigned int GcdNonRecursive(unsigned p.&b). } /* Recursive Function*/ unsigned int GcdRecursive(unsigned m. unsigned n) { if(n>m) return GcdRecursive(n.iGcd.GcdNonRecursive(a.h> unsigned int GcdRecursive(unsigned m. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . scanf("%d%d". #include<stdio.unsigned q).a.&a.m).a. printf("Enter the two numbers whose GCD is to be found: ").GcdRecursive(a.b)).unsigned q) { unsigned remainder.b)).

#include<conio.sndl. sndl=sndl. stkindl[top]=indl. stkdndl[top]=dndl.stkindl[100].char indl. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .char sndl.CP LAB remainder = p-(p/q*q). one: if(num==1) { printf("\nMove top disk from needle %c to needle %c ".stkdndl[100].h> #include<stdio. stkadd[top]=3. } two: top=top+1. stkn[top]=num. stksndl[top]=sndl. } iii) To solve Towers of Hanoi problem. 8 if(remainder==0) return q.add.stkadd[100]. num=num-1.h> /* Non-Recursive Function*/ void hanoiNonRecursion(int num. dndl=temp.temp.dndl).remainder). goto one.stksndl[100]. else GcdRecursive(q. int top.char dndl) { char stkn[100]. temp=indl. goto four. indl=dndl. top=NULL.

ndl2 ). stkadd[top]=5. indl=temp. stkindl[top]=indl. sndl=indl. if(add==3) goto three. } /* Recursive Function*/ void hanoiRecursion( int num. stksndl[top]=sndl. add=stkadd[top]. top=top+1.ndl1. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . num=num-1. num=stkn[top]. else if(add==5) goto four. ndl3. ndl2 ). indl=stkindl[top]. stkn[top]=num.dndl). sndl=stksndl[top]. return. 9 goto one. stkdndl[top]=dndl.1.char ndl1. temp=sndl.sndl. } hanoiRecursion( num . char ndl2. four: if(top==NULL) return. dndl=stkdndl[top].CP LAB three: printf("\nMove top disk from needle %c to needle %c ". char ndl3) { if ( num == 1 ) { printf( "Move top disk from needle %c to needle %c.". top=top-1. dndl=dndl. ndl1.

1. hanoiNonRecursion(no. of disks to be transferred: ").'A'. if(no<1) printf("\nThere's nothing to move. hanoiRecursion(no. clrscr(). scanf("%d". printf("\nRecursive").CP LAB printf( "Move top disk from needle %c to needle %c. } 10 void main() { int no. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .").'C').'A'. ndl1.'B'. ndl2.&no).'C'). ndl2 ).".ndl3. hanoiRecursion( num . else printf("Non-Recursive"). printf("Enter the no.'B'. ndl1 ). getch().

Write C program to find the distance travelled at regular intervals of time given the values of ‘u’ and ‘a’.) and acceleration (m/sec2). counter <= tim_intrval.time). counter++) { printf("\n\t\t\tAT T%d TIME(sec) : ". printf("<===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>").h> void main() { int tim_intrval. distance=0.time. 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. scanf("%f". scanf("%f".distance). counter. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . 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’.CP LAB 11 7. clrscr(). float accl. distance += (velos*time + (accl*pow(time. getch(). } printf("\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF TIME : %f".&time).2))/2). scanf("%d". #include <stdio.&accl). printf("\n\n\n\t\t\tNO OF TIME INTERVALS : "). printf("\t\t\tACCLERATION AT %d sec (m/sec^2): ".h> #include <math.counter). scanf("%d". velos.&velos).&tim_intrval). printf("\t\t\tVELOCITY AT %d sec (m/sec) : ".tim_intrval. for(counter = 1.time).

} switch(ch) { case 1: res=a+b. scanf("%d".h> #include<conio.ch.res). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . break.res. clrscr().-. Write a C program.b. which takes two integer operands and one operator form the user.&ch).*. printf("\n\t(1)ADDITION").CP LAB 12 8. performs the operation and then prints the result. printf("\n\t(2)SUBTRACTION"). printf("\n Subtraction:%d".&b).&a. printf("\t *********************").h> void main() { int a. scanf("%d%d". if(ch<=5 & ch>0) { printf("Enter two numbers:\n"). printf("\n\tMENU\n").res). printf("\t********************"). printf("\n\t(0)EXIT"). printf("\n\t(5)REMAINDER"). case 2: res=a-b. /. printf("\n\n\tEnter your choice:"). printf("\n\t(4)DIVISION"). % and use Switch Statement) #include<stdio. printf("\n Addition:%d". printf("\n\t(3)MULTIPLICATION"). (Consider the operators +. printf("\n\t********************").

} SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } getch().res). case 4: res=a/b. exit(). case 5: res=a%b. break. default: printf("\n Invalid Choice"). printf("\n Division:%d". break.res). break. break. printf("\n Remainder:%d". 13 case 3: res=a*b. printf("\n Multiplication:%d".res).CP LAB break. case 0: printf("\n Choice Terminated").

printf("%f\n". return(max). float value[4] = {2.3. main( ) { float largest(float a[ ]. largest(value.2. Write a C program to find both the larges and smallest number in a list of integers. int n) { int i.5. } float largest(float a[].-4.1. for(i = 1.CP LAB 14 9. int n).75. max = a[0]. i < n. i++) if(max < a[i]) max = a[i]. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . float max.4)).67}.

printf("\n\tEnter your choice:\n").c1.a[10][10].j<c1.&a[i][j]).i<r1.m.i. for(i=0. printf("\n[2]MULTIPLICATION OF TWO MATRICES").&c1). printf("\n[0]EXIT").q. if(ch<=2 & ch>0) { printf("Valid Choice\n").j++) scanf("%d".n. printf("\n**********************************"). Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices #include<stdio.c[10][10].&ch).b[10][10]. printf("\n\t\tMENU"). } printf("Enter elements of matrix B:\n").r1. scanf("%d%d". clrscr().k.&r1.p. printf("************************************").i++) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .j. printf("Enter elements of matrix A:\n"). for(i=0.i++) { for(j=0.CP LAB 15 10.h> void main() { int ch. scanf("%d". printf("\n[1]ADDITION OF TWO MATRICES"). printf("\n**********************************"). } switch(ch) { case 1: printf("Input rows and columns of A & B Matrix:").i<r1.

for(k=0.p.a[i][j]+b[i][j]).j<q. } printf("Resultant of two matrices:\n").i<r1.++k) c[i][j]=c[i][j]+a[i][k]*b[k][j]. /*Function call to read the matrix*/ read_matrix(b. printf("Input A matrix\n"). scanf("%d%d". for(i=0.m. read_matrix(a. } printf("\n =====Matrix Addition=====\n").++j) { c[i][j]=0.q).&b[i][j]). for(i=0.k<n.&m.i<m.j<c1. write_matrix(c. printf("Input rows and columns of B matrix:"). } break.&n). printf("Input B matrix\n").m.CP LAB for(j=0.m.i++) { for(j=0. printf("\n").j++) scanf("%d".&q).n). scanf("%d%d". 16 case 2: printf("Input rows and columns of A matrix:").j<c1. /*Function for Multiplication of two matrices*/ printf("\n =====Matrix Multiplication=====\n").&p.j++) printf("%5d".q).++i) for(j=0.q). printf("resultant matrix is %d*%d\n". } /*end if*/ else SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . if(n==p) { printf("matrices can be multiplied\n").

i++) { for(j=0.j++) scanf("%d".j<n. } /*end else*/ break.j<n.CP LAB { printf("Matrices cannot be multiplied.j.int n) { int i. exit().i<m. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } getch().i++) for(j=0.i<m. printf("\n").int n) { int i.a[i][j]). default: printf("\n Invalid Choice"). break. for(i=0.int m. return 0.j. } /*Function read matrix*/ int read_matrix(int a[10][10].").&a[i][j]).int m. } /*Function to write the matrix*/ int write_matrix(int a[10][10].j++) printf("%5d". } return 0. for(i=0. 17 case 0: printf("\n Choice Terminated").

r = strlen(a). int t=0. int x.h> #include <string.h> void main() { char a[10]. i++. int p=0.s. // Copying the input string into another array while(i <= r) { c[i]=a[i].CP LAB 18 11. #include <stdio. 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. n = strlen(b).h> #include <conio. char c[10].o. gets(b).&p). puts("Enter Second String:").g. gets(a).n. o = p+n. i=0. puts("Enter First String:").i=0. char b[10]. } s = n+r.r=0. scanf("%d". // Adding the sub-string SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . clrscr(). printf("Enter the position where the item has to be inserted: ").

} a[o]=x. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . if(t<n) { a[i] = b[t].i++) { x = c[i].CP LAB for(i=p. a). t=t+1. o=o+1.i<s. getch(). } 19 printf("%s".

&n). clrscr(). gets(string). puts("Enter the string"). #include <stdio.h> 20 void delchar(char *x. } // Function to delete n characters void delchar(char *x.&x[a+b-1]). printf("Enter the position from where to delete"). delchar(string.p. scanf("%d". scanf("%d". int n.h> #include <conio.pos). puts(x).int a. void main() { char string[10]. int b) { if ((a+b-1) <= strlen(x)) { strcpy(&x[b-1].CP LAB ii) To delete n Characters from a given position in a given string.&pos).int a. int b).pos. n.h> #include <string. printf("Enter the number of characters to be deleted"). getch(). } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

printf("****Program to test if the given string is a palindrome****\n").right.true}. scanf("%s".CP LAB 21 12.second & second last & so on */ while(left<right&&matched) { if(string[left]!=string[right]) matched=false. /* Compare the first and last letter.len=strlen(string). if(IsPalindrome(string)) printf("The given string %s is a palindrome\n". } int main() { char string[40]. right--.h> #include<string.string). clrscr(). left=0. enum Boolean IsPalindrome(char string[]) { int left. else { left++. enum Boolean matched=true. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . Write a C program to determine if the given string is a palindrome or not #include<stdio.string). right=len-1. if(len==0) return 0. printf("Enter a string:").h> enum Boolean{false. } } return matched.

return 0. } 22 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . getch().string).CP LAB else printf("The given string %s is not a palindrome\n".

CP LAB 23 13. Write a C program that displays the position or index in the

string S where the string T begins, or – 1 if S doesn’t contain T.
#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: "); 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(); }

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB 24 14. Write a C program to count the lines, words and characters in a

given text.
#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); }

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB 15. Write a C program to generate Pascal’s triangle.
#include<stdio.h> #include<conio.h> void main() { int bin,p,q,r,x; clrscr(); bin=1; q=0;

25

printf("Rows you want to input:"); scanf("%d",&r);

printf("\nPascal's Triangle:\n");

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(); }

16. Write a C program to construct a pyramid of numbers.

#include<stdio.h> #include<conio.h>

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

y<=num.CP LAB void main() { int num.y-coordinate)*/ gotoxy(x.y++) { /*(x-coordinate.x=35.i.y+1). clrscr().abs(i)). scanf("%d". 26 for(y=0.&num).i++) printf("%3d". x=x-3. } getch().i<=y.y. printf("\nEnter the number to generate the pyramid:\n"). /*for displaying digits towards the left and right of zero*/ for(i=0-y. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

then the program computes 1+5+25+125. n.&n). Are any values of x also illegal ? If so.i<=n. } printf("Sum of series=%d\n". Have your program print an error message if n<0.x. For example. clrscr(). printf("Enter the values for x and n:"). Write a C program to read in two numbers.i).+xn For example: if n is 3 and x is 5. scanf("%d %d".CP LAB 27 17.n. } getch().&x. Print x.h> void main() { int s_sum. and then compute the sum of this geometric progression: 1+x+x2+x3+………….i. if(n<=0 || x<=0) { printf("Value is not valid\n"). the sum Perform error checking. the formula does not make sense for negative exponents – if n is less than 0.i++) { s_sum=s_sum+pow(x.s_sum). s_sum=1. x and n.h> #include<conio.h> #include<math. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . test for them too. #include<stdio. then go back and read in the next pair of numbers of without computing the sum. } else { printf("Value is valid\n"). for(i=1.

h> #include<conio. l=strlen(a). 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. int i. void main() { char a[16]. i>=0.a[i]!='\0'.h> void complement (char *a). getch(). clrscr(). i++) { if (a[i]!='0' && a[i]!='1') { printf("The number entered is not a binary number. c=0. i. Enter the correct number"). exit(0). for (i=l-1. else b[i]='0'. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . char b[16]. Write a C program to find the 2’s complement of a binary number. #include <stdio. for(i=0. gets(a). } } complement(a). Thus 2’s complement of 11100 is 00100. printf("Enter the binary number"). i--) { if (a[i]=='0') b[i]='1'. } void complement (char *a) { int l.CP LAB } 28 18.

} } } b[l]='\0'. printf("The 2's complement is %s". else { b[i]='0'.CP LAB for(i=l-1. i--) { if(i==l-1) { if (b[i]=='0') b[i]='1'. b). } } else { if(c==1 && b[i]=='0') { b[i]='1'. c=1. i>=0. } else if (c==1 && b[i]=='1') { b[i]='0'. c=1. } 29 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . c=0.

h> #include<conio. char *rom. #include<stdio.i++) { if(rom[i]=='I') a[i]=1.len. else if(rom[i]=='V') a[i]=5.i<len. else if(rom[i]=='L') a[i]=50.k. for(i=0. else if(rom[i]=='X') a[i]=10. else if(rom[i]=='D') a[i]=500. clrscr().CP LAB 30 19. len=strlen(rom).i. printf("Enter the Roman Numeral:"). else if(rom[i]=='M') a[i]=1000. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . scanf("%s".h> #include<string.h> #include<stdlib. else if(rom[i]=='C') a[i]=100.j. else { printf("\nInvalid Value"). Write a C program to convert a Roman numeral to its decimal equivalent.h> void main() { int *a.rom).

} printf("\nIts Decimal Equivalent is:").CP LAB getch(). } 31 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . printf("%d". exit(0).k). for(i=len-1.i--) { if(a[i]>a[i-1]) k=k-a[i-1]. else if(a[i]==a[i-1] || a[i]<a[i-1]) k=k+a[i-1]. getch(). } } k=a[len-1].i>0.

printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 0 : EXIT \n\n\t\t Enter your Option [ ]\b\b"). Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers (Note: represent complex number using a structure.h> void arithmetic(int opern). printf("\n\n \t\t\t***** MAIN MENU *****"). void main() { int opern. switch(opern) { case 0: exit(0).CP LAB 32 20. clrscr().h> #include<math. default: main(). }. double imgpart.&opern). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . case 1: case 2: arithmetic(opern). struct comp { double realpart.) #include<stdio. scanf("%d".

scanf("%lf". printf("\n Enter two Complex Numbers (x+iy):\n Real Part of First Number:"). printf("\n Real Part of Second Number:").realpart).&w2. } if (w. w.realpart.imgpart*w2.w. else printf("\n Answer = %lf%lfi".&w1. w2.imgpart=(w1.realpart*w2. break.w.CP LAB } 33 void arithmetic(int opern) { struct comp w1.realpart*w2. printf("\n Imaginary Part of First Number:"). scanf("%lf".imgpart).realpart=(w1.imgpart). w.realpart.realpart = w1. printf("\n Imaginary Part of Second Number:").imgpart)+(w1.imgpart = w1.imgpart>0) printf("\n Answer = %lf+%lfi". break. switch(opern) { /*addition of complex number*/ case 1: w. /*multiplication of complex number*/ case 2: w. scanf("%lf".w.realpart).realpart).imgpart*w2.realpart.realpart)-(w1. main().imgpart). w.w.&w2. getch(). scanf("%lf".realpart+w2.imgpart.imgpart+w2. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .&w1.imgpart).imgpart).

exit(0). } ft = fopen(argv[2]. Write a C program which copies one file to another. clrscr(). else fputc(ch.h> void main(int argc. if (ft==NULL) { puts("Target file cannot be opened. #include <stdio.CP LAB } 34 21. if (ch==EOF) break.*ft. } fs = fopen(argv[1]. if(argc!=3) { puts("Invalid number of arguments. char ch."). } while(1) { ch=fgetc(fs). } fclose(fs). fclose(ft). if(fs==NULL) { puts("Source file cannot be opened. char *argv[]) { FILE *fs.h> #include <conio.ft). exit(0)."). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE ."). fclose(fs)."r").h> #include <process. exit(0)."w").

exit(0).1.CP LAB getch(). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .i--) { s[j]=a[i]. int i. printf("%c". int j=0. int len.h> #include <string.h> #include <process. char *argv[]) { char a[15]. } s[j+1]='\0'.fp).h> #include <conio. if(argc!=3) { puts("Improper number of arguments.h> void main(int argc. a[n]='\0'. } fp = fopen(argv[1]. FILE *fp.s[j]). Write a C program to reverse the first n characters in a file. } k=*argv[2]-48. (Note: The file name and n are specified on the command line. n = fread(a."r"). if(fp == NULL) { puts("File cannot be opened."). j=j+1. len=strlen(a).i>=0. int k."). char s[20].k. char n. exit(0). } 35 22. for(i=len-1.) #include <stdio.

CP LAB getch(). } 36 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

typedef struct linked_list node. void print(node *p). struct linked_list *next. &list -> number). scanf("%d". int count(node *p). printf("(type -999 at end): "). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . /* create current node */ if(list->number == -999) { list->next = NULL. void create(node *p). /* node type defined */ main() { node *head. count(head)).h> NULL 0 struct linked_list { int number. Write a C program that uses functions to perform the following operations on singly linked list. head = (node *)malloc(sizeof(node)). printf("\nNumber of items = %d \n". printf("\n").h> <stdlib. printf(head).CP LAB 37 23.: i) Creation ii) Insertion iii) Deletion iv) Traversal i) Creation #include #include #define <stdio. create(head). printf("\n"). }. } void create(node *list) { printf("Input a number\n").

create(list->next). int key. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .list ->number). /* print current item */ /*create next node */ 38 if(list->next->next == NULL) printf("%d". node *n1. } return.CP LAB else { list->next = (node *)malloc(sizeof(node)). } int count(node *list) { if(list->next == NULL) return (0). int x. */ Recursion occurs */ } return. print(list->next). } ii) Insertion node *insert(node *head) { node *find(node *p. else /* move to next item */ return(1+ count(list->next)). list->next->number). /* new item (number) to be inserted */ /* pointer to new node */ /* pointer to node preceding key node */ printf("Value of new item?"). int a). node *new. } void print(node *list) { if(list->next != NULL) { printf("%d-->".

else { new = (node *)malloc(sizeof(node)). int key) { if(list->next->number == key) /* key found */ return(list). key). &x). } } return(head). new->number = x. else find(list->next. } /* end */ iii) Deletion SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } node *find(node *lists. new->next = n1->next. head = new. key). else /* insert new node */ if(list->next->next == NULL) return(NULL). 39 if(head->number == key) { /* new node is first */ new = (node *)malloc(size of(node)). new->number = x. /* find key node */ if(n1 == NULL) printf("\n key is not found \n"). &key). printf("Value of key item ? (type -999 if last) ").CP LAB scanf("%d". scanf("%d". n1->next = new. } else { /* find key node and insert new node */ /* before the key node */ n1 = find(head. new->next = head.

} else { n1 = find(head. free(head). n1->next = p. node *n1. if(head->number == key) { p = head->next.h> #include <stdlib. &key). else { p = n1->next->next. } /* free key node */ /* establish link */ iv) Traversal #include <stdio. head = p. if(n1 == NULL) printf("\n key not found \n"). /* pointer to the node following the keynode */ /* delete key node */ /* pointer to 2nd node in list */ /* release space of key node */ /* make head to point to 1st node */ /* first node to be deleted) */ /* item to be deleted */ /* pointer to node preceding key node */ /* temporary pointer */ 40 printf("\n What is the item (number) to be deleted?"). } } return(head). node *p. int key. free(n1->next). scanf("%d".h> #define NULL 0 struct linked_list { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . int a). key).CP LAB node *delete(node *head) { node *find(node *p.

type -999. int n). p1 = NULL. } printf("\n").\n"). printf("Input the list of numbers. while(n != -999) { if(head == NULL) { head = (node *)malloc(sizeof(node)). p2 = list.&n). int x) { node *p1.n). node *head = NULL.\n"). print("\n"). typedef struct linked_list node. head->next = NULL. node *insert_Sort(node *p. } scanf("%d".CP LAB int number. }. void print(node *p). print(head). /* p2 points to first node */ SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . struct linked_list *next. *p2. &n). 41 main () { int n. head ->number = n. } node *insert_sort(node *list. *p. printf("At end. /* create 'base' node */ } else { /* insert next item */ head = insert_sort(head. scanf("%d".

print(list->next). } void print(node *list) { if (list == NULL) printf("NULL"). p2 = p2->next) { p1 = p2. node */ else p1->next = p. else { printf("%d-->". if (p1 == NULL) list = p. /* space for new node */ p->number = x. p->next = p2. break. p2->number < x . 42 if(p2->next == NULL) { p2 = p2->next. } return.list->number). } } /* p2 set to NULL */ /* insert new node at end */ /* key node found */ p = (node *)malloc(sizeof(node)). /* new node inserted after 1st node */ return (list). } /* new node becomes the first /* place value in the new node */ /* link new node to key node */ SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .CP LAB for( .

int).CP LAB 43 24.Item. while(1) { clrscr(). high=NULL. int flag=0.h" typedef struct dubll { int data.last. void PrintItem(). DUBLL NodeAlloc(). Write a C program that uses functions to perform the following operations on doubly linked list. struct dubll *leftlink.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways #include "stdio. void AppendItem().pntr. void CreateItem(). DUBLL Search(int. DUBLL high. DUBLL NodeAlloc(). }*DUBLL. scanf("%d".low. DUBLL Search(int item. printf("\n \t\t\t***** M A I N M E N U *****\n\n").&choice). void main(void) { int choice. void DeleteItem().h" #include "alloc.*rightlink.int flag). void InsertItem().temp_node. switch(choice) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . printf("\n 1: Create Linked List \n 2: Append a Node to the List \n 3: Traverse the List \n 4: Delete a Node from the List \n 5: Search a Node \n 6: Insert a Node to the List \n 7: Close \n\n\t\t Enter your Option [ ]\b\b").

puts("\nPress any key to go back to main menu. break.CP LAB case 1: CreateItem(). temp_node=Search(Item."). getch(). } else { puts("The item is not found in the Linked List. break. getch(). break. case 7: exit()."). case 5: printf("Find an Item: "). puts("\nPress any key to go back to main menu. case 4: DeleteItem(). } getch(). case 3: PrintItem()."). default: puts("Invalid choice.0). break. puts("\nPress any key to go back to main menu. case 2: AppendItem(). if(temp_node) { puts("The item is available in the Linked List. } 44 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . getch(). break. scanf("%d". break.&Item)."). case 6: InsertItem()."). break.").

scanf("%d".high. temp_node->leftlink=low.CP LAB } } 45 /* Function to Create the list*/ void CreateItem() { if(high==NULL) { printf("\n --Creating the list--"). while(low->rightlink!=NULL) low=low->rightlink.high->data). last=low->rightlink. printf("\n Enter Item (in integer) :"). low->rightlink=temp_node. printf("\n Enter starting data (as integer value) :"). temp_node=NodeAlloc(). scanf("%d". } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } else{ printf("\n List already created @ %d with %d as data. if(high==NULL) { CreateItem().".} } /* Function to Append items to the list*/ void AppendItem() { low=high. } else { temp_node=NodeAlloc(). temp_node->rightlink=NULL.&temp_node->data).&temp_node->data). high=temp_node.

Please create a list first.temp_node->data). last = last->leftlink. DUBLL temp_node.CP LAB /* Function to Traverse the list both ways and print the data*/ void PrintItem() { DUBLL temp_node. printf("\n--Printing The List In Backward direction--\n"). CreateItem(). Please create a list first. if(high==NULL) { printf("\n List is not available.return. temp_node=high.last->data). if(high==NULL) { printf("\n List is not available. } temp_node=high. CreateItem()."). } printf("\n"). } } //In backward direction /* Function to Delete items of the list*/ void DeleteItem() { int value. } while(last!=NULL) { printf("\t %d". } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . temp_node = temp_node->rightlink. if(temp_node->rightlink==NULL){printf("%d". last=low->rightlink. getch().temp_node->data). 46 while(temp_node!=NULL) { //In forward direction printf("\t %d". printf("\n--Printing The List In Forward direction--\n"). getch().").

if(high==NULL) { printf("\n List is not available. CreateItem().").&value). tmep_node=malloc(sizeof(struct dubll)). getch().int flag) { temp_node = high. } } temp_node=temp_node->rightlink. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . scanf("%d". } else { return(temp_node).CP LAB printf("\n Item to delete :"). } 47 /* Function to Search an item from the list*/ DUBLL Search(int item.1). pntr->rightlink->leftlink=pntr->leftlink. pntr->leftlink->rightlink=pntr->rightlink. } while(temp_node!=NULL) { if(temp_node->data==item ) { if(flag==0) { return(1). temp_node=pntr. free(temp_node). pntr=Search(value. } } /* Function to Allocate nodes*/ DUBLL NodeAlloc() { DUBLL tmep_node. Please create a list first.

"). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } tmep_node->rightlink=tmep_node->leftlink=NULL."). printf("Position At which node to be inserted: ___ & New Item Value: ___ "). DUBLL temp_node. getch(). getch().CP LAB if(tmep_node==NULL) { printf("\n No memory available.1). pntr->rightlink->leftlink=temp_node. Please create a list first. Node allocation cannot be done."). pntr->rightlink=temp_node. scanf("%d". CreateItem(). if(high==NULL) { printf("\n List is not available. //creating link to new node temp_node->rightlink=pntr->rightlink. } temp_node=NodeAlloc()."). getch().return. if(pntr->rightlink==NULL){printf("\n The operation is not possible.&temp_node->data). } 48 /* Function to Insert items in the middle of the list*/ void InsertItem() { int node. scanf("%d". pntr=Search(node.} temp_node->leftlink=pntr.&node). printf("\n Item has been Inserted. return(tmep_node).

num2=0. scanf("%c". void push_ele(int ele).h> #include<conio. switch(choice-'0') { case 1: { printf("\n\tElement to be pushed: "). printf("\n======================================"). int t=-1. push_ele(num1). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . while(1) { clrscr(). int pop_ele().&choice).h> int st_arr[20]. void display_ele(). printf("\n\tEnter your choice: "). scanf("%d".num1=0. printf("\n[4] Exit\n"). printf("\n[2] Using Pop Function"). printf("======================================"). printf("\n[1] Using Push Function"). fflush(stdin). void main() { char choice. printf("\n\t\t MENU ").&num1). printf("\n[3] Elements present in Stack"). break. Write C programs that implement stack (its operations) using 49 i) Arrays #include<stdio.CP LAB 25.

break. } case 4: exit(1). } } } /*Implementing the push() function. getch(). } st_arr[++t]=ele. exit(1). getch().\n"). } 50 case 3: { display_ele(). break. getch().\n"). break.num2). break. */ void push_ele(int ele) { if(t==99) { printf("STACK is Full.CP LAB case 2: { num2=pop_ele(1). printf("\n\tElement to be popped: %d\n\t". default: printf("\nYour choice is invalid. } /*Implementing the pop() function. */ int pop_ele() SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

printf("\n\tElements present in the stack are:\n\t").CP LAB { int ele1. */ void display_ele() { int k. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .k++) printf("%d\t". if(t==-1) { printf("\n\tSTACK is Empty. getch().st_arr[k]). } 51 /*Implementing display() function. for(k=0. } return(st_arr[t--]).k<=t.\n"). exit(1).

} *t. printf("======================================"). printf("\n======================================"). void push_ele(int j).CP LAB Write C programs that implement stack (its operations) using 52 ii) Pointers #include<stdio. printf("\n\tEnter your choice: "). printf("\n\t\t MENU ").&choice). struct st_point *l. int pop_ele(). switch(choice-'0') { case 1: { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . scanf("%c". printf("\n[2] Using Pop Function").num2=0.h> struct st_point { int ele. int i. void main() { char choice.h> #include<conio. int i.num1=0. printf("\n[4] Exit\n"). void display_ele(). fflush(stdin). printf("\n[3] Elements present in Stack"). while(1) { clrscr(). printf("\n[1] Using Push Function").

num2).\n"). scanf("%d". getch(). getch(). m=(struct st_point*)malloc(sizeof(struct st_point)). break.&num1). } case 4: exit(1).CP LAB printf("\n\tElement to be pushed:"). break. display_ele(). } } } /*Inserting the elements using push function*/ void push_ele(int j) { struct st_point *m. } 53 case 2: { num2=pop_ele(1). break. break. } case 3: { printf("\n\tElements present in the stack are:\n\t"). m->l=t. m->ele=j. t=m. default: printf("\nYour choice is invalid. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . break. push_ele(num1). printf("\n\tElement to be popped: %d\n\t".

} return 0.pointer->ele). while(pointer!=NULL) { printf("%d\t". } else { int i=t->ele. t=t->l. } 54 /*Removing the elements using pop function*/ int pop_ele() { if(t==NULL) { printf("\n\STACK is Empty. exit(1). pointer=pointer->l. return (i). } /*Displaying the elements */ void display_ele() { struct st_point *pointer=NULL. } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . pointer=t.").CP LAB return. getch().

int rem_ele(struct q_arr* queue). printf("============================================"). int num. while(1) { clrscr(). }.int).h> #define size 10 #define true 1 #define false 0 struct q_arr { int f. void display_ele(struct q_arr* queue). int ch.h> #include<conio. int add_ele(struct q_arr* queue. printf("\n\n****IMPLEMENTATION OF QUEUE USING ARRAYS****\n"). struct q_arr *queue = (struct q_arr*)malloc(sizeof(struct q_arr)).h> #include<alloc. Write C programs that implement Queue (its operations) using 55 i) Arrays #include<stdio. /*main function*/ void main() { int ele.r. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .CP LAB 26. int e_que(struct q_arr* queue). init(queue). printf("\n\t\tMENU\n"). int f_que(struct q_arr* queue). void init(struct q_arr* queue).k. printf("============================================"). int a[size].

break."). printf("\n\n\t Enter your choice: "). printf("\n\t[3] To display all the elements"). } case 3: { display_ele(queue).&ele). No element can be removed. } else { printf("\tQueue is Empty.CP LAB printf("\n\t[1] To insert an element"). printf("\n\t[4] Exit"). } case 4: SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } 56 case 2: { if(!e_que(queue)) { k=rem_ele(queue). printf("\n%d element is removed\n". break. scanf("%d". scanf("%d".ele).&ch).k). } break. getch(). printf("\n\t[2] To remove an element"). switch(ch) { case 1: { printf("\nElement to be inserted:"). getch(). add_ele(queue. getch().

if(queue->r == size . getch(). } } } /*end main*/ void init(struct q_arr* queue) { queue->f = 0.CP LAB exit(0). } /* Function to add an element to the queue*/ int add_ele(struct q_arr* queue. queue->num = 0.1) SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } /* Function to check if the queue is full*/ int f_que(struct q_arr* queue) { if(queue->num == size) return true. break. return false.int j) { if(f_que(queue)) return false. 57 default: printf("\tInvalid Choice. } /* Function to check is the queue is empty*/ int e_que(struct q_arr* queue) { if(queue->num==0) return true. return false."). queue->r = -1.

queue->a[j]). printf("\n"). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . return true."). return.CP LAB queue->r = -1. } 58 /* Function to remove an element of the queue*/ int rem_ele(struct q_arr* queue) { int j. queue->a[++queue->r] = j. return j. queue->num--. queue->num++. if(e_que(queue)) { printf("Queue is Empty.j++) printf("%d\t". if(queue->f == size) queue->f = 0. j = queue->a[queue->f++]. No records to display. } /* Function to display the queue*/ void display_ele(struct q_arr* queue) { int j. } printf("\nElements present in the Queue are: "). for(j=queue->f.j<=queue->r. if(e_que(queue)) return -9999.

h> #include<conio. printf("\n\n\tEnter your choice:"). printf("\n\t\t MENU\n"). void add_ele(int). }.h> struct q_point { int ele. printf("\n\t[1] To insert an element"). printf("\n\n****IMPLEMENTATION OF QUEUE USING POINTERS****\n"). &choice). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . void show_ele(). int rem_ele(void). printf("\n\t[4] Exit"). struct q_point* n.choice. printf("=============================================="). scanf("%d".j. while(1) { clrscr().h> #include<process.CP LAB Write C programs that implement Queue (its operations) using 59 ii) Pointers #define true 1 #define false 0 #include<stdio. printf("\n\t[3] To display all the elements"). /*main function*/ void main() { int ele. int e_que(void). printf("\n\t[2] To remove an element"). printf("=============================================="). struct q_point *f_ptr = NULL.

getch(). default: printf("\n\tInvalid choice. } break. printf("\n\t%d is removed from the queue".j). break. } case 3: show_ele(). break."). case 4: exit(1). getch().&ele). getch(). getch(). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } 60 case 2: { if(!e_que()) { j=rem_ele(). scanf("%d". } else { printf("\n\tQueue is Empty.CP LAB switch(choice) { case 1: { printf("\n\tElement to be inserted:"). break."). break. getch(). add_ele(ele).

ptr->n = queue. if(f_ptr==NULL) f_ptr = queue. f_ptr = f_ptr->n. if(e_que()==false) { int j = f_ptr->ele. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . ptr = f_ptr. queue->n = NULL. for(ptr=f_ptr . } } /* Function to remove an element from the queue*/ int rem_ele() { struct q_point* queue=NULL. queue->ele = ele.ptr->n!=NULL.CP LAB } 61 } } /* Function to check if the queue is empty*/ int e_que(void) { if(f_ptr==NULL) return true. return false. else { struct q_point* ptr. queue=f_ptr. ptr=ptr->n). free (queue). return j. } /* Function to add an element to the queue*/ void add_ele(int ele) { struct q_point *queue = (struct q_point*)malloc(sizeof(struct q_point)).

"). ptr=ptr->n."). } else { printf("\n\tElements present in Queue are:\n\t").CP LAB } else { printf("\n\tQueue is empty. return. } } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . ptr=f_ptr.ptr->ele). if(e_que()) { printf("\n\tQUEUE is Empty. while(ptr!=NULL) { printf("%d\t". } } 62 /* Function to display the queue*/ void show_ele() { struct q_point *ptr=NULL. return -9999.

int st_top=-1. } st[++st_top]=it. int cal(char post[]).h> #include<conio. } /*end main*/ void push_item(int it) { if(st_top==99) { printf("\n\n\t*STACK is Full*"). clrscr(). printf("\n\tEnter the Infix Expression: "). gets(in). int st_ISP(char t). getch(). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . /*main function*/ void main() { char in[100]. in_post(in). void in_post(char in[]). Write a C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression #include<stdio.h> int st[100]. void push_item(int it).CP LAB 63 27. int st_ICP(char t). getch().post[100]. int pop_item(). exit(1).

result=0. post[100]. char a. } c=pop_item(). while(t!='\0') { if(isalnum(t)) /*For checking whether the value in t is an alphabet or number. push_item('\0'). if(st_top==-1) { getch(). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . */ { post[y]=t.z. } 64 /*Function for converting an infix expression to a postfix expression. */ void in_post(char in[]) { int x=0. char t. y++.c. } else if(t=='(') { push_item('('). post[y]=c. } else if(t==')') { while(st[st_top]!='(') { c=pop_item(). t=in[x]. } return(st[st_top--]).y=0.CP LAB int pop_item() { int it. y++.

z++) printf("%c". getch(). printf("\n\n\tResult is: %d\n". } push_item(t). y++. } else if(a=='n' || a=='N') { exit(0). } x++. } } /*Determining priority of inside elements*/ int st_ISP(char t) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .z<y. } 65 while(st_top!=-1) { c=pop_item().CP LAB else { while(st_ISP(st[st_top])>=st_ICP(t)) { c=pop_item(). for(z=0. y++. if(a=='y' || a=='Y') { result=cal(post). t=in[x]. printf("\n\nDo you want to evaluate the Result of Postfix Expression?(Y/N):").&a).post[z]). post[y]=c.result). scanf("%c". } printf("\n\tThe Postfix Expression is:"). post[y]=c.

} return 0. case ')':return (9). case '*':return (8). default: printf("Expression is invalid. len=strlen(post). } 66 /*Determining priority of approaching elements*/ int st_ICP(char t) { switch(t) { case '(':return (10). default: printf("Expression is invalid."). } /*Evaluating the result of postfix expression*/ int cal(char post[]) { int m. break.x. case '/':return (8). case '-':return (7).").y. case ')':return (9). case '+':return (7). case '/':return (8). } return 0. case '-':return (7). case '+':return (7). case '\0':return (0).CP LAB switch(t) { case '(':return (10). case '\0':return (0). while(j<len) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .j=0. break. case '*':return (8).len.n.

67 switch(post[j]) { case '+':x=n+m. } j++. case '/':x=n/m. } if(st_top>0) { printf("Number of Operands are more than Operators."). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } return 0. return (y). break. break. } push_item(x). exit(0). } else { m=pop_item(). break.CP LAB if(isdigit(post[j])) { x=post[j]-'0'. break. push_item(x). case '*':x=n*m. } else { y=pop_item(). case '-':x=n-m. n=pop_item().

&choice). void TraverseInorder(struct treenode *t). }.value. #include<stdio. printf("[1] Create a Binary Tree and Use Inorder Traversal\n"). printf("\t\t\tMENU\n"). printf("[3] Create a Binary Tree and Use Postorder Traversal\n"). scanf("%d". printf("----------------------------------------------------\n"). void TraversePreorder(struct treenode *t). Write a C program that uses functions to perform the following: i) Creating a Binary Tree of integers ii) Traversing the above binary tree in preorder. int num. int choice. inorder and postorder.CP LAB 68 28. struct treenode *insert_node(struct treenode *t. *r_child. struct treenode *l_child.h> #include<conio. printf("-----------------------------------------------------\n"). clrscr().int a).h> #include <stdlib. void TraversePostorder(struct treenode *t). /*main function*/ void main() { struct treenode *root_node = NULL. printf("Enter your choice:"). printf("[2] Create a Binary Tree and Use Preorder Traversal\n").h> struct treenode { int ele. printf("-----------------------------------------------------\n"). if(choice>0 & choice<=3) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

scanf("%d". break. } } } /*end main*/ /* Function to create a Binary Tree of integers data */ struct treenode *insert_node(struct treenode *t. getch().int a) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .> 0) { printf("\n\nEnter the data value:"). root_node = insert_node(root_node.value).&num). } switch(choice) { case 1: printf("\n\nBinary tree using Inorder Traversal : "). TraverseInorder(root_node). scanf("%d". 69 while(num-. getch(). TraversePostorder(root_node). break. case 2: printf("\n\nBinary tree using Preorder Traversal : "). getch(). break. TraversePreorder(root_node). break. default: printf("Invalid Choice").&value).CP LAB printf("\nEnter the number of nodes:"). case 3: printf("\n\nBinary tree using Postorder Traversal : ").

exit(0).*temp_node2. } else { temp_node2->r_child = (struct treenode*)malloc(sizeof(struct treenode)). if( temp_node1 ->ele > a) temp_node1 = temp_node1->l_child. } t->ele = a. temp_node2 = temp_node2->l_child. else temp_node1 = temp_node1->r_child. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } temp_node2->ele = a. exit(0). temp_node2->l_child=temp_node2->r_child = NULL. 70 while(temp_node1 != NULL) { temp_node2 = temp_node1.CP LAB struct treenode *temp_node1. if(temp_node2 == NULL) { printf("Value cannot be allocated. if(t == NULL) { printf("Value cannot be allocated. if(t == NULL) { t = (struct treenode *) malloc(sizeof(struct treenode)).\n").\n"). t->l_child=t->r_child=NULL. temp_node2 = temp_node2->r_child. } if( temp_node2->ele > a) { temp_node2->l_child = (struct treenode*)malloc(sizeof(struct treenode)). } else { temp_node1 = t.

TraversePostorder(t->r_child). TraversePreorder(t->l_child). } 71 /* Function for Traversing the binary tree in inorder.CP LAB if(temp_node2 == NULL) { printf("Value cannot be allocated. } } /* Function for Traversing the binary tree in preorder.\n"). */ void TraversePreorder(struct treenode *t) { if(t != NULL) { printf("%d\t". TraversePreorder(t->r_child).t->ele). in_order(t->r_child). printf("%d\t". exit(0). */ void TraversePostorder(struct treenode *t) { if(t != NULL) { TraversePostorder(t->l_child). } } return(t). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } temp_node2->ele = a. */ void TraverseInorder(struct treenode *t) { if(t != NULL) { TraverseInorder(t->l_child). temp_node2->l_child=temp_node2->r_child = NULL. } } /* Function for Traversing the binary tree in postorder.t->ele).

} } 72 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .t->ele).CP LAB printf("%d\t".

print_list(l.int ele).&num). void print_list(int l[]. if(ch<=2 & ch>0) { printf("Enter the number of elements :"). read_list(l. printf("\n\nEnter your Choice:").h> #define MAX_LEN 10 ii) Binary search void l_search_recursive(int l[]. void main() { int l[MAX_LEN]. switch(ch) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .int num). printf("\nElements present in the list are:\n\n"). num.num).CP LAB 73 29. int ch. void read_list(int l[].int num. printf("\n=====================================================").&ch). printf("======================================================"). void l_search(int l[]. printf("\n[1] Linary Search using Recursion method").num).int num. printf("\n\t\t\tMENU").int num). printf("\n\nElement you want to search:\n\n"). ele. printf("\n[2] Linary Search using Non-Recursion method"). clrscr(). scanf("%d". scanf("%d". scanf("%d".int ele). Write C programs that use both recursive and non recursive functions to perform the following searching operations for a Key value in a given list of integers : i) Linear search i) Linear search #include <stdio.&ele).

int num. for(j=0. getch(). } /*end main*/ /* Non-Recursive method*/ void l_search_nonrecursive(int l[].j). } /* Recursive method*/ void l_search_recursive(int l[]. getch(). f=1.ele). break. if( l[num] == ele) { printf("\nThe element %d is present at position %d in list\n".ele. } else SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .ele).int ele) { int f = 0.ele.ele). l_search_nonrecursive(l.int num. break.j++) if( l[j] == ele) { printf("\nThe element %d is present at position %d in list\n". f=1. break. } } getch().num.j<num.num). } if(f==0) printf("\nThe element is %d is not present in the list\n".num.CP LAB case 1:printf("\n**Recursion method**\n"). 74 case 2:printf("\n**Non-Recursion method**\n"). f=0. l_search_recursive(l.int ele) { int j.

num-1. } 75 void read_list(int l[].ele).j++) printf("%d\t".l[j]). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .".CP LAB { if((num==0) && (f==0)) { printf("The element %d is not found.j++) scanf("%d".int num) { int j.&l[j]). } } getch().ele). } void print_list(int l[].j<num.j<num.int num) { int j. for(j=0. } else { l_search(l. for(j=0. printf("\nEnter the elements:\n").

else i = j-1.int ele) { int l1. } else if(l[j] < ele) l1 = j+1. break.j). } if( flag == 0) printf("\nThe element %d is not present in the list\n". flag =1. } 76 /* Recursive function*/ int b_search_recursive(int l[]. if( l[j] == ele) { printf("\nThe element %d is present at position %d in list\n".j.h> #define MAX_LEN 10 /* Non-Recursive function*/ void b_search_nonrecursive(int l[].ele.int a) { int m. i = num-1.int arrayEnd. flag = 0.int arrayStart. l1 = 0. if (arrayStart<=arrayEnd) { m=(arrayStart+arrayEnd)/2.int num.ele). if (l[m]==a) return m. else if (a<l[m]) SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .CP LAB ii) Binary search #include <stdio.i.pos. while(l1 <= i) { j = (l1+i)/2.

ele. for(i=0.&l[i]).i<n.i++) printf("%d\t". printf("\n\t\t\tMENU").arrayEnd. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .a. } /*main function*/ void main() { int l[MAX_LEN]. printf("======================================================").a).m+1. printf("\n[2] Binary Search using Non-Recursion method"). int ch. clrscr(). for(i=0.a).int n) { int i.i<n.l[i]).f. printf("\n=====================================================").arrayStart. printf("\n[1] Binary Search using Recursion method").CP LAB return b_search_recursive(l.l1.&ch). else return b_search_recursive(l. printf("\nEnter the elements:\n"). } 77 void print_list(int l[].m-1. printf("\n\nEnter your Choice:"). scanf("%d".int n) { int i. num. } return -1.i++) scanf("%d". } void read_list(int l[]. if(ch<=2 & ch>0) { printf("\nEnter the number of elements : ").pos.

} SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .num. } } getch().ele).ele). printf("\nElements present in the list are:\n\n").num). 78 switch(ch) { case 1:printf("\nRecursive method:\n").&ele). if(pos==-1) { printf("Element is not found"). break.&num). pos=b_search_recursive(l. print_list(l. } else { printf("Element is found at %d position". case 2:printf("\nNon-Recursive method:\n").CP LAB scanf("%d". read_list(l.0. b_search_nonrecursive(l.num). printf("\n\nEnter the element you want to search:\n\n").num. } getch().pos). getch(). break. scanf("%d".

printf("\nEnter the elements: \n"). } ii) Quick sort // Function for Bubble Sort void bub_sort(int list[]. *n = temp. for(j=0.j<(n-(i+1)). *m = *n.i<(n-1).j<n.i++) for(j=0. } // Showing the contents of the list void printlist(int list[]. } void readlist(int list[]. int n) { int i.int n) { int j.j++) scanf("%d".h> #define MAX 10 void swapList(int *m.list[j]).j++) if(list[j] > list[j+1]) swapList(&list[j].CP LAB 79 30. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .j++) printf("%d\t".&list[j]).j<n. for(i=0.&list[j+1]). temp = *m.int *n) { int temp.j. for(j=0. Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Bubble sort i) Bubble sort #include <stdio.int n) { int j.

num).&num). num.CP LAB } 80 void main() { int list[MAX].num).num). printf("\n\n\n***** Enter the number of elements [Maximum 10] *****\n"). printf("\n\nElements in the list before sorting are:\n"). printlist(list. clrscr(). readlist(list. scanf("%d".num). printlist(list. printf("\n\nElements in the list after sorting are:\n"). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . getch(). bub_sort(list.

j = n.m.j+1.h> #define MAX 10 void swap(int *m. while(i <= j) { while((i <= n) && (list[i] <= key)) i++. quicksort(list. *n = temp. } 81 // Function for Quick Sort void quicksort(int list[]. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . quicksort(list.k.int y ) { return((x+y) /2).CP LAB ii) Quick sort #include <stdio.int *n) { int temp.j.int m. while((j >= m) && (list[j] > key)) j--. i = m+1.i.n). *m = *n. swap(&list[m]. temp = *m. key = list[m]. } swap(&list[m]. if( m < n) { k = get_key_position(m.n). if( i < j) swap(&list[i]. } int get_key_position(int x.&list[k]).int n) { int key.&list[j]).j-1).&list[j]).

for(j=0. read_data(list.num).num-1). scanf("%d". print_data(list.&list[j]). clrscr().j++) printf("%d\t". printf("\n\nElements in the list before sorting are:\n"). print_data(list.0.j++) scanf("%d". printf("\n\nElements in the list after sorting are:\n").j<n. printf("\n\nEnter the elements:\n"). num.CP LAB } } 82 // Function to read the data void read_data(int list[].j<n.num). for(j=0. } // Function to print the data void print_data(int list[].int n) { int j.num).int n) { int j. printf("\n***** Enter the number of elements Maximum [10] *****\n"). } void main() { int list[MAX]. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . getch().&num).list[j]). quicksort(list.

j. clrscr(). for (count=0. void main() { int num[5].count++) printf("%d\n". Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Insertion sort ii) Merge sort i) Insertion sort #include<stdio.j++) { k=num[j]. for(i=j-1.CP LAB 83 31.count. printf("\n\nElements after sorting: \n").count<5. for(j=1. } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .count++) scanf("%d". } // Function for Insertion Sorting void inst_sort(int num[]) { int i.j<5. for(count=0.h> #include<conio.num[count]).i>=0 && k<num[i]. getch().count<5.k.&num[count]). inst_sort(num).i--) num[i+1]=num[i]. num[i+1]=k. printf("\nEnter the Five Elements to sort:\n").h> void inst_sort(int []).

j++) scanf("%d". /* array after mergesort */ printf("After Merge Sort :"). int mid = 0. const int size = start .1). printf("\n").h> #include <stdlib. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . MAX_ARY .end + 1. int end. ary[j]). printf("\n"). for(j = 0.CP LAB ii) Merge sort #include <stdio. for(j = 0. int start). int start) { int j = 0. int end. getch(). j < MAX_ARY. int j = 0.j<MAX_ARY. } /* Method to implement Merge Sort*/ void merge_sort(int x[]. j++) printf(" %d". j++) printf(" %d". ary[j]). merge_sort(ary. int main(void) { int ary[MAX_ARY].h> #define MAX_ARY 10 84 void merge_sort(int x[].&ary[j]). printf("\n\nEnter the elements to be sorted: \n"). 0. for(j=0. j < MAX_ARY. /* array before mergesort */ printf("Before :").

else x[j + end] = executing[mrg1++]. else x[j + end] = executing[mrg2++]. j < size. } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .CP LAB int mrg1 = 0. end. else x[j + end] = executing[mrg1++]. mrg2 = mid . j < size. int executing[MAX_ARY].end + 1.end) if(executing[mrg1] > executing[mrg2]) x[j + end] = executing[mrg2++]. mid). merge_sort(x. 85 if(end == start) return. merge_sort(x. mrg1 = 0. start). mid + 1. for(j = 0. mid = (end + start) / 2.end) if(mrg1 <= mid . j++) { if(mrg2 <= start . for(j = 0. j++) executing[j] = x[end + j]. int mrg2 = 0.

&x). scanf("%f". } y+=(numerator/denominator)*arr_y[i]. i<=n. i<=n.h> #include<conio. j<=n. clrscr().1f\n". numerator. for(i=0. &arr_y[i]). } printf("When x=%4. printf("Enter the value of n: \n"). x. i++) scanf("%f%f". printf("Enter the values of x and y: \n"). arr_y[MaxN+1]. int i. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . &arr_x[i]. n. j++) if(j!=i) { numerator *= x-arr_x[j]. &n).Gregory forward interpolation. getch(). for (j=0. i++) { numerator=1. Lagrange interpolation: #include<stdio. scanf("%d".x. denominator. printf("Enter the value of x at which value of y is to be calculated: "). for (i=0. denominator=1. j. denominator *= arr_x[i]-arr_x[j].1f y=%7. Write C programs to implement the Lagrange interpolation and Newton.y). y=0.CP LAB 86 32.h> #define MaxN 90 void main() { float arr_x[MaxN+1].

i++) diff_table[i][j]=diff_table[i+1][j-1] .Gregory forward interpolation.0. i=0. for (k=1. scanf("%f". i--.&n)./*Creating the difference table and calculating first order differences*/ for(j=2. i++) scanf("%f%f". h=arr_x[1]-arr_x[0]. &x). &arr_y[i]). numerator=1. y=arr_y[i]. k++) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . denominator=1. x. clrscr(). while(!(arr_x[i]>x)) /* Finding x0 */ i++.n. j<=Order_of_diff. y.k.CP LAB Newton.h> #include<conio. printf("Enter the values of x and y"). h. k<=Order_of_diff. for(i=0. scanf("%d". p=(x-arr_x[i])/h.: #include<stdio. i<=n-1. for(i=0.h> #define MaxN 100 #define Order_of_diff 4 87 void main () { float arr_x[MaxN+1]. &arr_x[i].0. j++)/*Calculating higher order differences*/ for(i=0. i<=n-j. i<=n.diff_table[i][j-1]. diff_table[MaxN+1][Order_of_diff+1]. i++) diff_table[i][1]=arr_y[i+1]-arr_y[i].j. int i. arr_y[MaxN+1]. p. printf("Enter the value of n \n"). printf("Enter the value of x at which value of y is to be calculated").

denominator *=k. getch().1f. y +=(numerator/denominator)*diff_table[i][k]. } printf("When x=%6. y=%6. y).CP LAB numerator *=p-k+1.x.2f\n". } 88 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

for(i=0.b[20].dx.&n).h> #include<string.reg_coff_xy=0.n).dx[20].&sy). mean_x=mean(a.i=0.i<n.&a[i].i++) scanf("%f%f". int n. printf("Enter the value of n: "). fflush(stdin).sx=0.mean_y. gets(type_coff). Write C programs to implement the linear regression and polynomial regression algorithms #include<stdio.&b[i]).h> #include<math. int n). clrscr(). corr_coff=sum_xy/(n*sx*sy).&sx).i++) sum_xy=sum_xy+dx[i]*dy[i].dy.h> float mean(float *a. deviation(a. void main() { float a[20]. mean_y=mean(b.sum_xy=0. int n=0. reg_coff_yx=0. printf("Enter the values of x and y:\n"). float corr_coff=0.n.h> #include<conio.CP LAB 89 33.mean_x=0. float mean.i<n. if(strcmp(type_coff. float sy=0.dy[20]. float *S). deviation(b."x on y")==1) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . float *d. scanf("%d". void deviation(float *a.mean_y=0.n). for(i=0. char type_coff[7].mean_x. printf("Enter the type of regression coefficient as 'x on y' or 'y on x': ").n.

sum=sum+t. printf("\nThe value of linear regression coefficient is %f". float mean. sum=sum/n. int i=0. t=d[i]*d[i]. } else printf("\nEnter the correct type of regression coefficient. } sum=sum/n.i++) sum=sum+a[i]. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .t=0.reg_coff_xy). int n. return (sum). int n) { float sum=0."y on x")==1) { reg_coff_yx=corr_coff*(sy/sx).i<n."). } void deviation(float *a.reg_coff_yx).CP LAB reg_coff_xy=corr_coff*(sx/sy).i<n. float *d. printf("\nThe value of linear regression coefficient is %f". float *s) { float sum=0. } 90 float mean(float *a. getch(). i=0. *s=sqrt(sum).i++) { d[i]=a[i]-mean. for(i=0. for(i=0. } else if(strcmp(type_coff.

infix_postfix(arr). i++) arr[0]=exp[i+3]. char stack1[80].l=0. s=log(e1)+log(e2). arr[i]='\0'. char exp[80].CP LAB 34. e2=eval(postfix. int top=-1. for (i=1.x0+i*h)).xn).i++) s+=2*log(eval(postfix. &n). int i. float stack[80]. &xn. xn.x0). xn and number of subintervals"). gets(exp).i<=n-1. Write C programs to implement 91 Trapezoidal and Simpson methods. float x1). void infix_postfix(char infix[]). printf("\nEnter an expression: "). &x0.h> char postfix[80]. h=(xn-x0)/n.i<l-3.e1. float eval(char postfix[]. e1=eval(postfix. for(i=0.h> #include<conio. clrscr().h> #include<math. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . main() { float x0.top1=-1.n. s. h.e2. scanf("%f%f%d". puts("Enter x0. if(exp[0]=='l'&& exp[1]=='o'&& exp[2]=='g') { l=strlen(exp). Trapezoidal: #include<stdio. arr[80].

3f\n". if(top==-1) { printf("\n\tThe stack is empty\n\t"). s=eval(postfix. */ float pop() { float item.xn). getch().x0)+eval(postfix. } printf("Value of the integral is %6. stack[top]=item. } void push1(char item) { 92 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . } item=stack[top]. exit(0). } /*Inserting the operands in a stack. */ void push(float item) { if(top==99) { printf("\n\tThe stack is full").CP LAB else { infix_postfix(exp). top--. getch().i<=n-1. } else { top++.(h/2)*s). return(0). } return.x0+i*h). return (item). for (i=1. } /*Removing the operands from a stack.i++) s+=2*eval(postfix.

i++) postfix[i]=' '. } else { top1++. if(top1==-1) { printf("\n\tThe stack1 is empty\n\t"). getch(). } item=stack1[top1]. */ void infix_postfix(char infix[]) { int i=0.j=0. */ char pop1() { char item. stack1[top1]=item. push1('?'). char ch. char token. for(i=0.k. exit(0).i<79. i=0. top1--.CP LAB if(top1==79) { printf("\n\tThe stack is full"). } /*Converting an infix expression to a postfix expression. token=infix[i]. } return. return (item). } /*Removing the operands from a stack. while(token!='\0') { if(isalnum(token)) { 93 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . getch().

} else { 94 while(ISPriority(stack1[top1])>=ICP(token)) { ch=pop1(). j++. j++. token=infix[i]. } postfix[j]='\0'. postfix[j]=ch. j++. /*Assigning the popped element into the postfix array. postfix[j]=ch. } push1(token). } ch=pop1(). } i++. } else if(token=='(') { push1('('). j++. } else if(token==')') { while(stack1[top1]!='(') { ch=pop1(). } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .CP LAB postfix[j]=token. */ postfix[j]=ch. } while(top1!=0) { ch=pop1().

case '-':return (7). break. break. case ')':return (9). while(i<l) { 95 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . */ int ICP(char token) { switch(token) { case '(':return (10). } return 0. case '+':return (7).CP LAB int ISPriority(char token) { switch(token) { case '(':return (0). case '-':return (7). } /*Determining the priority of elements that are approaching towards the stack.t2. case '?':return (0). default: printf("Invalid expression"). int i=0. l=strlen(p). case ')':return (9). } /*Calculating the result of expression. case '*':return (8).l. case '+':return (7). case '\0':return (0). which is converted in postfix notation. case '/':return (8). float x1) { float t1.k. case '*':return (8). case '/':return (8). } return 0. */ float eval(char p[]. default: printf("Invalid expression").r.

} 96 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . exit(0). } if(top>0) { printf("You have entered the operands more than the operators"). return (r). else if(isdigit(p[i])) { k=p[i]-'0'. break.CP LAB if(p[i]=='x') push(x1). } else { t1=pop(). t2=pop(). break. push(k). } i++. } return 0. break. case '-':k=t2-t1. } else { r=pop(). } push(k). case '/':k=t2/t1. break. break. case '*':k=t2*t1. switch(p[i]) { case '+':k=t2+t1. default: printf("\n\tInvalid expression").

CP LAB 97 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

h> #include<conio. e3=4*eval(postfix.l=0. int i.i<l-3. if(exp[0]=='l'&& exp[1]=='o'&& exp[2]=='g') { l=strlen(exp). int top=-1. &xn. gets(exp).i+=2) s+=4*eval(postfix. xn. char stack1[80]. for(i=0.x0+i*h)+2*eval(postfix.x0).n. puts("Enter x0. e2=eval(postfix. } else { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .h> 98 char postfix[80]. float x1). arr[80].h> #include<math. s.e2.e1. void infix_postfix(char infix[]).i<=n-1. char exp[80]. for (i=3. e3. clrscr(). x0+(i-1)*h). xn and number of sub-intervals: "). arr[i]='\0'. float stack[80]. &x0. h=(xn-x0)/n. s=log(e1)+log(e2)+log(e3). h. &n).CP LAB Simpson methods: #include<stdio. e1=eval(postfix. infix_postfix(arr). main() { float x0.top1=-1.xn). scanf("%f%f%d". printf("\nEnter an expression: "). x0+h). float eval(char postfix[]. i++) arr[0]=exp[i+3].

CP LAB
infix_postfix(exp); s=eval(postfix,x0)+eval(postfix,xn)+4*eval(postfix, x0+h); for (i=3;i<=n-1;i+=2) s+=4*eval(postfix,x0+i*h)+2*eval(postfix, x0+(i-1)*h); } printf("The value of integral is %6.3f\n",(h/3)*s); return(0); } /*Inserting the operands in a stack. */ void push(float item) { if(top==99) { printf("\n\tThe stack is full"); getch(); exit(0); } else { top++; stack[top]=item; } return; } /*Removing the operands from a stack. */ float pop() { float item; if(top==-1) { printf("\n\tThe stack is empty\n\t"); getch(); } item=stack[top]; top--; return (item); } void push1(char item) { if(top1==79) {

99

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB
printf("\n\tThe stack is full"); getch(); exit(0); } else { top1++; stack1[top1]=item; } return; } /*Removing the operands from a stack. */ char pop1() { char item; if(top1==-1) { printf("\n\tThe stack1 is empty\n\t"); getch(); } item=stack1[top1]; top1--; return (item); } /*Converting an infix expression to a postfix expression. */ void infix_postfix(char infix[]) { int i=0,j=0,k; char ch; char token; for(i=0;i<79;i++) postfix[i]=' '; push1('?'); i=0; token=infix[i]; while(token!='\0') { if(isalnum(token)) { postfix[j]=token; j++;

100

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

CP LAB
} else if(token=='(') { push1('('); } else if(token==')') { while(stack1[top1]!='(') { ch=pop1(); postfix[j]=ch; j++; } ch=pop1(); } else { while(ISPriority(stack1[top1])>=ICP(token)) { ch=pop1(); postfix[j]=ch; j++; } push1(token); } i++; token=infix[i]; } while(top1!=0) { ch=pop1(); postfix[j]=ch; j++; } postfix[j]='\0'; }

101

/*Determining the priority of elements that are placed inside the stack. */ int ISPriority(char token) { switch(token)

SARADA INSTITUTE OF TECHNOLOGY & SCIENCE

t2. } return 0.l. case '-':return (7). */ int ICP(char token) { switch(token) { case '(':return (10). case '\0':return (0). case '+':return (7). } 102 /*Determining the priority of elements that are approaching towards the stack. case '-':return (7). case ')':return (9). l=strlen(p). case '/':return (8).CP LAB { case '(':return (0). float x1) { float t1. */ float eval(char p[]. default: printf("Invalid expression"). } /*Calculating the result of expression.r. while(i<l) { if(p[i]=='x') push(x1). else if(isdigit(p[i])) SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . case '?':return (0). int i=0.k. case '+':return (7). which is converted in postfix notation. case '*':return (8). case '/':return (8). } return 0. case ')':return (9). case '*':return (8). default: printf("Invalid expression").

break. } else { t1=pop(). } 103 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . return (r). exit(0). } else { r=pop(). t2=pop(). break. } return 0.CP LAB { k=p[i]-'0'. case '/':k=t2/t1. case '-':k=t2-t1. case '*':k=t2*t1. } if(top>0) { printf("You have entered the operands more than the operators"). switch(p[i]) { case '+':k=t2+t1. } i++. } push(k). break. break. default: printf("\n\tInvalid expression"). push(k).

Programming in C. Padmanabham. C programming and Data Structures. Ghosh. Third Edition. 4. Gilberg and B. TMH publications. second edition R. Data Structures: A pseudo code approach with C. P.CP LAB 104 REFERENCES: 1. P.A. Oxford Univ.F. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . BS Publications 2. Forouzan 3.Dey & M. E Balaguruswamy.Press. C and Data Structures.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times