You are on page 1of 126

HI POINT COLLEGE OF ENGG & TECHNOLOGY C PROGRAMMING AND DATA STRUCTURES LAB MANUAL 1)Aim: Write a C program to find

the sum of individual digits of a positive integer. Explanation: we have to enter any 2 digits or 3 digit number, then it will give sum of the individual digits. #include<stdio.h> #include<conio.h> void main() { int num, k=1, sum=0; clrscr(); printf("Enter the number whose digits are to be added:"); scanf("%d",&num); while(num!=0) { k=num%10; sum=sum+k; k=num/10; num=k; } printf("Sum of the digits:%d",sum); getch(); } OUTPUT:

Enter the number whose digits are to be added: 123 Sum of digits: 6

2)Aim: Write a C program to generate the first n terms of the sequence. Explanation: 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.

#include <stdio.h> void main() { int num1=0, num2=1,no,counter,fab; clrscr(); printf("<===========PROGRAM TO FIND THE FIBONACCI SERIES UP TO N NO. IN SERIES=========>"); printf("\n\n\n\t\tENTER LENGTH OF SERIES (N) : "); scanf("%d",&no); printf("\n\n\t\t\t<----FIBONACCI SERIES---->"); printf("\n\n\t\t%d %d",num1,num2);

//LOOP WILL RUN FOR 2 TIME LESS IN SERIES AS THESE WAS PRINTED IN ADVANCE for(counter = 1; counter <= no-2; counter++) { fab=num1 + num2; printf(" %d",fab); num1=num2;

num2=fab; } getch(); } OUTPUT: <===========PROGRAM TO FIND THE FIBONACCI SERIES UP TO N NO. IN SERIES=========> ENTER LENGTH OF SERIES (N) : 6 <----FIBONACCI SERIES----> 0 1 1 2 3 5 3 ) Aim: Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. Explanation: User has to enter any value, then the program will print prime numbers below that value. #include <stdio.h> void main() { int no,counter,counter1,check; clrscr(); printf("<-----------------------PRIME NO. SERIES------------------------>"); printf("\n\n\n\t\t\tINPUT THE VALUE OF N: ");

scanf("%d",&no); printf("\n\nTHE PRIME NUMBER SERIES B/W 1 TO %d : \n\n",no); for(counter = 1; counter <= no; counter++) { check = 0; //THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT. for(counter1 = counter-1; counter1 > 1 ; counter1--) if(counter%counter1 == 0) { check++; break; } if(check == 0) printf("%d\t",counter); } getch(); } OUTPUT: <-----------------------PRIME NO. SERIES------------------------> INPUT THE VALUE OF N: 10 THE PRIME NUMBER SERIES B/W 1 TO 10 : 2 3 5 7 // INCREMENT CHECK IF NO. IS NOT A PRIME NO.

4)Aim: Write a C program to calculate the Sum:1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! Explanation: User has to enter x value.

#include <stdio.h> #include <math.h> void main() { int counter, f_coun; float sum=0,x,power,fact; clrscr(); printf("<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->"); printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!"); printf("\n\n\n\tENTER VALUE OF X : "); scanf("%f",&x); for(counter=0, power=0; power<=10; counter++,power=power+2) { fact=1; //CALC FACTORIAL OF POWER VALUE for(f_coun=power; f_coun>=1; f_coun--) fact *= f_coun; //EQ. FOR SUM SERIES sum=sum+(pow(-1,counter)*(pow(x,power)/fact)); } printf("SUM : %f",sum); getch();

OUTPUT: <-----------------------PROGRAM FOR SUM OF EQ. SERIES-----------------------> EQUATION SERIES: 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10! ENTER VALUE OF X: 2 SUM: -1 5))Aim: Write a C program to find the roots of a quadratic equation a*x*x+b*x+c. Explanation: User has to enter a,b and c values, then this program will give roots. #include<stdio.h> #include<conio.h> #include<math.h> void main() { float a,b,c,root1,root2; clrscr(); printf("\n Enter values of a,b,c for finding roots of a quadratic eq:\n"); scanf("%f%f%f",&a,&b,&c); /*checking condition*/ if(b*b>4*a*c) { root1=-b+sqrt(b*b-4*a*c)/2*a; root2=-b-sqrt(b*b-4*a*c)/2*a; printf("\n*****ROOTS ARE*****\n"); printf("\n root1=%f\n root2=%f",root1,root2);

} else printf("\n Imaginary Roots."); getch(); } OUTPUT: Enter values of a,b,c for finding roots of a quadratic eq: 2 5 3 *****ROOTS ARE***** root1= -1.5 root2=-1 6)Aim: Write C programs that use both recursive and non-recursive functions,to find the factorial of a given integer. Explanation: User has to enter any value, then this program will return factorial of a number using recursive and non-recursive functions. #include<stdio.h> #include<conio.h> unsigned int recr_factorial(int n); unsigned int iter_factorial(int n); void main() { int n,i; long fact; clrscr(); printf("Enter the number: ");

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

OUTPUT:

Enter the number:4 Factorial of 4 Using Recursive Function is:24 Factorial of 4 Using Non-Recursive Function is :24

7) Aim: Write C programs that use both recursive and non-recursive functions,to find the GCD (greatest common divisor) of two given integers. Explanation: User has to enter any two values,then this program will return GCD of two numbers. #include<stdio.h> #include<conio.h> #include<math.h> unsigned int GcdRecursive(unsigned m, unsigned n); unsigned int GcdNonRecursive(unsigned p,unsigned q); int main(void) { int a,b,iGcd; clrscr(); printf("Enter the two numbers whose GCD is to be found: "); scanf("%d%d",&a,&b); printf("GCD of %d and %d Using Recursive Function is %d\n",a,b,GcdRecursive(a,b)); printf("GCD of %d and %d Using Non-Recursive Function is %d\n",a,b,GcdNonRecursive(a,b));

getch(); }

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

if(remainder==0) return q; else GcdRecursive(q,remainder); }

Output Enter the two numbers whose GCD is to be found:80 45

GCD of 80 and 45 Using Recursive Function is:5 GCD of 80 and 45 Using Non-Recursive Function is :5 8 )Aim: Write a C program that use both recursive and non-recursive functions,to solve Towers of Hanoi problem. Explanation: User has to enter any values, then this program will return number of transitions. #include<conio.h> #include<stdio.h> /* Non-Recursive Function*/ void hanoiNonRecursion(int num,char sndl,char indl,char dndl) { char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp; int top,add; top=NULL; one: if(num==1) { printf("\nMove top disk from needle %c to needle %c ",sndl,dndl); goto four; } two: top=top+1; stkn[top]=num; stksndl[top]=sndl; stkindl[top]=indl; stkdndl[top]=dndl;

stkadd[top]=3; num=num-1; sndl=sndl; temp=indl; indl=dndl; dndl=temp; goto one; three: printf("\nMove top disk from needle %c to needle %c ",sndl,dndl); top=top+1; stkn[top]=num; stksndl[top]=sndl; stkindl[top]=indl; stkdndl[top]=dndl; stkadd[top]=5; num=num-1; temp=sndl; sndl=indl; indl=temp; dndl=dndl; goto one; four: if(top==NULL) return; num=stkn[top];

sndl=stksndl[top]; indl=stkindl[top]; dndl=stkdndl[top]; add=stkadd[top]; top=top-1; if(add==3) goto three; else if(add==5) goto four; }

