Sunteți pe pagina 1din 73

Aim:

1A Celsius to Fahrenheit Conversion and vice versa

To write a C program to convert the given temperature in degree centigrade to Fahrenheit and vice versa.

Flow chart:

Algorithm:
1. Read the temperature in degree Centigrade. 2. Convert the Centigrade to Fahrenheit using the formula F=9/5*c+32 3. Print the Celsius and Fahrenheit value. 4. Read the temperature in degree Fahrenheit. 5. Convert the Fahrenheit to Centigrade using the formula C=5/9*(F-32) 6. Print the Fahrenheit and Celsius value. 7. Stop

Program:
/* Program to convert Centigrade to Fahrenheit and vice versa */ #include <stdio.h> #include<conio.h> void main() { float c,f; clrscr(); /*To convert Centigrade to Fahrenheit*/ printf("Enter the temperature in centigrade:"); scanf("%f",&c); f=9.0/5.0*c+32; printf("\n\t%.2f Centigrade=%.2f Fahrenheit",c,f); /*To convert Fahrenheit to centigrade*/ printf("\n\nEnter the temperature in Fahrenheit:"); scanf("%f",&f); c=5.0/9.0*(f-32); printf("\n\t%.2f Fahrenheit=%.2f Centigrade",f,c); getch(); }

Output:

Enter the temperature in centigrade:45 45.00 Centigrade=113.00 Fahrenheit Enter the temperature in Fahrenheit:114 114.00 Fahrenheit=45.56 Centigrade

1B Simple Interest and Compound Interest Calculation


Aim:
To write a C program to find the simple interest and Compound interest for the Amount (P), Rate of Interest (R) and Number of years (N)

Flowchart:

Algorithm:
1. Read Principal (P), Rate of Interest (R) and Number of years (N). 2. Calculate Simple Interest (SI) and Compound Interest using the formula SI=(P*N*R)/100 CI=P * ((1+R)/100)^N P 3. Display the result. 4. Stop

Program:
/* Program to calculate Simple Interest and Compound Interest */ #include<conio.h> #include<stdio.h> #include<math.h> // For pow function void main() { double p,n,r,si,ci,x; clrscr(); printf("Enter the principal:Rs "); scanf("%lf",&p); printf("Enter rate of interest:"); scanf("%lf",&r); printf("Enter number of years:"); scanf("%lf",&n); /* To calculate Simple Interest*/ si=p*n*r/100; /* To calculate Compound Interest*/ ci=pow((1+r/100),n)*p-p; /* Display the result*/ printf("\n\nSimple interest =Rs %.2lf\n\n",si); printf("Compound Interest =Rs %.2lf",ci); getch(); }

Output:

Enter the principal:Rs 1000 Enter rate of interest:3 Enter number of years:5 Simple interest =Rs 150.00 Compound Interest =Rs 159.27

1C To perform arithmetic operation of two numbers


Aim:
To write a program to read two numbers and print the sum, difference, product and quotient of the two numbers.

Flowchart:

Algorithm:
1. Read the numbers a,b; 2. Calculate Sum=a+b Difference=a-b Product=a*b Quotient=a/b 3. Print sum, difference, product and the quotient. 4. Stop

Program:
/* Program to find sum, difference, product and quotient */ #include<conio.h> #include<stdio.h> void main() { float a,b,sum,diff,pro,quo; clrscr(); printf("Enter the value for A:"); scanf("%f",&a); printf("Enter the value for B(B<>0):"); scanf("%f",&b); sum=a+b; diff=a-b; pro=a*b; quo=a/b; printf("\n\tThe sum of %.2f and %.2f = %.2f",a,b,sum); printf("\n\tThe difference of %.2f and %.2f= %.2f",a,b,diff); printf("\n\tThe product of %.2f and %.2f = %.2f",a,b,pro); printf("\n\tThe quotient of %.2f by %.2f = %.2f",a,b,quo); getch(); }

Output:

Enter the value for A:7 Enter the value for B(B<>0):5 The sum of 7.00 and 5.00 = 12.00 The difference of 7.00 and 5.00= 2.00 The product of 7.00 and 5.00 = 35.00 The quotient of 7.00 by 5.00 = 1.40

Viva Questions:
1) What are the various arithmetic operators? + Addition - Subtraction * Multiplication / Divison % modulus 2) What is an arithmetic expression? An arithmetic expression is a combination operators and operands. 3) What are the various relational operators? < Less than > Greater than = Equal != Not equal >= Greater than or equal to <= Lesser than or equal to 4) What are the various logical operators? && - Logical AND || - Logical OR ! - Logical NOT 5) Explain the ternary operator. The ternary opearor is also known as Conditional opearator. Syntax: The expr-1 is evaluated first. If it is true, the expr-2 is evaluated and it is the value of expr-1 . If expr-1 is false, expr-3 is evaluated and it is the value for expr-1 Example: A=10 B= 15 Max =(A>B )? A : B

Ex 2A Identification of Even and Odd number


Aim:
To write a program to find whether the given number is even or odd.

Flowchart:

Algorithm:
1. Read the number N. 2. Find the remainder of N divided by 2 using the Modulus operator (N%2); 3. If the remainder is zero The number is Even number Otherwise The number is Odd number 4. Print the result. 5. Stop.

Program:
/* To find whether the number is even or odd*/ #include<conio.h> #include<stdio.h> void main() { int n,r; clrscr(); printf("Enter a number:"); scanf("%d",&n); r=n%2; if(r= =0) printf("\n\tThe given number %d is even",n); else printf("\n\tThe given number %d is odd",n); getch(); }

Output 1:
Enter a number:8 The given number 8 is even

Output 2:
Enter a number:-7 The given number -7 is odd

2B To display students Grade


Aim:
To write a C program to read the mark of the student and display grade based on the following norms: >=75 Grade A , >=50 and <75 Grade B , >=25 and <50 Grade C <25 Grade F

Flowchart:

Algorithm:
1. 2. 3. 4. 5. 6. Read the average mark of the student. If the mark is >=75 print GRADE A. If the mark is between 50 to 75 print GRADE B. If the mark is between 25 to 50 print GRADE C. If the mark is less than 25 print GRADE F. Stop.

Program:
/* To display the grade of the student */ #include<stdio.h> #include<conio.h> void main() { float avg; clrscr(); printf("Enter the average mark of the student:"); scanf("%f",&avg); if(avg>=75) printf("\n\tThe student's grade - A"); else if(avg>=50) printf("\n\tThe student's grade - B"); else if(avg>=25) printf("\n\tThe student's grade - C"); else printf("\n\tThe student's grade -F"); getch(); }

Output 1: Output 2: Output 3: Output 4:

