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

CP LAB Week 13 Write a C program that uses functions to perform the following operations on singly linked list. 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. ii) Quick sort Week 23 Write C programs to implement the linear regression and polynomial regression algorithms. inorder and postorder. SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .: 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.Gregory forward interpolation.: 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

switch(opern) { case 0: exit(0). case 1: case 2: arithmetic(opern). double imgpart.CP LAB 32 20. clrscr(). default: main().&opern).h> void arithmetic(int opern). 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. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . struct comp { double realpart. scanf("%d". }.) #include<stdio. void main() { int opern.h> #include<math. 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").

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

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

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

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

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

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

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

scanf("%d". int a). if(head->number == key) { p = head->next.CP LAB node *delete(node *head) { node *find(node *p. n1->next = p. else { p = n1->next->next.h> #include <stdlib. key). node *n1. head = p.h> #define NULL 0 struct linked_list { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . /* 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?"). int key. node *p. free(n1->next). if(n1 == NULL) printf("\n key not found \n"). free(head). } /* free key node */ /* establish link */ iv) Traversal #include <stdio. &key). } } return(head). } else { n1 = find(head.

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

p2 = p2->next) { p1 = p2. break. } return. if (p1 == NULL) list = p. } void print(node *list) { if (list == NULL) printf("NULL").CP LAB for( .list->number). /* space for new node */ p->number = x. } } /* 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 . print(list->next). else { printf("%d-->". p->next = p2. node */ else p1->next = p. p2->number < x . 42 if(p2->next == NULL) { p2 = p2->next.

DUBLL Search(int item. printf("\n \t\t\t***** M A I N M E N U *****\n\n"). scanf("%d".last.: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways #include "stdio.temp_node.Item. int flag=0. struct dubll *leftlink. }*DUBLL.CP LAB 43 24.pntr. high=NULL. void PrintItem().int). void AppendItem().low. DUBLL NodeAlloc(). void main(void) { int choice. switch(choice) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . DUBLL Search(int. void CreateItem().h" #include "alloc.h" typedef struct dubll { int data.&choice). void InsertItem().*rightlink. void DeleteItem(). 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"). while(1) { clrscr(). DUBLL NodeAlloc(). DUBLL high.int flag). Write a C program that uses functions to perform the following operations on doubly linked list.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

exit(1). } st[++st_top]=it. gets(in). int pop_item(). void push_item(int it). int st_ICP(char t).h> int st[100]. getch().CP LAB 63 27. int cal(char post[]).h> #include<conio. /*main function*/ void main() { char in[100]. printf("\n\tEnter the Infix Expression: "). int st_ISP(char t). getch(). clrscr().post[100]. } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . in_post(in). int st_top=-1. } /*end main*/ void push_item(int it) { if(st_top==99) { printf("\n\n\t*STACK is Full*"). 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.

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

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

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

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

}. printf("-----------------------------------------------------\n"). struct treenode *l_child. void TraversePostorder(struct treenode *t). void TraversePreorder(struct treenode *t).CP LAB 68 28.value. printf("\t\t\tMENU\n"). int choice. scanf("%d". printf("Enter your choice:"). *r_child. clrscr(). printf("[3] Create a Binary Tree and Use Postorder Traversal\n"). /*main function*/ void main() { struct treenode *root_node = NULL.&choice). int num.int a). inorder and postorder. printf("[1] Create a Binary Tree and Use Inorder Traversal\n").h> #include<conio. printf("-----------------------------------------------------\n"). if(choice>0 & choice<=3) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .h> #include <stdlib. void TraverseInorder(struct treenode *t). #include<stdio. 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. struct treenode *insert_node(struct treenode *t. printf("[2] Create a Binary Tree and Use Preorder Traversal\n").h> struct treenode { int ele. printf("----------------------------------------------------\n").

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

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

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

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

void l_search(int l[].num). scanf("%d".int ele). scanf("%d".int num).int num). clrscr().&ele).h> #define MAX_LEN 10 ii) Binary search void l_search_recursive(int l[]. printf("\n\nEnter your Choice:"). printf("\n\t\t\tMENU"). 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.&num). printf("======================================================"). void main() { int l[MAX_LEN]. int ch.int num. printf("\n[2] Linary Search using Non-Recursion method"). void print_list(int l[]. if(ch<=2 & ch>0) { printf("Enter the number of elements :"). void read_list(int l[].CP LAB 73 29.&ch).num). ele. printf("\n[1] Linary Search using Recursion method"). printf("\n\nElement you want to search:\n\n"). num. print_list(l. switch(ch) { SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .int num. read_list(l. printf("\n=====================================================").int ele). scanf("%d". printf("\nElements present in the list are:\n\n").

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

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

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

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

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

h> #define MAX 10 void swapList(int *m.j<n. temp = *m. } ii) Quick sort // Function for Bubble Sort void bub_sort(int list[]. int n) { int i.list[j]).int n) { int j. printf("\nEnter the elements: \n"). SARADA INSTITUTE OF TECHNOLOGY & SCIENCE . *n = temp. } void readlist(int list[].j.int *n) { int temp.&list[j]). for(i=0.i++) for(j=0. for(j=0.j<(n-(i+1)). for(j=0. *m = *n.j++) if(list[j] > list[j+1]) swapList(&list[j].j++) printf("%d\t".&list[j+1]).j<n.i<(n-1). 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.j++) scanf("%d".int n) { int j.CP LAB 79 30. } // Showing the contents of the list void printlist(int list[].

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

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

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

j<5.count. printf("\n\nElements after sorting: \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.h> void inst_sort(int []). for(j=1.CP LAB 83 31. for (count=0.&num[count]). clrscr(). for(i=j-1.num[count]). } } SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .j++) { k=num[j].j.h> #include<conio. for(count=0. } // Function for Insertion Sorting void inst_sort(int num[]) { int i.i--) num[i+1]=num[i]. num[i+1]=k.k. void main() { int num[5].count++) printf("%d\n".count<5. printf("\nEnter the Five Elements to sort:\n").count<5.count++) scanf("%d".i>=0 && k<num[i]. inst_sort(num). getch().

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

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

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

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

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

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

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

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

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

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

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

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

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

CP LAB 97 SARADA INSTITUTE OF TECHNOLOGY & SCIENCE .

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

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

Cancel anytime.