/* Recursive Function*/ void hanoiRecursion( int num,char ndl1, char ndl2, char ndl3) { if ( num == 1 ) { printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 ); return; }

hanoiRecursion( num - 1,ndl1, ndl3, ndl2 ); printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 ); hanoiRecursion( num - 1,ndl3, ndl2, ndl1 ); }

void main()

{ int no; clrscr(); printf("Enter the no. of disks to be transferred: "); scanf("%d",&no);

if(no<1) printf("\nThere's nothing to move."); else printf("Non-Recursive"); hanoiNonRecursion(no,'A','B','C'); printf("\nRecursive"); hanoiRecursion(no,'A','B','C');

getch(); }

Output: Enter the no. of disks to be transferred:2 Non-Recursive Move top disk from needle A to needle B Move top disk from needle A to needle C Move top disk from needle B to needle C Recursive Move top disk from needle A to needle C

Move top disk from needle A to needle B Move top disk from needle C to needle B 9)Aim : Write a c program to calculate the expression ut+1/2at2. Explanation: The total distance travelled by vehicle in 't' seconds is given by distance=ut+1/2at2 , where 'u' and 'a' are the initial velocity (m/sec.) and acceleration (m/sec2) . 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' and 't'. #include <stdio.h> #include <math.h> void main() { int tim_intrval, counter,time; float accl, distance=0, velos; clrscr(); printf("<===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>"); printf("\n\n\n\t\t\tNO OF TIME INTERVALS : "); scanf("%d",&tim_intrval);

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

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

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

Output <===========PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL===========>

NO OF TIME INTERVALS :2

AT T1 TIME(sec) :3 VELOCITY AT 3 sec (m/sec) :4 ACCLERATION AT 3 sec (m/sec^2):2 AT T2 TIME(sec) :1 VELOCITY AT 3 sec (m/sec) :5 ACCLERATION AT 3 sec (m/sec^2):7 TOTAL DISTANCE TRAVELLED BY VEHICLE IN 2 INTERVALS OF TIME :29.500000 10)Aim: 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)

Explanation:User has to enter value that should be below 5,because based on that value program will perform operation(addition or subtraction or multiplication or division or Modulous division).Again user has to enter any two values,then program will give result based on the operator.

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

void main() { int a,b,res,ch; clrscr(); printf("\t *********************"); printf("\n\tMENU\n"); printf("\t********************"); printf("\n\t(1)ADDITION"); printf("\n\t(2)SUBTRACTION"); printf("\n\t(3)MULTIPLICATION"); printf("\n\t(4)DIVISION"); printf("\n\t(5)REMAINDER"); printf("\n\t(0)EXIT"); printf("\n\t********************"); printf("\n\n\tEnter your choice:"); scanf("%d",&ch);

if(ch<=5 & ch>0)

{ printf("Enter two numbers:\n"); scanf("%d%d",&a,&b); }

switch(ch) { case 1: res=a+b; printf("\n Addition:%d",res); break;

case 2: res=a-b; printf("\n Subtraction:%d",res); break;

case 3: res=a*b; printf("\n Multiplication:%d",res); break;

case 4: res=a/b; printf("\n Division:%d",res);

break;

case 5: res=a%b; printf("\n Remainder:%d",res); break;

case 0: printf("\n Choice Terminated"); exit(); break;

default: printf("\n Invalid Choice"); } getch(); }

Output ********************* MENU ********************* (1)ADDITION (2)SUBTRACTION (3)MULTIPLICATION

(4)DIVISION (5)REMAINDER (0)EXIT ******************** Enter your choice:1 Enter two numbers:2 4 Addition:6 11) Write a C program to find both the largest and smallest number in a list of integers*/ #include<stdio.h> void main( ) { int largest(int a[ ], int n); int smallest(int a[ ], int m); int value[4] = {2,7,3,5}; clrscr(); printf("Largest value is: %d\n", largest(value,4)); printf("Smallest value is: %d\n", smallest(value,4)); getch(); } int largest(int a[], int n) { int i; int max; max = a[0];

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

Output

Largest value is: 7 Smallest value is :4 12)Aim: Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices Explanation: User has to choose one option addition or multiplication. If that value is valid then it will proceed else it will exit.Then user has to enter number of rows and columns of a

matrix.Next user has to enter values into matrix.If thematrix is 2*2 size,then user must pass 4 values.If it is 2*3 matrix user has to enter 6 values.

#include<stdio.h> void main() { int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10]; clrscr(); printf("************************************"); printf("\n\t\tMENU"); printf("\n**********************************"); printf("\n[1]ADDITION OF TWO MATRICES"); printf("\n[2]MULTIPLICATION OF TWO MATRICES"); printf("\n[0]EXIT"); printf("\n**********************************"); printf("\n\tEnter your choice:\n"); scanf("%d",&ch);

if(ch<=2 & ch>0) { printf("Valid Choice\n"); }

switch(ch)

{ case 1: printf("Input rows and columns of A & B Matrix:"); scanf("%d%d",&r1,&c1); printf("Enter elements of matrix A:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("Enter elements of matrix B:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&b[i][j]); } printf("\n =====Matrix Addition=====\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d",a[i][j]+b[i][j]); printf("\n"); } break;

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

printf("Resultant of two matrices:\n");

write_matrix(c,m,q); } /*end if*/ else { printf("Matrices cannot be multiplied."); } /*end else*/ break;

case 0: printf("\n Choice Terminated"); exit(); break;

default: printf("\n Invalid Choice"); } getch(); }

/*Function read matrix*/ int read_matrix(int a[10][10],int m,int n) { int i,j;

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

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

Output: ************************************ MENU ************************************ [1]ADDITION OF TWO MATRICES [2]MULTIPLICATION OF TWO MATRICES

[0]EXIT ********************************** Enter your choice:1 Valid choice Input rows and columns of A & B Matrix:2 2 Enter elements of matrix A: 1 2 3 4 Enter elements of matrix B: 5 6 7 8 =====Matrix Addition===== 6 10 8 12

13)Aim: Write a C program that uses functions to insert a sub-string in to given main string from a given position. Explanation: User has to enter two strings, then user has to enter the position, to insert second string in the first main string. #include <stdio.h> #include <conio.h> #include <string.h>

void main() { char a[10]; char b[10]; char c[10]; int p=0,r=0,i=0; int t=0; int x,g,s,n,o; clrscr();

puts("Enter First String:"); gets(a); puts("Enter Second String:"); gets(b); printf("Enter the position where the item has to be inserted: "); scanf("%d",&p); r = strlen(a); n = strlen(b); i=0;

// Copying the input string into another array while(i <= r) { c[i]=a[i];

i++; } s = n+r; o = p+n;

// Adding the sub-string for(i=p;i<s;i++) { x = c[i]; if(t<n) { a[i] = b[t]; t=t+1; } a[o]=x; o=o+1; }

printf("%s", a); getch(); }

Output Enter First String: civil

Enter Second String: students Enter the position where the item has to be inserted:3 civstudentsil

14)Aim: Write a C program that uses functions to delete n Characters from a given position in a given string. Explanation:User has to enter any string, then again user has to enter the position Of character from where they want to delete and also user has to enter one more value it indicated the number of characters to delete from the apesified position.