Enter the average mark of the student:78 The student's grade - A Enter the average mark of the student:50 The student's grade B Enter the average mark of the student:30 The student's grade - C Enter the average mark of the student:24 The student's grade -F

Viva Questions:
1) What is a decision making statement? Decision making statement is used to break the normal flow of the program and execute part of the statement based on some condition 2) What are the various decision making statements available in C ? If statement If ..else statement. Nested if statement If ..else ladder statement Switch statement 3) Write the program logic to find biggest among three without using , = return (a>b) ? (a>c ? a:c) : (b>c ? b: c)

3A To check for perfect Number


Aim:
To write a C program to find whether the given number is perfect number or not. A number is a perfect number if the sum of the factors of the number other than itself is equal to that number. Example: 28=1+2+4+7+14 is a perfect number.

Flowchart:

Algorithm:
1. Read the number N. 2. If the number is less than 0 goto step 7 3. Initialize sum=1, i=2 4. if N % i=0 then sum=sum+i 5. Increment i. If i<=N/2 goto step 4 6. if sum=N Print the number is a perfect number else Print the number is not a perfect number

7. Stop. Program:
/* To find whether the given number is perfect number */ #include<stdio.h> #include<conio.h> void main() { int n,sum=1,i; clrscr(); printf("Enter a number:"); scanf("%d",&n); if(n>0) { for(i=2;i<=n/2;i++) if(n%i==0) sum=sum+i; if(sum==n) printf("\n\t%d is a perfect number",n); else printf("\n\t%d is not a perfect number",n); } else printf("\n\tThe input number should be greater than zero"); getch(); }

Output -1:
Enter a number:28 28 is a perfect number

Output-2:
Enter a number:56 56 is not a perfect number

Output-3:
Enter a number:-28 The input number should be greater than zero

3B To design simple Calculator


Aim:
To write a simple program to develop a simple calculator that accepts two floating point numbers from the keyboard. Display a menu to the user and get the users choice. Perform the operation and display the result using switch statement.

Algorithm:
1. Read the two floating point numbers A, B. 2. Display the menu. 1 - Add 2 - Subtract 3 - Multiply 4 - Divide 3. Get the users choice. 4. If choice =1 then Result=A+B. Goto step 8. 5. If choice =2 then Result=A-B. Goto step 8. 6. If choice =3 then Result=A*B. Goto step 8. 7. If choice =4 then Result=A/B. Goto step 8.

8. Display the result. 9. Stop.

Program:
/* To design simple calculator */ #include<stdio.h> #include<conio.h> void main() { float a,b,res; int ch; clrscr(); printf("Enter the value of A:"); scanf("%f",&a); printf("Enter the value of B(B<>0):"); scanf("%f",&b); printf("\n\nMathematical Operations"); printf("\n************************"); printf("\n\t1->Add"); printf("\n\t2->Subtract"); printf("\n\t3->Multiply"); printf("\n\t4->Divide"); printf("\n\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1:res=a+b; break; case 2:res=a-b; break; case 3:res=a*b; break; case 4:res=a/b; break; } printf("Answer =%.2f",res); getch(); }

Output 1:
Enter the value of A:5 Enter the value of B(B<>0):7

Mathematical Operations ************************


1->Add 2->Subtract 3->Multiply 4->Divide Enter your choice:1 Answer =12.00

1->Add 2->Subtract 3->Multiply 4->Divide Enter your choice:2 Answer =-49.00

Output 3:
Enter the value of A:5.2 Enter the value of B(B<>0):3 Mathematical Operations ************************ 1->Add 2->Subtract 3->Multiply 4->Divide Enter your choice:3 Answer =15.60

Output 2:
Enter the value of A:7 Enter the value of B(B<>0):56 Mathematical Operations ************************

4A To find sum of integers between A and B


Aim:
To write a C program to find the sum of all integers between any two numbers.

Flowchart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. Read the two numbers A and B Initialize sum=0, i=A Repeat step 4 and 5 until i <=B Sum=Sum+i i=i+1 Print Sum Stop

Program:
/* Sum of integers between given two ranges */ #include<stdio.h> #include<conio.h> void main() { int a,b,i,sum=0; clrscr(); printf("Enter the starting number:"); scanf("%d",&a); printf("Enter the ending number:"); scanf("%d",&b); for(i=a;i<=b;i++) sum=sum+i; printf("\n\tThe sum of integers between %d and %d=%d",a,b,sum); getch(); }

Output:

Enter the starting number:5 Enter the ending number:12 The sum of integers between 5 and 12=68

4B To print Fibonacci numbers


Aim:
To write a C program to print the first ten terms of the Fibonacci Sequence assuming the first two terms as 0 and 1.

Flowchart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. 8. Initialize f1=0 , f2=1, i=3 Print f1,f2 Repeat steps 4 to 8 until i<=10. f3=f1+f2 Print f3 f1=f2 ,f2=f3 i= i +1 Stop

Program:

/* Fibonacci series */ #include<stdio.h> #include<conio.h> void main() { int f1=0,f2=1,f3,i; clrscr(); printf("Fibonacci series"); printf("\n****************\n\t"); printf("%5d%5d",f1,f2); for(i=3;i<=10;i++) { f3=f1+f2; printf("%5d",f3); f1=f2; f2=f3; } getch(); }

Output:
Fibonacci series

0 1 1 2 3 5 8 13 21 34

4C To find number of positive, negative and zero in N elements


Aim:
To find the number of positive, negative and zeros in given N elements

Flowchart:

Algorithm:
1. Read the number of elements N. 2. Initialize pos=0, neg=0, ze=0 3. Repeat steps 4 to 5 N times. 4. Read the number X 5. If X =0 ze++ else if X>0 pos++ else neg++ 6. Print pos, neg, ze 7. Stop

Program:
/* To find number of Positive, Negative and Zeros in given 'N' numbers */

#include<stdio.h> #include<conio.h> void main() { int n,x,i,pos=0,neg=0,ze=0; clrscr(); printf("Enter number of terms:"); scanf("%d",&n); printf("\n\nEnter %d numbers\n",n); printf("***************\n"); for(i=1;i<=n;i++) { scanf("%d",&x); if(x==0) ze++; else if(x>0) pos++; else neg++; }

C and Data Structures Lab Manual M.S.P.V.L Polytechnic College, Pavoorchatram Page 27
printf("\n\tNumber of positive numbers=%d",pos); printf("\n\tNumber of negative number=%d",neg); printf("\n\tNumber of zeros=%d",ze); getch(); }

Output:

Enter number of terms:7 Enter 7 numbers ************** 23 0 -6 4 -12 0 3 Number of positive numbers=3 Number of negative number=2 Number of zeros=2

Viva Questions:
1) What are the various looping statements available in C? a) While statement b) Do..while statement c) For statement 2) What is the difference between while and do..while statement? While is an entry controlled statement. The statements inside the while may not be executed at all when the condition becomes false at the first attempt itself. The do..while is an exit controlled statement. The statements in the block are executed at least once.