#include <stdio.h> #include <conio.h> #include <string.h> void delchar(char *x,int a, int b); void main() { char string[10]; int n,pos,p; clrscr();

puts("Enter the string"); gets(string); printf("Enter the position from where to delete"); scanf("%d",&pos); printf("Enter the number of characters to be deleted");

scanf("%d",&n); delchar(string, n,pos); getch(); }

// Function to delete n characters void delchar(char *x,int a, int b) { if ((a+b-1) <= strlen(x)) { strcpy(&x[b-1],&x[a+b-1]); puts(x); } } Output Enter the string: students Enter the position from where to delete: 2 Enter the number of characters to be deleted:3 sents 15)Aim: Write a C program to determine if the given string is a palindrome or not Explanation: palindrome means it gives meaning from left to right and right to left. For example palindrome strings Malayalam, liril etc. numbers are 121,343,etc.User has to enter one value,then program will give whether that value is palindrome or not. #include<stdio.h>

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

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

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

OUTPUT ****Program to test if the given string is a palindrome**** Enter a string: liril The given string nitin is a palindrome

16)Aim: Write a C program to count the lines, words and characters in a given text. Explanation:User has to enter words with spaces,then this program will return number of lines entered ,number of words and number of characters.

#include <stdio.h> void main() { char line[81], ctr; int i,c,end = 0,characters = 0,words = 0,lines = 0; printf("ENTER ANY MATTER.\n"); printf("GIVE ONE SPACE AFTER EACH WORD.\n"); printf("WHEN COMPLETED, PRESS ENTER \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 including white spaces= %d\n", characters); getch(); } Output ENTER ANY MATTER GIVE ONE SPACE AFTER EACH WORD WHEN COMPLETED, PRESS ENTER

Ayaan College Of Engineering And Technology. Students are good. Number of lines = 2 Number of words = 9 Number of characters including white spaces =60

17)Aim: Write a C program to generate Pascal's triangle. Explanation:User has to enter any value ,then it will give that many number of rows of pascal values.

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

void main() { int bin,p,q,r,x; clrscr(); bin=1; q=0;

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

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

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

OUTPUT Rows you want to input:5

Pascal's Triangle: 1 1 1 1 4 3 6 2 3

1 1 1 1 4 1

18)Aim:Write a C program to construct a pyramid of numbers. Explanation:User has to enter any value,then this program will return Pyramid of that many rows.

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

void main() { int num,i,y,x=35; clrscr(); printf("\nEnter the number to generate the pyramid:\n"); scanf("%d",&num); printf(pyramid is:); for(y=0;y<=num;y++) { /*(x-coordinate,y-coordinate)*/ gotoxy(x,y+1);

/*for displaying digits towards the left and right of zero*/ for(i=0-y;i<=y;i++)

printf("%3d",abs(i)); x=x-3; }

getch(); }

OUTPUT Enter the number to generate the pyramid: 3 pyramid is: 1 2 3 2 1 1 0 0 0 0 1 1 1 2 2 3

19)Aim: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 . Explanation:If n value is negative program will terminate.so user should pass only positive values for n variable. For example: if n is 3 and x is 5, then the program computes 1+5+25+125.

#include<stdio.h> #include<conio.h> #include<math.h> void main() { int s_sum,i,x,n; clrscr(); printf("Enter the values for x and n:"); scanf("%d %d",&x,&n); if(n<=0 || x<=0) {

printf("Value is not valid\n"); } else { printf("Value is valid\n"); s_sum=1; for(i=1;i<=n;i++) { s_sum=s_sum+pow(x,i); } printf("Sum of series=%d\n",s_sum); } getch(); }

OUTPUT Enter the values for x and n:4 3 Value is valid Sum of series=85

20)Aim: Write a C program to find the 2s complement of a binary number. Explanation: User has to enter only binary values. Then it program will return 2s complement of that number. Otherwise program will terminate. 2s complement of a number is obtained by scanning it from right to left and complementing all the bits then add 1to the right most bit. For example 2s complement of 11011 is calculated as: first complement all the bits then will get 00100.Next add to right most bit then we will get 00101.

#include <stdio.h> #include<conio.h> void complement (char *a); void main() { char a[16]; int i; clrscr(); printf("Enter the binary number"); gets(a); for(i=0;a[i]!='\0'; i++) { if (a[i]!='0' && a[i]!='1') { printf("The number entered is not a binary number. Enter the correct number"); exit(0); } } complement(a);

getch(); } void complement (char *a) { int l, i, c=0; char b[16]; l=strlen(a); for (i=l-1; i>=0; i--) { if (a[i]=='0') b[i]='1'; else b[i]='0'; } for(i=l-1; i>=0; i--) { if(i==l-1) { if (b[i]=='0') b[i]='1'; else { b[i]='0'; c=1; }

} else { if(c==1 && b[i]=='0') { b[i]='1'; c=0; } else if (c==1 && b[i]=='1') { b[i]='0'; c=1; } } } b[l]='\0'; printf("The 2's complement is :%s", b); }

OUTPUT Enter the binary number: 0001001 The 2's complement is: 1110111 21)Aim: 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.) */ Explanation:User has to choose the option either addition or multiplication,then user has to enter one more value it indicates performing opearation among that many values.Next user has to enter real part and imaginary value.Then it will give choosen operation result. #include<stdio.h> #include<math.h> void arithmetic(int opern); struct comp { double realpart; double imgpart; }; void main() { int opern; clrscr(); printf("\n\n \t\t\t***** MAIN MENU *****"); printf("\n\n Select your option:\n1:ADD\n 2:MULTIPLY\n0:EXIT Option [ ]\b\b"); scanf("%d",&opern); switch(opern) { case 0: exit(0); \n\n\t\t Enter your

case 1: case 2: arithmetic(opern); default: main(); } } void arithmetic(int opern) {

struct comp w1, w2, w;

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

w.imgpart = w1.imgpart+w2.imgpart; break; /*multiplication of complex number*/ case 2: w.realpart=(w1.realpart*w2.realpart)- (w1.imgpart*w2.imgpart); w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart); break; } if (w.imgpart>0) printf("\n Answer = %lf+%lfi",w.realpart,w.imgpart); else printf("\n Answer = %lf%lfi",w.realpart,w.imgpart); getch(); main(); }

OUTPUT

***** MAIN MENU ***** Select your option: 1:ADD 2:MULTIPLY 0:EXIT Enter your Option [ 1 ] Enter two Complex Numbers (x+iy):

Real Part of First Number: 2.0 Imaginary Part of First Number: 4.0

Real Part of Second Number: 7.0 Imaginary Part of Second Number: 6.0 Answer = 9.000000+10.000000i 22)Aim: Write a C program which copies one file to another. Explanation:It will copy files. #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { FILE *fs,*ft; int a,b; clrscr(); printf(" copying files \n"); fs=fopen("ft.dat","r"); if(!a) { printf("nt able to open \n"); exit(101); } ft=fopen("fs.dat","w"); if(!ft) { printf("nt able to open \n"); exit(102); } while((fscanf(fs,"%d",&a))==1) fprintf(ft,"%d\n",a); b=fclose(ft); if(b==EOF) { printf("nt able to close\n"); exit(201); }

printf("File copy completed\n"); getch(); }

OUTPUT copying files File copy complete 23)Aim: Write a C program to reverse the first n characters in a file. Explanation:This program will return first n characters of a file in reverse order. #include<stdio.h> #include<conio.h> #include<string.h> #include<process.h> void main(int argc, char *argv[]) { char a[15]; char s[20]; char n; int k; int j=0; int i; int len; FILE *fp; printf(Program will reurn characters in reverse order); if(argc!=3)

{ puts("Improper number of arguments."); exit(0); } fp = fopen(argv[1],"r"); if(fp == NULL) { puts("File cannot be opened."); exit(0); } k=*argv[2]-48; n = fread(a,1,k,fp); a[n]='\0'; len=strlen(a); for(i=len-1;i>=0;i--) { s[j]=a[i]; printf("%c",s[j]); j=j+1; } s[j+1]='\0'; getch(); }

OUTPUT

Program will reurn characters in reverse order 24)Aim: Write a program to create a linear linked list interactively and print out the list and the total number of items in the list. Explanation:User has to enter any value in the list and user must enter -999 to end the list.Then this program will return list and also number values in the list.

#include<stdio.h> #include<stdlib.h> #define NULL 0 struct linked_list { int number; struct linked_list *next; }; typedef struct linked_list node; /* node type defined */

main() { node *head; void create(node *p); int count(node *p); void print(node *p); head = (node *)malloc(sizeof(node)); create(head); printf("\n"); print(head);

printf("\n"); printf("\nNumber of items = %d \n", count(head)); getch(); } void create(node *list) { printf("Input a number\n"); printf("(type -999 at end): "); scanf("%d", &list -> number); /* create current node */

if(list->number == -999) { list->next = NULL; }

else {

/*create next node */

list->next = (node *)malloc(sizeof(node)); create(list->next); /* Recursion occurs */ } return; } void print(node *list) { if(list->next != NULL)

{ printf("%d-->",list ->number); /* print current item */

if(list->next->next == NULL) printf("%d", list->next->number);

print(list->next); } return; }

/* move to next item */

int count(node *list) { if(list->next == NULL) return (0); else return(1+ count(list->next)); }

OUTPUT

Input a number (type -999 to end):35 Input a number (type -999 to end): 1

Input a number (type -999 to end): 0 Input a number (type -999 to end): 79 Input a number (type -999 to end): 57 Input a number (type -999 to end): -999

35 -->1 -->0 -->79 -->57 --> -999 Number of items = 5 25) Aim: Write a function for inserting an item into a linked list. Explanation:User has to enter any value in the list and user must enter -999 to end the list.Then this program will return the list and alsothe number values in the list.

/* Write a function for inserting an item into a linked list */

node *insert(node *head) { node *find(node *p, int a); node *new; node *n1; int key; int x; /* new item (number) to be inserted */ /* pointer to new node */ /* pointer to node preceding key node */

printf("Value of new item?"); scanf("%d", &x); printf("Value of key item ? (type -999 if last) "); scanf("%d", &key);

if(head->number == key) {

/* new node is first */

new = (node *)malloc(size of(node)); new->number = x; new->next = head; head = new; } else { /* find key node and insert new node */ /* before the key node */ n1 = find(head, key); /* find key node */

if(n1 == NULL) printf("\n key is not found \n"); else { new = (node *)malloc(sizeof(node)); new->number = x; new->next = n1->next; n1->next = new; /* insert new node */

} } return(head); } node *find(node *lists, int key) { if(list->next->number == key) return(list); else /* key found */

if(list->next->next == NULL) return(NULL); else find(list->next, key); }

/* end */

OUTPUT

26 )Aim: Write a function for deleting an item from linked list */ Explanation:User has to enter any value in the list,if user must enter -999 to end the list.Then this program will return list and also number values in the list /* Write a function for deleting an item from linked list */ node *delete(node *head) { node *find(node *p, int a);

int key; node *n1; node *p;

/* item to be deleted */ /* pointer to node preceding key node */ /* temporary pointer */

printf("\n What is the item (number) to be deleted?"); scanf("%d", &key); if(head->number == key) { p = head->next; free(head); head = p; } else { n1 = find(head, key); if(n1 == NULL) printf("\n key not found \n"); else { p = n1->next->next; /* 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) */

free(n1->next); n1->next = p; } }

/* free key node */ /* establish link */

return(head); }

OUTPUT

27) Aim: Write a program for creation of sorted list from a given list of numbers. Explanation:User has to enter any value in the list,if user must enter -999 to end the list.Then this program will return list and also number values in the list

/* Write a program for creation of sorted list from a given list of numbers */ #include <stdio.h> #include <stdlib.h> #define NULL 0 struct linked_list { int number; struct linked_list *next; }; typedef struct linked_list node; main () { int n; node *head = NULL; void print(node *p); node *insert_Sort(node *p, int n);

printf("Input the list of numbers.\n"); printf("At end, type -999.\n"); scanf("%d",&n);

while(n != -999) { if(head == NULL) { head = (node *)malloc(sizeof(node)); head ->number = n; head->next = NULL; /* create 'base' node */

else {

/* insert next item */

head = insert_sort(head,n); } scanf("%d", &n); } printf("\n"); print(head); print("\n"); }

node *insert_sort(node *list, int x) { node *p1, *p2, *p; p1 = NULL; p2 = list; /* p2 points to first node */

for( ; p2->number < x ; p2 = p2->next) { p1 = p2;

if(p2->next == NULL) { p2 = p2->next; break; } } /* p2 set to NULL */ /* insert new node at end */

/* key node found */ p = (node *)malloc(sizeof(node)); /* space for new node */ p->number = x; p->next = p2; if (p1 == NULL) list = p; else p1->next = p; /* new node inserted after 1st node */ /* new node becomes the first node */ /* place value in the new node */ /* link new node to key node */

return (list); } void print(node *list) { if (list == NULL) printf("NULL"); else { printf("%d-->",list->number); print(list->next); } return; }

OUTPUT Input the list of number. At end, type -999. 80 70 50 40 60 -999 40-->50-->60-->70-->80 -->NULL

28)Aim:Write a C program that uses functions to perform the following operations on doubly linked list: i) Creation ii) Insertion iii) Deletion iv) Traversal in both ways. Explantion: User has to enter any value in the list and user must enter -999 to end the list.If user want to insert more elements in the list ,user should select number 2 and then they can enter any values in the list.Next user must select number 3 to see the list.Next user must select number 4 to delete any item in the list.Next user has to enter number 5 for searching a node.Next user has

to enter number 6,then user can insert a node in the list.Next if user want to exit from the output ,user has to enter number 7.

#include "stdio.h" #include "alloc.h"

typedef struct dubll { int data; struct dubll *leftlink,*rightlink; }*DUBLL;

DUBLL high,temp_node,low,last,pntr; int flag=0;

DUBLL NodeAlloc(); DUBLL Search(int,int);

void CreateItem(); void AppendItem(); void PrintItem(); void DeleteItem(); DUBLL Search(int item,int flag); DUBLL NodeAlloc();

void InsertItem();