5A To calculate & display the Total and Average of integers


Aim: To calculate and display the total and the average of 10 integer numbers. Flowchart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. 8. Define main Function & Declare all variables required. Assign Initial value to the variable sum=0; Read 10 numbers and store it in an array variable a[i]. Calculate the total of 10 numbers and find the average. Sum=sum + a[i]. Avg=sum / 10; Display the array elements and the total. Stop

Program:
/* Program to find sum and average of 10 numbers */ #include<stdio.h> void main() { int i,a[10]; float sum,avg; sum=0; clrscr(); printf("---------- INPUT------------\n\n"); printf("Enter the Array Elements (10 Nos)...\n"); for (i=0;i<10;i++) scanf("%d",&a[i]); for(i=0;i<10;i++) sum=sum+a[i]; printf("----------- OUTPUT----------\n\n"); printf("The Array Elements are...\n"); for(i=0;i<10;i++) printf("%d\n",a[i]); printf("Sum of 10 Numbers=== %.0f\n\n",sum); avg=sum/10; printf("Average of 10 Numbers=== %.2f",avg); getch(); }

Output:

---------- INPUT-----------Enter the Array Elements (10 Nos)... 1 2 3 4 5 6 7 8 9 10 ----------- OUTPUT---------The Array Elements are... Sum of 10 Numbers=== 55 Average of 10 Numbers=== 5.50

5B To calculate & display the Total marks using 2D array


Aim:
Read 3 subject marks of 4 students. Write a program to calculate and display the total marks of each student. Use a 2D (two-dimensional) array to store the marks

Flowchart:

Algorithm:
1. Define main Function. 2. Declare all variables in specified data type. 3. Get the details for 4 students. R.no & Name of the students using a single dimensional array. 4. And a inner for loop is to be used to get 3 marks of each students. 5. Calculate the total marks and store it in a 2-D array variable marks[i][j]; 6. Display all the details of 4 students.

Program:
/* Program to calculate and display the total marks of each student */

#include<stdio.h> void main() { int i,j,k,rno[10],sum[10],mark[10][10],tot[10]; float avg[10]; char name[10][10],*sub[10]; clrscr(); for(i=0;i<4;i++) { sum[i]=0; printf("\nStudent Detail No : %d\n",i); printf("Enter the Student Rno "); scanf("%d",&rno[i]); printf("Enter the Student Name "); scanf("%s",name[i]); for(j=0;j<3;j++) { printf("Enter the Mark %d ",j); scanf("%d",&mark[i][j]); sum[i]=sum[i]+mark[i][j]; } avg[i]=sum[i]/3; } printf("\n---------OUTPUT--------\n\n"); for(i=0;i<4;i++) { printf("\nStudent No %d",i); printf("\n\t Rno \t: "); printf("%d",rno[i]); printf("\n\t Name\t: "); printf("%s",name[i]); for(j=0;j<3;j++) { printf("\n\t Sub%d\t\t",j); printf("%d",mark[i][j]); } printf("%n"); printf("\n\tTotal Marks : "); printf("%d",sum[i]); printf("\n\tAverage : %.2f",avg[i]); } getch(); }

Output:
Student Detail No : 0 Enter the Student Rno 1001 Enter the Student Name MuthuKumar Enter the Mark 0 89 Enter the Mark 1 78 Enter the Mark 2 82 Student Detail No : 1 Enter the Student Rno 1002 Enter the Student Name ShivaKumar Enter the Mark 0 76 Enter the Mark 1 80 Enter the Mark 2 83 Student Detail No : 2

Enter the Student Rno 1003 Enter the Student Name RamKumar Enter the Mark 0 89 Enter the Mark 1 90 Enter the Mark 2 91 Student Detail No : 3 Enter the Student Rno 1004 Enter the Student Name NanthaKumar Enter the Mark 0 86 Enter the Mark 1 56 Enter the Mark 2 73 --------------OUTPUT-----------------Student No 0 Rno : 1001 Name : MuthuKumar Sub0 89 Sub1 78 Sub2 82 Total Marks :249 Average :83.00 Student No 1 Rno : 1002 Name : ShivaKumar Sub0 76 Sub1 80 Sub2 83 Total Marks :239 Average :79.66 Student No 2 Rno : 1003 Name : RamKumar Sub0 89 Sub1 90 Sub2 91 Total Marks :270 Average :90.00 Student No 3 Rno : 1004 Name : NanthaKumar Sub0 86 Sub1 56 Sub2 73 Total Marks :215 Average :71.66

Viva questions:
1) What is an array? An array is a collection of data of same data type. The elements of the array are stored in consecutive memory locations. The array elements can be processed using its index. 2) What is the starting index of an array in C? The starting index of an array in C is 0. 3) What are the types of array? One dimensional array Two dimensional array Multidimensional array. 4) What is a two dimensional array? Two dimensional is n array of one dimensional array. The elements in the array are referenced with the help of its row and column index. 5) What are the advantages of the functions? Debugging is easier It is easier to understand the logic involved in the program Testing is easier Recursive call is possible Irrelevant details in the user point of view are hidden in functions Functions are helpful in generalizing the program

6A To find minimum of two numbers using function


Aim:
Devise a function called min (x , y) that returns the smaller of two double values. Test the function with a simple data.

Flow chart:

Algorithm:
1. Define main Function & Declare all variables required. 2. Define a function prototype called double min(double,double). 3. Read two values X,Y. 4. Call Function min(X,Y) and store the return value in a variable. 5. Print the result. 6. In Function Definition Check the smallest number by using a relational Operator(<). Return the smallest value to step 6.

Program:
/* Program to write a function to find minimum value */ #include<conio.h> #include<stdio.h> /* Main Function */ void main() { double x,y,mm; double min(double,double); /* Function Prototype */ clrscr(); printf("Enter the value of x:"); scanf("%lf",&x); printf("Enter the value of y:"); scanf("%lf",&y); mm=min(x,y); /* Calling the function min(a,b) */ printf("\n\n\tThe minimum of %.4lf and %.4lf is %.4lf",x,y,mm); getch();

} /* Function to return the minimum of two numbers */ double min(double a,double b) { if(a<b) return(a); else return(b); }

Output 1:

Enter the value of x:45.565 Enter the value of y:32.23 The minimum of 45.5650 and 32.2300 is 32.2300 Output 2: Enter the value of x:-1.2 Enter the value of y:1.2 The minimum of -1.2000 and 1.2000 is -1.2000

6B To calculate factorial using recursive function


Aim:
To calculate the factorial of given number using recursive function.

Flow chart:

Algorithm:
1. Define main Function & Declare all variables required. 2. Define a Function prototype with one argument and return value. 3. Read an integer value and store it in a variable . 4. Call the function called factorial( ) and pass the value as argument. 5. Print the return value. In function Definition A) Calculate the value for given number. N*factorial(N - 1); Repeat step A until n becomes 0 or 1.

Program:
/* Program to find Factorial of Given No: using Recursive Function */ #include <stdio.h> long factorial(long); void main() { long number=0,f; clrscr(); printf("\nEnter an integer value: "); scanf("%ld",&number); f=factorial(number); /* Calling Function */ printf("\nThe Factorial of %ld is %ld\n",number,f); getch(); } long factorial(long N) { if(N<2) /* Terminating Condition */ return N; else return N*factorial(N-1); /* Recursive call */ }

Output:
Enter an integer value:

6: The Factorial of 6 is 720

Viva Questions 1) What is a function?


Functions are group of statements that can perform a task. Functions reduce the amount of coding and the functions can be called from another program. 2) Write the syntax of a function definition. return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result (default int) void indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter unless, the parameter is of type int 3) What is a recursive function? A function that calls itself is called a recursive function. 4) How the functions can be called? Call by value o Copy of argument passed to function o Changes in function do not effect original o Use when function does not need to modify argument o Avoids accidental changes Call by reference o Passes original argument o Changes in function effect original o Only used with trusted functions 5) What is the use of return statement? The return statement is used to exit from the function and return a value.

7A To calculate the number of vowels in a string


Aim:
Write a C program to find the number of vowels present in the string. [Assume your string contains both uppercase and lowercase characters]

Algorithm:
1. Begin a program with a comment line. 2. Include Header Files for standard input output function. 3. Define main Function & Declare all variables required.

4. Assign the vowels to an array variable. A[ ] = aeiouAEIOU 5. Get the String and store it in a variable 6. In a nested for Loop * Check the given string is equal to the value assigned in the array variable. * This is done until the string becomes NULL(\o) * If the character in a string is equal increment the COUNT variable by 1. 7. Print the Count variable which gives the result.

Program:
/* Program to count No:of Vowels in a String */ #include<stdio.h> #include<string.h> void main() { char *str; char a[]="aeiouAEIOU"; int i,j,count=0; clrscr(); printf("\nEnter the string\n"); gets(str); for(i=0;str[i]!='\0';i++) for(j=0;a[j]!='\0';j++) if(a[j] == str[i]) { count++; break; } printf("\n %d vowels are present in the string -> %s",count,str); getch(); }

Output:

Enter the String Programming 3 Vowels are present in the string -> Programming

7B To find given string is palindrome or not


Aim:

Write a program to find whether a given string is palindrome or not.

Algorithm:
1. Define main Function & Declare all variables required. 2. Let flag =0

3. Read a String and Find the Length of the String as n. 4. Using a for loop check the character str[i] and str[n-1-i]. 5. if equal continue the for loop until i=n/2 else set flag=1 and break the for loop. 6. If flag =0 Print The string is Palindrome Else Print The string is not palindrome 7. Stop

Program

/* Program to find whether the string is Palindrome */ #include<stdio.h> #include<conio.h> #include<ctype.h> void main() { char str[20]; int n,i,flag=0; clrscr(); printf("Enter the string:"); gets(str); n=strlen(str); //calculate string length /* Loop to check the characters*/ for(i=0;i<n/2;i++) if(toupper(str[i])!=toupper(str[n-1-i])) { flag=1; break; } /* Check the result*/ if(flag==0) printf("\n\tThe string %s is a palindrome",str); else printf("\n\tThe string %s is not a palindrome",str); getch(); }

Output:

Enter the String malayalam The Given String is Palindrome Enter the String TamilNadu The Given String is not Palindrome

7C To convert the lowercase into uppercase


Aim:
Read a string, which consists of both lower case characters and upper case

characters. Convert the lowercase character into upper case and vice versa. Display the new string

Algorithm:
1. Define main Function & Declare all variables required. 2. Read a String and Find the Length of the String. 3. Check the characters ASCII value whether it lies between 97 and 122. 4. If the Condition is true a. Change the ASCII value of the character by subtracting 32 5. Else check the ASCII value lies between 65 and 90 a. If the condition becomes true i. Add 32 to the value for the character. 6. Repeat the step 4 & step 5 until the length of the string becomes NULL. 7. Print the result. 8. Stop.

Program:
/* Convert the lowercase character into upper case and vice versa. */ #include<stdio.h> void main()

{ char str[20]; int i; clrscr(); printf("\n--------INPUT---------\n"); printf("Enter any string->"); scanf("%s",str); printf("\n\n---------OUTPUT--------\n\n"); printf("The Entered string is---->%s\n\n",str); for(i=0;i<=strlen(str);i++) { if(str[i]>=65 && str[i]<=90) /* Checking for upper case letters */ str[i]=str[i]+32; else if(str[i]>=97 && str[i]<=122) /* Checking for lowercase letters */ str[i]=str[i]-32; } printf("\nThe Converted string is---->%s",str); getch(); }

Output:

--------INPUT--------Enter any string->jAVAiNTERFACE ---------OUTPUT-------The Entered string is---->jAVAiNTERFACE The Converted string is---->JavaInterface

Viva Questions:
1) What is a string? String is a sequence of characters. 2) What is the use of getchar() and gets() functions?

The getchar() function is used to read a single character from the key board. The gets() function is used to read a sequence of characters from the keyboard. 3) What is the use of puts() function? The puts() function is used to display a string in the standard output device. 4) What is the difference between getchar() and getch() function? Both the functions are used to read a single character from the keyboard. When we use getchar() the character read is displayed on the screen. When we use getch() the character is not echoed on the screen. 5) What is the difference between strings and character arrays? A major difference is string will have static storage duration, whereas as a character array will not, unless it is explicity specified by using the static keyword. 6) Give some string processing functions. strcmp() - Used to compare two strings strcat() Used to concatenate two string. strlen() Returns the length of the string. strcpy() Copies one string to another. toupper() Converts the lowercase letters to uppercase. tolower() Converts the uppercase letters to lower case. 7) What is the delimiter for string? \0 is the string delimiter

8A Display the students detail using nested structure


Aim:
Write a program for nested structure, the two structures are declared

within a single structure. The two inner structures are : dob ( fields : dd, mm, yy) and address (st, cty) and the outer structure Student ( fields : rollno, name). Write a main program to get and display the details of N students.