void main(void) { int choice,Item; high=NULL; while(1) { clrscr(); printf("\n \t\t\t***** M A I N M E N U *****\n\n"); 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"); scanf("%d",&choice); switch(choice) { case 1: CreateItem(); puts("\nPress any key to go back to main menu."); getch(); break; case 2: AppendItem(); break; case 3: PrintItem();

puts("\nPress any key to go back to main menu."); getch(); break; case 4: DeleteItem(); break; case 5: printf("Find an Item: "); scanf("%d",&Item); temp_node=Search(Item,0); if(temp_node) { puts("The item is available in the Linked List."); } else { puts("The item is not found in the Linked List."); } getch(); break; case 6: InsertItem(); break; case 7: exit();

default: puts("Invalid choice."); puts("\nPress any key to go back to main menu."); getch(); break; } } }

/* Function to Create the list*/ void CreateItem() { if(high==NULL) { printf("\n --Creating the list--"); temp_node=NodeAlloc(); printf("\n Enter starting data (as integer value) :"); scanf("%d",&temp_node->data); high=temp_node; } else{ printf("\n List already created @ %d with %d as data.",high,high->data);} }

/* Function to Append items to the list*/ void AppendItem()

{ low=high; if(high==NULL) { CreateItem(); } else { temp_node=NodeAlloc(); printf("\n Enter Item (in integer) :"); scanf("%d",&temp_node->data); temp_node->rightlink=NULL;

while(low->rightlink!=NULL) low=low->rightlink; low->rightlink=temp_node; temp_node->leftlink=low; last=low->rightlink;

} }

/* Function to Traverse the list both ways and print the data*/ void PrintItem() {

DUBLL temp_node; if(high==NULL) { printf("\n List is not available. Please create a list first."); getch(); CreateItem(); } temp_node=high; last=low->rightlink; printf("\n--Printing The List In Forward direction--\n");

while(temp_node!=NULL) {

//In forward direction

printf("\t %d",temp_node->data); temp_node = temp_node->rightlink; } printf("\n"); printf("\n--Printing The List In Backward direction--\n"); temp_node=high; if(temp_node->rightlink==NULL){printf("%d",temp_node->data);return; } while(last!=NULL) { printf("\t %d",last->data); last = last->leftlink; } //In backward direction

/* Function to Delete items of the list*/ void DeleteItem() { int value; DUBLL temp_node; if(high==NULL) { printf("\n List is not available. Please create a list first."); getch(); CreateItem(); } printf("\n Item to delete :"); scanf("%d",&value); pntr=Search(value,1); pntr->leftlink->rightlink=pntr->rightlink; pntr->rightlink->leftlink=pntr->leftlink; temp_node=pntr; free(temp_node); }

/* Function to Search an item from the list*/ DUBLL Search(int item,int flag) {

temp_node = high; if(high==NULL) { printf("\n List is not available. Please create a list first."); getch(); CreateItem(); } while(temp_node!=NULL) { if(temp_node->data==item ) { if(flag==0) { return(1); } else { return(temp_node); } } temp_node=temp_node->rightlink; } }

/* Function to Allocate nodes*/

DUBLL NodeAlloc() { DUBLL tmep_node; tmep_node=malloc(sizeof(struct dubll)); if(tmep_node==NULL) { printf("\n No memory available. Node allocation cannot be done."); } tmep_node->rightlink=tmep_node->leftlink=NULL; return(tmep_node); }

/* Function to Insert items in the middle of the list*/ void InsertItem() { int node; DUBLL temp_node;

if(high==NULL) { printf("\n List is not available. Please create a list first."); getch(); CreateItem(); } temp_node=NodeAlloc();

printf("Position At which node to be inserted: ___ & New Item Value: ___ "); scanf("%d",&node); scanf("%d",&temp_node->data); pntr=Search(node,1);

if(pntr->rightlink==NULL){printf("\n The operation is not possible."); getch();return;} temp_node->leftlink=pntr; //creating link to new node

temp_node->rightlink=pntr->rightlink;

pntr->rightlink->leftlink=temp_node; pntr->rightlink=temp_node;

printf("\n Item has been Inserted."); getch(); }

OUTPUT ***** M A I N M E N U ***** 1: Create Linked List 2: Append a Node to the List 3: Traverse the List 4: Delete a Node from the List 5: Search a Node 6: Insert a Node to the List 7: Close

Enter your Option [ 1 ] --Creating the list-Enter starting data (as integer value) :20 Press any key to go back to main menu. Enter your Option [ 2 ] Enter an item(in the integer ) :67 Enter your Option [ 3 ] --Printing The List In Forward direction 20 67

--Printing The List In Backward direction-67 20

Press any key to go back to main menu. Enter your Option [ 4 ] Item to delete 67 --Printing The List In Forward direction 20 --Printing The List In Backward direction 20 Press any key to go back to main menu. Enter your Option [ 5 ] Find an item : 20 The item is available in the linked list Enter your Option [ 6]

29)Aim: Write C programs that implement stack (its operations) using i) Arrays Explanation: #include<stdio.h> #include<conio.h>

int st_arr[20]; int t=-1;

void push_ele(int ele); int pop_ele(); void display_ele();

void main() { char choice,num1=0,num2=0; while(1) { clrscr(); printf("======================================"); printf("\n\t\t MENU "); printf("\n======================================"); printf("\n[1] Using Push Function"); printf("\n[2] Using Pop Function"); printf("\n[3] Elements present in Stack"); printf("\n[4] Exit\n");

printf("\n\tEnter your choice: "); fflush(stdin); scanf("%c",&choice);

switch(choice-'0') {

case 1: { printf("\n\tElement to be pushed: "); scanf("%d",&num1); push_ele(num1); break; }

case 2: { num2=pop_ele(1); printf("\n\tElement to be popped: %d\n\t",num2); getch(); break; }

case 3: {

display_ele(); getch(); break; }

case 4: exit(1); break;

default: printf("\nYour choice is invalid.\n"); break; } } }

/*Implementing the push() function. */ void push_ele(int ele) { if(t==99) { printf("STACK is Full.\n"); getch(); exit(1); }

st_arr[++t]=ele; }

/*Implementing the pop() function. */ int pop_ele() { int ele1; if(t==-1) { printf("\n\tSTACK is Empty.\n"); getch(); exit(1); } return(st_arr[t--]); }

/*Implementing display() function. */ void display_ele() { int k; printf("\n\tElements present in the stack are:\n\t"); for(k=0;k<=t;k++) printf("%d\t",st_arr[k]); } OUTPUT

======================================

MENU ====================================== [1] Using Push Function [2] Using Pop Function [3] Elements present in Stack [4] Exit Enter your choice 1 Element to be pushed 20 Enter your choice 1 Element to be pushed 30 Enter your choice 1 Element to be pushed 40 Enter your choice 3 Elements present in the stack are: 20 30 40

Enter your choice 2 Element to be popped 40 Enter your choice 3 Elements present in the stack are: 20 30

Enter your choice 4

30) aim:Write C programs that implement stack (its operations) using ii) Pointers #include<stdio.h> #include<conio.h>

struct st_point { int ele; struct st_point *l; }

*t; int i;

void push_ele(int j); int pop_ele(); void display_ele();

void main() { char choice,num1=0,num2=0; int i; while(1) { clrscr(); printf("======================================");

printf("\n\t\t MENU "); printf("\n======================================"); printf("\n[1] Using Push Function"); printf("\n[2] Using Pop Function"); printf("\n[3] Elements present in Stack"); printf("\n[4] Exit\n"); printf("\n\tEnter your choice: "); fflush(stdin); scanf("%c",&choice);

switch(choice-'0') { case 1: { printf("\n\tElement to be pushed:"); scanf("%d",&num1); push_ele(num1); break; }

case 2: { num2=pop_ele(1); printf("\n\tElement to be popped: %d\n\t",num2); getch();

break; }

case 3: { printf("\n\tElements present in the stack are:\n\t"); display_ele(); getch(); break; }

case 4: exit(1); break;

default: printf("\nYour choice is invalid.\n"); break; } } }

/*Inserting the elements using push function*/ void push_ele(int j) {

struct st_point *m; m=(struct st_point*)malloc(sizeof(struct st_point)); m->ele=j; m->l=t; t=m; return; }

/*Removing the elements using pop function*/ int pop_ele() { if(t==NULL) { printf("\n\STACK is Empty."); getch(); exit(1); } else { int i=t->ele; t=t->l; return (i); } return 0; }

/*Displaying the elements */ void display_ele() { struct st_point *pointer=NULL; pointer=t; while(pointer!=NULL) { printf("%d\t",pointer->ele); pointer=pointer->l; } } OUTPUT ====================================== MENU ====================================== [1] Using Push Function [2] Using Pop Function [3] Elements present in Stack [4] Exit

Enter your choice:1 Element to be pushed 20 Enter your choice 1 Element to be pushed 30

Enter your choice 1 Element to be pushed 40 Enter your choice:3 Elements present in the stack are: 20 30 40

Enter your choice 2 Element to be popped 40 Enter your choice 3 Elements present in the stack are: 20 30

Enter your choice 4

31)Aim:Write C programs that implement Queue (its operations) using

i) Arrays */

#include<stdio.h> #include<alloc.h> #include<conio.h> #define size 10 #define true 1 #define false 0

struct q_arr { int f,r; int num;

int a[size]; };

void init(struct q_arr* queue); int e_que(struct q_arr* queue); int f_que(struct q_arr* queue); int add_ele(struct q_arr* queue,int); int rem_ele(struct q_arr* queue); void display_ele(struct q_arr* queue);

/*main function*/ void main() { int ele,k; int ch;

struct q_arr *queue = (struct q_arr*)malloc(sizeof(struct q_arr)); init(queue);

while(1) { clrscr(); printf("\n\n****IMPLEMENTATION OF QUEUE USING ARRAYS****\n"); printf("============================================"); printf("\n\t\tMENU\n");

printf("============================================"); printf("\n\t[1] To insert an element"); printf("\n\t[2] To remove an element"); printf("\n\t[3] To display all the elements"); printf("\n\t[4] Exit"); printf("\n\n\t Enter your choice: "); scanf("%d",&ch);

switch(ch) { case 1: { printf("\nElement to be inserted:"); scanf("%d",&ele); add_ele(queue,ele); break; }

case 2: { if(!e_que(queue)) { k=rem_ele(queue); printf("\n%d element is removed\n",k); getch();

} else { printf("\tQueue is Empty. No element can be removed."); getch(); } break; }

case 3: { display_ele(queue); getch(); break; }

case 4: exit(0);

default: printf("\tInvalid Choice."); getch(); break; } }

} /*end main*/

void init(struct q_arr* queue) { queue->f = 0; queue->r = -1; queue->num = 0; }

/* Function to check is the queue is empty*/ int e_que(struct q_arr* queue) { if(queue->num==0) return true; return false; }

/* Function to check if the queue is full*/ int f_que(struct q_arr* queue) { if(queue->num == size) return true; return false; }

/* Function to add an element to the queue*/ int add_ele(struct q_arr* queue,int j) { if(f_que(queue)) return false;

if(queue->r == size - 1) queue->r = -1; queue->a[++queue->r] = j; queue->num++; return true; }

/* Function to remove an element of the queue*/ int rem_ele(struct q_arr* queue) { int j; if(e_que(queue)) return -9999; j = queue->a[queue->f++]; if(queue->f == size) queue->f = 0; queue->num--; return j;

/* Function to display the queue*/ void display_ele(struct q_arr* queue) { int j; if(e_que(queue)) { printf("Queue is Empty. No records to display."); return; } printf("\nElements present in the Queue are: "); for(j=queue->f;j<=queue->r;j++) printf("%d\t",queue->a[j]); printf("\n"); }

OUTPUT ============================================ MENU ============================================ [1] To insert an element [2] To remove an element [3] To display all the elements [4] Exit

Enter your choice: 1 Element to be inserted: 25 Enter your choice: 1 Element to be inserted: 35 Enter your choice: 1 Element to be inserted: 45 Enter your choice: 3 Elements present in the Queue are: 25 Enter your choice: 2 45 Element is removed. Enter your choice: 2 35 Element is removed. Enter your choice: 3 Elements present in the Queue are: 25 Enter your choice: 4 32) Aim: Write C programs that implement Queue (its operations) using Explanation: ii) Pointers 35 45

#define true 1 #define false 0 #include<stdio.h> #include<conio.h> #include<process.h> struct q_point {

int ele; struct q_point* n; };

struct q_point *f_ptr = NULL; int e_que(void); void add_ele(int); int rem_ele(void); void show_ele(); /*main function*/ void main() { int ele,choice,j; while(1) { clrscr(); printf("\n\n****IMPLEMENTATION OF QUEUE USING POINTERS****\n"); printf("=============================================="); printf("\n\t\t MENU\n"); printf("=============================================="); printf("\n\t[1] To insert an element"); printf("\n\t[2] To remove an element"); printf("\n\t[3] To display all the elements"); printf("\n\t[4] Exit"); printf("\n\n\tEnter your choice:");

scanf("%d", &choice);

switch(choice) { case 1: { printf("\n\tElement to be inserted:"); scanf("%d",&ele); add_ele(ele); getch(); break; }

case 2: { if(!e_que()) { j=rem_ele(); printf("\n\t%d is removed from the queue",j); getch(); } else { printf("\n\tQueue is Empty."); getch();

} break; }

case 3: show_ele(); getch(); break;

case 4: exit(1); break;

default: printf("\n\tInvalid choice."); getch(); break; }

} }

/* Function to check if the queue is empty*/ int e_que(void) {

if(f_ptr==NULL) return true; return false; }

/* 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)); queue->ele = ele; queue->n = NULL; if(f_ptr==NULL) f_ptr = queue; else { struct q_point* ptr; ptr = f_ptr; for(ptr=f_ptr ;ptr->n!=NULL; ptr=ptr->n); ptr->n = queue; } }

/* Function to remove an element from the queue*/ int rem_ele() {

struct q_point* queue=NULL; if(e_que()==false) { int j = f_ptr->ele; queue=f_ptr; f_ptr = f_ptr->n; free (queue); return j; } else { printf("\n\tQueue is empty."); return -9999; } }

/* Function to display the queue*/ void show_ele() { struct q_point *ptr=NULL; ptr=f_ptr; if(e_que()) { printf("\n\tQUEUE is Empty."); return;

} else { printf("\n\tElements present in Queue are:\n\t"); while(ptr!=NULL) { printf("%d\t",ptr->ele); ptr=ptr->n; } } }

OUTPUT ============================================== MENU ==============================================

[1] To insert an element [2] To remove an element [3] To display all the elements [4] Exit Enter your choice: 1 Element to be inserted: 67

Enter your choice: 1 Element to be inserted: 53 Enter your choice: 3 Elements presents in Queue are 67 53