Algorithm:
1. Begin a program with a comment line. 2. Include Header Files for standard input output function. 3. Define the Structure called student and structure members (Rno & Name). 4. Define a nested structure called dob and define the structure members(day, month & year). Also define a structure variable d. 5. Define another nested structure called address and define the structure members (street & City). Also define a structure variable ad. 6. Define main Function & Define a structure of array variable Stu [ ]. 7. Read N for number of students. 8. Get the students details by structure referencing operator (.). Eg., Stu[ ].d.day Stu[ ] .ad.street 9. Repeat step 8 until N number of values. 10. Display the students detail by structure referencing operator (.). 11. Repeat step 10 for N times.

Program:
/* program to get and display the details of N students. Using structure */

#include<stdio.h> struct student

{ int rno; char name[10]; struct dob { int day; char mon[10]; int year; }d; struct address { char * st,*city; }ad; }; void main() { struct student stu[10]; int n,i; clrscr(); printf("Enter No of Students...."); scanf("%d",&n); for(i=0;i<n;i++) { printf("Student Detail No %d",i); printf("\nEnter The Student Rno...\t"); scanf("%d",&stu[i].rno); printf("\nEnter the Student Name...\t"); scanf("%s",stu[i].name); printf("\nEnter the Date of Birth...\t"); printf("\n\t\tDay \t "); scanf("%d",&stu[i].d.day); printf("\n\t\tMonth \t"); scanf("%s",stu[i].d.mon); printf("\n\t\tYear \t"); scanf("%d",&stu[i].d.year); printf("\nEnter The Address...\n"); printf("\n\t Enter the Street Name\t"); scanf("%s",stu[i].ad.st); printf("\n \tEnter the City Name \t"); scanf("%s",stu[i].ad.city); } clrscr(); printf("\n\n ----------OUTPUT----------\n\n"); for(i=0;i<n;i++) { printf("Student No %d\n\n",i); printf("\t\tStudent RNo\t\t"); printf("%d",stu[i].rno); printf("\n\t\tStudent Name\t\t"); printf("%s",stu[i].name); printf("\n\t\tDate of Birth\t\t"); printf("%d- %s - %d ",stu[i].d.day,stu[i].d.mon,stu[i].d.year); printf("\n\t\tAddress...\n"); printf("\n\t\t\t Street \t%s",stu[i].ad.st); printf("\n\t\t\t City \t%s\n",stu[i].ad.city); } getch();}

Output:

Enter No of Students....2 Student Detail No 0

Enter The Student Rno... 552001 Enter the Student Name... ArunKumar Enter the Date of Birth... Day 06 Month 11 Year 1979 Enter The Address... Enter the Street Name SakthiNagar Enter the City Name Tenkasi Student Detail No 1 Enter The Student Rno... 552002 Enter the Student Name... BanuMathi.K Enter the Date of Birth... Day 07 Month November Year 1979 Enter The Address... Enter the Street Name FirstStreet Enter the City Name Madurai ----------OUTPUT---------Student No 0 Student RNo 27713 Student Name ArunKumar Date of Birth 6- 11 - 1979 Address... Street SakthiNagar City Tenkasi Student No 1 Student RNo 27714 Student Name BanuMathi. Date of Birth 7- November - 1979 Address... Street FirstStreet City Madurai

8B To print the students name, rollno using unions


Aim:
Write a Program to print the student name, rollno, marks using unions.

Algorithm:
1. Begin a program with a comment line. 2. Include Header Files for standard input output function. 3. Define union called student and structure members (Rno , Name & mark[ ]). 4. Define the main function and all variables. 5. Read the student rno and name. 6. Get 3 marks of the students and store it in a array variable(mark[ ]). 7. Print the student details.

Program:
/* Program to print the student name, rollno, marks using unions*/

#include<stdio.h>

union student { int rno; char *name; int mark[10]; }stu; void main() { int i; clrscr(); printf("\nEnter the Student Rno :\t"); scanf("%d",&stu.rno); printf("\nEnter the Student Name :\t"); scanf("%s",stu.name); for(i=0;i<3;i++) { printf("\nEnter the Mark%d :\t",i); scanf("%d",&stu.mark[i]); } printf("\n--------OUTPUT-----------\n"); printf("Students Record:"); printf("\n\t\tRno :"); printf("%d",stu.rno); printf("\n\t\tName :"); printf("%s",stu.name); for(i=0;i<3;i++) { printf("\n\t\tMark%d :",i); printf("%d",stu.mark[i]); } getch(); }

Output:

Enter the Student Rno : 100 Enter the Student Name : Shiva Enter the Mark0 : 87 Enter the Mark1 : 78 Enter the Mark2 : 90 --------OUTPUT----------Students Record: Rno :87 Name :Shiva Mark0 :87 Mark1 :78 Mark2 :90

Viva Questions:
1) What is a structure? Structure is a collections of related variables under one name and Can

contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees 2) What is an union? Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Conserves storage Only the last data member defined can be accessed. 3) How the members of structures and unions can be accessed? The Members of structures and unions can be accessed with the help of dot operator as Structure variablename . structure member 4) What is a nested structure? Defining a structure within structure is called nested structure.

9A To swap two integer using pointers


Aim:

Write a program to swap two integer numbers using pointers.

Algorithm:
1. Begin a program with a comment line. 2. Include Header Files for standard input output function. 3. Define main Function & Declare all variables required. 4. Define a function prototype swap(int*,int*) with two pointer argument. 5. Read two values as input. 6. Print the two values before swapping process. 7. Function call by passing the address using referencing operator (&). 8. Print two numbers after swapping process. 9. Function Definition * Assign the first value to a temporary variable (temp) * Change the pointer value of first number to second number. * Now change the temp value to the first value.

Program:

/* Program to Swap two Numbers Using Pointers */ #include<stdio.h> void main() { int a,b; /* Function Declaration with two arguments */ void swap(int*,int*); clrscr(); printf("Enter the First Number\n"); scanf("%d",&a); printf("Enter the Second Number\n"); scanf("%d",&b); printf(" Result Before Swapping...\n"); printf("A=== %d\n",a); printf("B=== %d\n",b); swap(&a,&b); /* Call of Function */ printf(" Result After Swapping...\n"); printf("A=== %d\n",a); printf("B=== %d\n",b); getch();

} /* Function Definition */ void swap(int *x, int *y) { int temp; temp = *x; /* contents of pointer */ *x = *y; *y = temp; }

Output:

Enter the First Number 28 Enter the Second Number 42 Result Before Swapping A=== 28 B=== 42 Result After Swapping A=== 42 B=== 28

9B To read a string use pointer


Aim:
Read a string. Print the above string such that each line contains a single

character. ( Use pointers)

Flow chart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. 8. Begin a program with a comment line. Include Header Files for standard I/O function and string function. Define main Function & Declare all variables required. Get the string to print character by character. Find the length of the string. Assign the first pointer address content to the character variable. Print the character variable. Repeat step 6 and step 7 until length of the string becomes 0.

Program:

/* Program to Print the string such that each line contains a single character */