Enter your choice: 2 67 Element is removed Enter your choice: 3 Elements presents in Queue are 53 Enter your choice: 4

33)Aim: Write a C program that uses Stack operations to perform the following: i) Converting infix expression into postfix expression ii) Evaluating the postfix expression Explanation:

#include<stdio.h> #include<conio.h> int st[100]; int st_top=-1;

int cal(char post[]); void in_post(char in[]); void push_item(int it);

int pop_item(); int st_ISP(char t); int st_ICP(char t);

/*main function*/ void main() { char in[100],post[100]; clrscr(); printf("\n\tEnter the Infix Expression: "); gets(in); in_post(in); getch(); } /*end main*/

void push_item(int it) { if(st_top==99) { printf("\n\n\t*STACK is Full*"); getch(); exit(1); } st[++st_top]=it;

int pop_item() { int it; if(st_top==-1) { getch(); } return(st[st_top--]); }

/*Function for converting an infix expression to a postfix expression. */ void in_post(char in[]) { int x=0,y=0,z,result=0; char a,c, post[100]; char t; push_item('\0'); t=in[x]; while(t!='\0') { if(isalnum(t)) /*For checking whether the value in t is an alphabet or number. */ {

post[y]=t; y++; } else if(t=='(') { push_item('('); } else if(t==')') { while(st[st_top]!='(') { c=pop_item(); post[y]=c; y++; } c=pop_item(); } else { while(st_ISP(st[st_top])>=st_ICP(t)) { c=pop_item(); post[y]=c; y++; }

push_item(t); } x++; t=in[x]; }

while(st_top!=-1) { c=pop_item(); post[y]=c; y++; } printf("\n\tThe Postfix Expression is:");

for(z=0;z<y;z++) printf("%c",post[z]); printf("\n\nDo you want to evaluate the Result of Postfix Expression?(Y/N):"); scanf("%c",&a); if(a=='y' || a=='Y') { result=cal(post); printf("\n\n\tResult is: %d\n",result); getch(); } else if(a=='n' || a=='N')

{ exit(0); } }

/*Determining priority of inside elements*/ int st_ISP(char t) { switch(t) { case '(':return (10); case ')':return (9); case '+':return (7); case '-':return (7); case '*':return (8); case '/':return (8); case '\0':return (0); default: printf("Expression is invalid."); break; } return 0; }

/*Determining priority of approaching elements*/ int st_ICP(char t)

{ switch(t) {

case '(':return (10); case ')':return (9); case '+':return (7); case '-':return (7); case '*':return (8); case '/':return (8); case '\0':return (0); default: printf("Expression is invalid."); break; } return 0; }

/*Evaluating the result of postfix expression*/ int cal(char post[]) { int m,n,x,y,j=0,len; len=strlen(post); while(j<len) { if(isdigit(post[j]))

{ x=post[j]-'0'; push_item(x); } else { m=pop_item(); n=pop_item();

switch(post[j]) { case '+':x=n+m; break; case '-':x=n-m; break; case '*':x=n*m; break; case '/':x=n/m; break; } push_item(x); } j++; } if(st_top>0)

{ printf("Number of Operands are more than Operators."); exit(0); } else { y=pop_item(); return (y); } return 0; }

OUTPUT Enter the Infix Expression: 5*3+7*4 The Postfix Expression is: 53*74*+ Do you want to evaluate the Result of Postfix Expression? (Y/N): Y

Result is: 43 34)Aim: Write C programs that implement the following sorting methods to sort a given list of integers in ascending order: i) Bubble sort Explanation: User has to enter any value (it indicates maximum number of values in the list) then again user has to enter the values. Then this program will return the sorted list of values.

#include <stdio.h>

#define MAX 10 void swapList(int *m,int *n) { int temp; temp = *m; *m = *n; *n = temp; }

// Function for Bubble Sort void bub_sort(int list[], int n) { int i,j; for(i=0;i<(n-1);i++) for(j=0;j<(n-(i+1));j++) if(list[j] > list[j+1]) swapList(&list[j],&list[j+1]); }

void readlist(int list[],int n) { int j; printf("\nEnter the elements: \n"); for(j=0;j<n;j++) scanf("%d",&list[j]);

// Showing the contents of the list void printlist(int list[],int n) { int j; for(j=0;j<n;j++) printf("%d\t",list[j]); }

void main() { int list[MAX], num; clrscr(); printf("\n\n\n***** Enter the number of elements [Maximum 10] *****\n"); scanf("%d",&num); readlist(list,num); printf("\n\nElements in the list before sorting are:\n"); printlist(list,num); bub_sort(list,num); printf("\n\nElements in the list after sorting are:\n"); printlist(list,num); getch(); }

OUTPUT

***** Enter the number of elements [Maximum 10] ***** 5 Enter the elements: 16 17 9 20 3 Elements in the list before sorting are: 16 17 9 20 3

Elements in the list after sorting are: 3 9 16 17 20

35)Aim: Write C program that implement the following sorting methods to sort a given list of integers in ascending order: i) Insertion sort Explanation: User has to enter the values and it will give sorted list of values.

#include<stdio.h> #include<conio.h> void inst_sort(int []); void main() { int num[5],count; clrscr(); printf("\nEnter the Five Elements to sort:\n"); for (count=0;count<5;count++) scanf("%d",&num[count]); inst_sort(num);

printf("\n\nElements after sorting: \n"); for(count=0;count<5;count++) printf("%d\n",num[count]); getch(); }

// Function for Insertion Sorting void inst_sort(int num[])

{ int i,j,k; for(j=1;j<5;j++) { k=num[j]; for(i=j-1;i>=0 && k<num[i];i--) num[i+1]=num[i]; num[i+1]=k; } }

OUTPUT Enter the Five Elements to sort: 50 20 40 60 10 Elements after sorting: 10 20 40 50 60

36)Aim: 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 : ii) Binary search

#include <stdio.h> #define MAX_LEN 10 /* Non-Recursive function*/ void b_search_nonrecursive(int l[],int num,int ele) { int l1,i,j, flag = 0; l1 = 0; i = num-1; while(l1 <= i) { j = (l1+i)/2; if( l[j] == ele) { printf("\nThe element %d is present at position %d in list\n",ele,j); flag =1; break; } else if(l[j] < ele) l1 = j+1; else

i = j-1; } if( flag == 0) printf("\nThe element %d is not present in the list\n",ele); }

/* Recursive function*/ int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a) { int m,pos; if (arrayStart<=arrayEnd) { m=(arrayStart+arrayEnd)/2; if (l[m]==a) return m; else if (a<l[m]) return b_search_recursive(l,arrayStart,m-1,a); else return b_search_recursive(l,m+1,arrayEnd,a); } return -1; }

void read_list(int l[],int n) {

int i; printf("\nEnter the elements:\n"); for(i=0;i<n;i++) scanf("%d",&l[i]); }

void print_list(int l[],int n) { int i; for(i=0;i<n;i++) printf("%d\t",l[i]); }

/*main function*/ void main() { int l[MAX_LEN], num, ele,f,l1,a; int ch,pos;

clrscr();

printf("======================================================"); printf("\n\t\t\tMENU"); printf("\n====================================================="); printf("\n[1] Binary Search using Recursion method");

printf("\n[2] Binary Search using Non-Recursion method"); printf("\n\nEnter your Choice:"); scanf("%d",&ch);

if(ch<=2 & ch>0) { printf("\nEnter the number of elements : "); scanf("%d",&num); read_list(l,num); printf("\nElements present in the list are:\n\n"); print_list(l,num); printf("\n\nEnter the element you want to search:\n\n"); scanf("%d",&ele);

switch(ch) { case 1:printf("\nRecursive method:\n"); pos=b_search_recursive(l,0,num,ele); if(pos==-1) { printf("Element is not found"); } else {

printf("Element is found at %d position",pos); } getch(); break;

case 2:printf("\nNon-Recursive method:\n"); b_search_nonrecursive(l,num,ele); getch(); break; } } getch(); }

OUTPUT ====================================================== MENU ===================================================== [1] Binary Search using Recursion method [2] Binary Search using Non-Recursion method Enter your Choice: 1 Enter the number of elements: 3 Enter the elements:

20 17 45

Elements present in the list are: 20 17 45

Enter the element you want to search: 20 Recursive method Element is present in 0 position

37)Aim: Write C programs that use both recursive and non recursive functions to perform the following searching operation for a Key value in a given list of integers : i) Linear search Explanation: User has to choose the option 1 or 2(it indicates recursion or non recursion method).Next User has to enter the maximum number of elements and user has to enter the elements. Then Program will return the list of numbers. We can search any element in the list then it will show the position of that element. #include <stdio.h> #define MAX_LEN 10 void l_search_recursive(int l[],int num,int ele); void l_search(int l[],int num,int ele); void read_list(int l[],int num); void print_list(int l[],int num); void main() {

int l[MAX_LEN], num, ele; int ch; clrscr(); printf("======================================================"); printf("\n\t\t\tMENU"); printf("\n====================================================="); printf("\n[1] Linary Search using Recursion method"); printf("\n[2] Linary Search using Non-Recursion method"); printf("\n\nEnter your Choice:"); scanf("%d",&ch);

if(ch<=2 & ch>0) { printf("Enter the number of elements :"); scanf("%d",&num); read_list(l,num); printf("\nElements present in the list are:\n\n"); print_list(l,num); printf("\n\nElement you want to search:\n\n"); scanf("%d",&ele);

switch(ch) { case 1:printf("\n**Recursion method**\n"); l_search_recursive(l,num,ele);

getch(); break;

case 2:printf("\n**Non-Recursion method**\n"); l_search_nonrecursive(l,num,ele); getch(); break; } } getch(); } /*end main*/

/* Non-Recursive method*/ void l_search_nonrecursive(int l[],int num,int ele) { int j, f=0; for(j=0;j<num;j++) if( l[j] == ele) { printf("\nThe element %d is present at position %d in list\n",ele,j); f=1; break; } if(f==0)

printf("\nThe element is %d is not present in the list\n",ele); }

/* Recursive method*/ void l_search_recursive(int l[],int num,int ele) { int f = 0; if( l[num] == ele) { printf("\nThe element %d is present at position %d in list\n",ele,num); f=1; } else { if((num==0) && (f==0)) { printf("The element %d is not found.",ele); } else { l_search(l,num-1,ele); } } getch(); }

void read_list(int l[],int num) { int j; printf("\nEnter the elements:\n"); for(j=0;j<num;j++) scanf("%d",&l[j]); }

void print_list(int l[],int num) { int j; for(j=0;j<num;j++) printf("%d\t",l[j]); }

OUTPUT

====================================================== MENU ====================================================== [1] Linear Search using Recursion method [2] Linear Search using Non-Recursion method

Enter your Choice: 1 Enter the number of elements: 2 Enter the elements: 17 45 Elements present in the list are: 17 45 Enter the element you want to search: 17 **Recursion method** The element 17 is present at position 0 in list 38)Aim: Write C program that implement the following sorting methods to sort a given list of integers in ascending order: ii) Quick sort Explanation: User has to enter the maximum number of elements and user has to enter the elements. Then Program will return the list of numbers and also sorted list.

#include <stdio.h> #define MAX 10 void swap(int *m,int *n) { int temp; temp = *m; *m = *n; *n = temp; }

int get_key_position(int x,int y ) { return((x+y) /2); }

// Function for Quick Sort void quicksort(int list[],int m,int n) { int key,i,j,k; if( m < n) { k = get_key_position(m,n); swap(&list[m],&list[k]); key = list[m]; i = m+1; j = n; while(i <= j) { while((i <= n) && (list[i] <= key)) i++; while((j >= m) && (list[j] > key)) j--; if( i < j) swap(&list[i],&list[j]); }

swap(&list[m],&list[j]); quicksort(list,m,j-1); quicksort(list,j+1,n); } }

// Function to read the data void read_data(int list[],int n) { int j; printf("\n\nEnter the elements:\n"); for(j=0;j<n;j++) scanf("%d",&list[j]); }

// Function to print the data void print_data(int list[],int n) { int j; for(j=0;j<n;j++) printf("%d\t",list[j]); }

void main() {

int list[MAX], num; clrscr(); printf("\n***** Enter the number of elements Maximum [10] *****\n"); scanf("%d",&num); read_data(list,num); printf("\n\nElements in the list before sorting are:\n"); print_data(list,num); quicksort(list,0,num-1); printf("\n\nElements in the list after sorting are:\n"); print_data(list,num); getch(); } OUTPUT

***** Enter the number of elements Maximum [10] ***** 3 Enter the elements 20 17 32 Elements in the list before sorting are: 20 17 32

Elements in the list after sorting are: 17 20 32

39)Aim: Write C program that implement the following sorting methods to sort a given list of integers in ascending order: ii) Merge sort

#include <stdio.h> #include <stdlib.h> #define MAX_ARY 10 void merge_sort(int x[], int end, int start); int main(void) { int ary[MAX_ARY]; int j = 0; printf("\n\nEnter the elements to be sorted: \n"); for(j=0;j<MAX_ARY;j++) scanf("%d",&ary[j]); /* array before mergesort */ printf("Before :");

for(j = 0; j < MAX_ARY; j++) printf(" %d", ary[j]);

printf("\n"); merge_sort(ary, 0, MAX_ARY - 1); /* array after mergesort */ printf("After Merge Sort :"); for(j = 0; j < MAX_ARY; j++) printf(" %d", ary[j]);

printf("\n"); getch(); } /* Method to implement Merge Sort*/ void merge_sort(int x[], int end, int start) { int j = 0; const int size = start - end + 1; int mid = 0; int mrg1 = 0; int mrg2 = 0; int executing[MAX_ARY]; if(end == start) return;

mid = (end + start) / 2; merge_sort(x, end, mid); merge_sort(x, mid + 1, start); for(j = 0; j < size; j++) executing[j] = x[end + j]; mrg1 = 0; mrg2 = mid - end + 1; for(j = 0; j < size; j++) { if(mrg2 <= start - end) if(mrg1 <= mid - end) if(executing[mrg1] > executing[mrg2])

x[j + end] = executing[mrg2++]; else x[j + end] = executing[mrg1++]; else x[j + end] = executing[mrg2++]; else x[j + end] = executing[mrg1++]; } }

OUTPUT Enter the elements to be sorted (10): 12 9 8 10 15 14 13 5 4 11 Before: 12 9 8 10 15 14 13 5 4 11

After Merge Sort: 4 5 8 9 10 11 12 13 14 15

You might also like