#include<stdio.h> #include<string.h> void main() { int i,len; char *str,c,*ptr; clrscr(); printf("Enter the String\n"); scanf("%s",str); ptr=str; len=strlen(ptr);

printf("---------OUTPUT----------\n\n"); printf("Entered String is --> %s\t\n\n",str); printf("Output character by character....\n"); for(i=0;i<len;i++) { c=*ptr; printf("%c\n",c); ptr++; } getch(); }

Output:

Enter the String programming ---------OUTPUT---------Entered String is --> programming Output character by character.... p r o g r a m m i n g

9C To print the elements in reverse order using pointers


Aim:

Read an integer array consist of N elements. Print the elements in reverse order using pointers

Flowchart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. 8. Begin a program with a comment line. Include Header Files for standard I/O function. Define main Function & Declare all variables required. Get the array number N. Read N number of elements and store it in the array variable num[ ] ). Print the array list. Print the value using pointer operator *. Repeat step 7 for N times from N to 0.

Program:
/* Program to print the elements in reverse order using pointers */

#include <stdio.h> void main() { int i,n,num[10]; clrscr(); printf("Enter the number of elements in the array:"); scanf("%d",&n); printf("Enter the Array Numbers\n"); for (i= 0; i<n; i++ ) scanf("%d",num+i); printf("\n\nThe Array Numbers are...\n"); for(i=0;i<n;i++) printf("%5d",*(num+i)); printf("\n\nReversed Array List ...\n"); for (i = n-1; i >= 0; i-- ) printf("%5d",*( num+i)); getch(); }

Output:
Enter the number of elements in the array:5 Enter the Array Numbers 23 78 45 23 8 The Array Numbers are... 23 78 45 23 8 Reversed Array List ... 8 23 45 78 23

10A To read an array using pointer


Aim:

Write a C program to read through an array of any type using pointers. Write a C program to scan through this array to find a particular value

Flowchart:

Algorithm:
1. Begin a program with a comment line.

2. Include Header Files for standard I/O function, Conversion and String function. 3. Define a function prototype called search( ). 4. Define main Function & Declare all variables required. 5. Allocate dynamic memory for a variable using malloc( ) function. 6. Read a string. 7. Repeat step 5 and step 6 until n number of array elements. 8. Print the array elements. 9. Call the function Search ( ) by passing N number of strings. 10 .In function Definition *Define a temporary variable and allocate the memory space using malloc( ). * Read the String to search and store it in the temporary variable. * Check the value with the array element by using string compare function. * If they are equal set flag = 0 else set flag = 1. 11. Check the condition if flag = 0 Print the value is found. Otherwise print the value given to search is not found.

Program:
/* Pointer and Array of any data type to search a given value */ # include<stdio.h> # include<string.h> # include<ctype.h> int flag; /* FUNCTION PROTOTYPE */ int search(char **, int ); /* Function main */ void main( ) { char choice; int i, n = 0; char *string[100]; clrscr(); do { string[n] = (char *) malloc(50); printf("Input string: "); gets(string[n]); n++; printf("\n Input another Y/N? "); choice = getchar(); fflush(stdin); }while(toupper(choice) == 'Y'); printf("\nArray list \n"); printf("********** \n"); for (i = 0; i < n; i++) { printf("%s\n", string[i]); } /* Function CALL */ search(string, n); if (flag==0) printf("The String Given is FOUND"); else printf("The String Given is Not Found"); getch(); } /* Definition of function */ int search(char **str, int n) {

int i,j; char *temp[10] ; temp[0]= (char *)malloc(50); printf("Enter the string to Find\n"); gets(temp); printf("\nThe String to Find\n"); puts(temp); for(i=0;i<n;i++) { if(strcmp(str[i],temp)==0) flag=0; else flag=1; } return(flag); }

Output:
Input string: Mani Input another Y/N? y Input string: Raaju Input another Y/N? y Input string: 123 Input another Y/N? y Input string: 56.34 Input another Y/N? n Array list ********** Mani Raaju 123 56.34 Enter the string to Find 56.34 The String to Find 56.34 The String Given is FOUND

10B To find the length of the string using pointer


Aim:

To find the length of the string using pointer.

Flow chart:

Algorithm:
1. 2. 3. 4. 5. 6. 7. 8. Begin a program with a comment line. Include Header Files for standard input output function. Define main Function & Declare all variables required. Read the String. Increase the pointer value of the variable using increment operator. The count variable is incremented by 1. Repeat step 5 and step until the string pointer is NULL. Print the counted numbers which is the length of the string.

Program:
/* Program to Find Length of Strings using Pointers */ #include<stdio.h> void main() { int x; char *str; x=0; clrscr(); printf("Enter the String\n"); scanf("%s",str); printf("Length of %s is ",str); while (*str != '\0') { x++; str++; } printf("%d",x); getch(); }

Output:

Enter the String Programming Length of Programming is 11

10C To concatenate two string using pointer


Aim:

To concatenate two string using pointer

Algorithm:
1. Begin a program with a comment line. 2. Include Header Files for standard input output function. 3. Define main Function & Declare all variables required. 4. Read two strings s1 and s2 5. Move to the end of first string using a temporary pointer. 6. Add the second string to the end of first string pointed by temporary variable. 7. Print the concatenated string s1

Program:
/* String Concatenation */ #include<stdio.h> #include<conio.h> void main() { char *s1,*s2,*temp; clrscr();

printf("Enter the first string:"); gets(s1); printf("Enter the second string:"); gets(s2); printf("\n\tThe string s1 before concatenation:%s",s1); printf("\n\tThe string s2 before concatenation:%s",s2); temp=s1; while(*temp!='\0') /* Move to end of string1 */ temp++; while(*s2!='\0') /* Add second string to the end of string2 */ { *temp=*s2; temp++; s2++; } *temp='\0'; printf("\n\tThe concatenated string s1:%s",s1); getch(); }

Output:

Enter the first string:Operating Enter the second string:System The string s1 before concatenation:Operating The string s2 before concatenation:System The concatenated string s1:OperatingSystem

Viva Questions:

1) What is a pointer? Pointer is a variable that holds the address of another variable. 2) What is called the indirection operators? * is called the indirection operator since it is used to indirectly access the value of a variable through its pointer. 3) What are the advantages of pointer? As pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling arrays. Pointers reduce the program length and complexity of the program. Pointers increase the execution speed. Use of pointers to character strings results in saving of data storage space in memory. 4) What is the use of void pointer? Void pointer is used to point a variable of any data type. 5) What is the relationship between arrays and pointer? The arrays can be easily manipulated with the help of the pointers of appropriate type. The array name can be assigned to a pointer and the elements in the array can be accessed by incrementing the pointer. For example: int a[5]= {2,3,6,7,1}; int *p=a; Then *p=a[0]; *(p+1)=a[1]; *(p+2)=a[2]; *(p+3)=a[3] *(p+4)=a[4];

Ex 11A To create and Print Singly Linked List of Vowels

Aim:
To write a C program to create a linked list to contain the vowels a, e, i, o, u in the data field of the nodes.

Algorithm:
1. Define the structure of the node. 2. Define function to get a new node This function allocates memory for the node structure defined and returns the pointer to that node say newnode. 3. Define function insafter( p,x) to insert a node after a given node. Let the address for the previous node be prenode and data to be inserted as X Get a new node newnode newnodedata=X newnodenext= prenode next prenodenext=newnode Return the address of the new node 4. Define the function to create the list. Store the vowels in a character array. Get a new node and save its address. Store the first data. Let the next field be NULL. Store the remaining data in the link list by using the function insafter( ) that inserts a node after the given node. 5. Define a function Show to print the linked list. 6. Define the main function that calls the function to create the list and to print the list. 7. Stop.

Program:

/* To create and print linked list */ #include<stdio.h> #include<conio.h> /* Node structure definition */ struct node { char data; struct node *next; }; typedef struct node *nodeptr; nodeptr prenode,first; nodeptr getnode() { nodeptr d =(nodeptr) malloc(sizeof(struct node)); return d; } /* Function for insertion after a node */ nodeptr insafter(nodeptr p,char x) { nodeptr newnode; if (p==NULL) { printf("\n Void insertion:"); exit(1); } newnode=getnode(); newnode->data=x; newnode->next=prenode->next; prenode->next=newnode; return newnode; } void createlist() /* Function for creation */ { char vow[]={'a','e','i','o','u'}; int i; prenode=first=getnode(); prenode->data=vow[0]; prenode->next=NULL; fflush(stdin); for(i=1;i<6;i++) prenode=insafter(prenode,vow[i]); } void show() /* Function for displaying the list */ { prenode=first; while (prenode->next!= NULL) { printf("%c---->",prenode->data); prenode=prenode->next; } printf("NULL"); } void main() /* Main Function */ { clrscr(); createlist(); printf("\nThe created List"); printf("\n*****************\n\n"); show(); getch(); }

Output:
The created List a---->e---->i---->o---->u---->NULL

11B To delete the first node in the linked list of integers


Aim:
To write a C program to delete the first node that contains an integer data item of a single linked list.

Algorithm:
1. Define functions getnode(), insafter() and createlist() to get a new node, insert a node after a node and create the linked list respectively. 2. The first pointer points the address of the first node. 3. Define a function delfirst() that deletes the first node and returns the data in the first node using the algorithm given below. Store the data pointed by the first node in a variable. Make first pointer to point the next node as first=firstnext. Return the address of the new first node. 4. Define a function show to print the linked list. 5. Define the main function as Create the linked list using the function createlist(). Print the list using the function show(). Delete the first node using the function delfirst(). Print the list using the function show(). 6. Stop.

Program:
/* To create and print linked list */ #include<stdio.h> #include<conio.h> /* Node structure definition */ struct node { int data; struct node *next; }; typedef struct node *nodeptr; nodeptr prenode,first; /* Get node Function */ nodeptr getnode() { nodeptr d; d=(nodeptr) malloc(sizeof(struct node)); return d; } /* Function for insertion after a node */ nodeptr insafter(nodeptr p,int x) { nodeptr newnode; if (prenode==NULL) { printf("\n Void insertion:"); exit(1); } newnode=getnode(); newnode->data=x; newnode->next=prenode->next; prenode->next=newnode; return newnode; } /* Function for creation */ void createlist() { int no; char ans='y'; prenode=first=getnode(); printf("\n Enter the data:"); scanf("%d",&no); prenode->data=no; prenode->next=NULL; fflush(stdin); while(ans=='y' || ans=='Y') { printf("\n Any more data(Y/N)?:"); fflush(stdin); ans=getchar(); if(ans=='Y' || ans=='y') { printf("\n Enter the data:"); scanf("%d",&no); prenode=insafter(prenode,no); } else break; } }

/* Function to delete the first node */ int delfirst() { int x; x=first->data; first=first->next; return x; } /* Function for displaying the list */ void show() { prenode=first; while (prenode!= NULL) { printf("%d---->",prenode->data); prenode=prenode->next; } printf("NULL"); } /* Main Function */ void main() { int del; clrscr(); printf("\n Creating the list"); printf("\n******************"); createlist(); printf("\n Displaying the list"); printf("\n--------------------\n\n"); show(); del=delfirst(); printf("\n\n\nThe list after deleting the first node"); printf("\n---------------------------------------\n\t"); show(); printf("\n\nThe deleted data %d",del); getch(); }

Output:

Creating the list ************** Enter the data:5 Any more data(Y/N)?:y Enter the data:34 Any more data(Y/N)?:y Enter the data:23 Any more data(Y/N)?:y Enter the data:1 Any more data(Y/N)?:n Displaying the list -------------------5---->34---->23---->1---->NULL The list after deleting the first node --------------------------------------34---->23---->1---->NULL The deleted data 5

Viva Questions:
1) What is data structure? An organization and representation of data is called data structure. 2) What are the two types of data structure? Data structures can be classified into two types a) Linear data structures b) Non-linear data structures 3) What is the linear structure? In linear data structure the elements are stored in sequential order. The linear data structures are Array Linked list Stack Queue 4) What is a linked list? Linked list: Linked list is a collection of data of same data type but the data items need not be stored in consecutive memory locations.

A Linked list with 3 Nodes 5) What are the operations that can be performed on a linked list? Insertion Deletion Searching 6) What are the possible locations where the data can be inserted into a linked list? Data can be inserted into the linked list in the beginning, in the middle and at the end. 7) What are the possible locations where the data can be deleted in a linked list? Data can be deleted from the first, from the last and from the middle. 8) What is a doubly linked list or two way list? The linked list which has two pointer which points to the previous node and the next node is called a doubly linked list. When we use doubly linked lilst we can traverse the node in both the directions. 9) What is a circular list? The linked list in which the last node points back to the first node is called circular list.

12 To perform stack operations in Stack using array


Aim:
To write a C program to perform operations in stack using array.

Algorithm:
1. Declare the structure of stack with an array of size 20 to hold the stack and the initialize top =-1 2. Define a function push( ) to add the data to the stack as Check if the stack is full if so display Stack Full and return. Otherwise Increment the top value. Store the data in the stack[top] and return 3. Define a function pop( ) that deletes the value in the top of the stack as If top=-1 print Stack Empty and return Otherwise Print the element at stack[top] and decrement top value and return 4. Define a function show that prints the elements in the stack. 5. Define the main function as Display the menu to the user 1 - Push 2 - Pop 3 List the stack 4 Exit Get the choice from the user If choice =1 read the data and add it to the stack using push( ) function. If the choice = 2 delete the data from the stack using pop ( ) function. If the choice is 3 display the data in the stack. If choice = 4 exit from the program Else repeat the above steps. 6. Stop

Program:
/* stack using array */ #include<stdio.h> #include<conio.h> /*Structure to hold the stack*/ struct stack { int a[20], top;}s;

/*Function to add element to the stack*/ void push(int x) { if(s.top==20) printf("Stack full"); else { s.top++; s.a[s.top]=x; printf("\n\tData is added to stack\n"); } } /*Function to delete element from the stack*/ void pop() { int x; if(s.top==-1) { printf("\n\tStack empty"); } else { printf("\n\tThe deleted data is %d",s.a[s.top]); s.top--; } } /*Function to display the stack data*/ void show() { int i; if(s.top==-1) { printf("\nStack Empty"); } else { printf("\nThe stack elements"); printf("\n-------------------\n\t"); for(i=0;i<=s.top;i++) printf("%d\t",s.a[i]); printf("<---top\n"); } } /*Main function*/ void main() { int ch,data; clrscr(); s.top=-1; do { printf("\n\t\t\t Menu"); printf("\n\t\t1->Push"); printf("\n\t\t2->Pop"); printf("\n\t\t3->List stack"); printf("\n\t\t4->Exit"); printf("\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the data:");

scanf("%d",&data); push(data); break; case 2: pop(); break; case 3: show(); break; case 4: exit(0); } }while(ch<4); getch(); }

Output:
Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:1 Enter the data:67 Data is added to stack Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:1 Enter the data:11 Data is added to stack Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:3 The stack elements ------------------------67 11 <---top Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:2 The deleted data is 11 Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:3 The stack elements -----------------------67 <---top Menu 1->Push 2->Pop 3->List stack 4->Exit Enter your choice:4

Viva Questions
1) What is stack? A stack is a Last-In-First-Out linear data structure in which insertion and deletion takes place at only one end called the top of the stack. 2) What are the operations that can be performed on the stack? PUSH To add a new element to the top of the stack POP To remove an element at the top of the stack. 3) What are the applications of the stack? The stack data structure is used in applications where Last-In-FirstOut operations are carried out. Stack is used in implementing subroutine calls, recursion, evaluation of arithmetic expression, compilers etc. 4) What is an arithmetic expression? An arithmetic expression is a collection of operators and operands. 5) What is infix, postfix, prefix notation? Infix Notation: If the operator appears between the operands is called infix notation Example: A+B Postfix Notation ( Reverse Polish notation):If the operator comes after the operand then the notation is called postfix notation. Example: AB+ Prefix Notation(Polish notation): If the operator comes before the operand then the notation is called prefix notation. Example: +AB 6) What is the infix, prefix , post fix form of the following expression? a) A + B + C b) (A+B) * (C+D) c) A-B / C-D

7) Features of Prefix and Postfix expression: The operands are in the same order as the infix notation. Parenthesis is not needed to represent the precedence of operation The priority of operators is irrelevant.

13 Implementation of Queue using array


Aim:
To write a C program to perform operations in queue using array.

Algorithm:
1. Declare the array to hold the queue elements and the variables to hold the front and rear index. 2. Define functions to insert data into the rear end of queue as If the rear=Q-SIZE-1 then Print Queue Full Else Rear=Rear+1. Store the s=date in the rear position Print the queue 3. Define functions to delete the data from the queue If front=rear

Print Queue Empty Else front=front+1 Print the deleted element and the queue 4. Define function to print the elements in the queue. 5. Define main function Initialize front = rear =-1 Create a queue with elements Display the menu to the user 1->Insertion 2->Deletion 3->Exit Get the users choice If choice = 1 call the function to add element If choice = 2 call the function to delete the element If choice = 3 then Exit the program Repeat the step 5 till choice = 3. 6. Stop

Program:
/* Inserting and deleting elements from the queue */ #include<stdio.h> #include<conio.h> #define Q_SIZE 20 /*Declaration of array for queue*/ struct queue { int a[Q_SIZE]; int front,rear; }q; /* Function to insert element into the queue */ void insert() { int x; if (q.rear==Q_SIZE-1) printf("\n\nQueue full. Insertion not possible"); else { printf("\n Enter data to insert:"); scanf("%d",&x); q.rear++; q.a[q.rear]=x; } } /*Function to delete the elements in the queue */ void deleteq() { if(q.front==q.rear) printf("\n\nQueue is empty. Deletion not possible:"); else { ++q.front; printf("\n\n The deleted element is %d",q.a[q.front]); } } /*Function to display the elements in the queue*/ void show() { int i; if (q.front==q.rear) printf("\n\nQueue Empty\n");

else { printf("\n\n The elements in the queue:\n"); printf("******************************\n"); printf("\tFront--->"); for(i=q.front+1;i<=q.rear;i++) printf("%d ",q.a[i]); printf("<---Rear\n"); } } /* Main program*/ void main() { int n,i,ch; clrscr(); q.front=q.rear=-1; printf("\n No. of elements initially in the queue:"); scanf("%d",&n); /* Creating a queue with n elements */ for (i=0;i<n;i++) { q.rear++; printf("\n\tEnter the element:"); scanf("%d,",&q.a[i]); } show(); while(1) { printf("\n\n\t\t Select your choice:"); printf("\n\t1->Insertion"); printf("\n\t2->Deletion"); printf("\n\t3->Exit"); printf("\n\nEnter your choice:"); scanf("%d",&ch); switch (ch) { case 1:insert(); show(); break; case 2:deleteq(); show(); break; case 3:exit(0); }}}

Output:
No. of elements initially in the queue:3 Enter the element:2 Enter the element:4 Enter the element:5 The elements in the queue: *********************** Front--->2 4 5 <---Rear Select your choice: 1->Insertion 2->Deletion 3->exit Enter your choice:1 Enter data to insert:45 The elements in the queue: *********************** Front--->2 4 5 45 <---Rear Select your choice: 1->Insertion 2->Deletion 3->exit Enter your choice:2 The deleted element is 2 The elements in the queue: *********************** Front--->4 5 45 <---Rear Select your choice: 1->Insertion 2->Deletion 3->Exit Enter your choice:3

Viva Questions:
1) What is a queue? Queue is a linear data structure in which insertions are done end one end called the Rear of the queue and Deletions are done at another end called the Front. The queue is referred as First-In-First-Out data structure. 2) What is a circular queue? A queue in which both the front and the rear wrap around to the beginning of the array when they reached the MAX size of the queue is called circular queue. 3) What is a priority queue? A queue where insertions and deletions are performed based on some priority is called priority queue.

S-ar putea să vă placă și