Top Banner
1A Celsius to Fahrenheit Conversion and vice versa Aim: 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
86
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: C_&_DS_Lab_record

1A Celsius to Fahrenheit Conversion and vice versaAimTo write a lsquoCrsquo program to convert the given temperature in degreecentigrade to Fahrenheit and vice versaFlow chart

Algorithm1 Read the temperature in degree Centigrade2 Convert the Centigrade to Fahrenheit using the formulaF=95c+323 Print the Celsius and Fahrenheit value4 Read the temperature in degree Fahrenheit5 Convert the Fahrenheit to Centigrade using the formulaC=59(F-32)6 Print the Fahrenheit and Celsius value7 Stop

Program

Program to convert Centigrade to Fahrenheit and vice versa include ltstdiohgtincludeltconiohgtvoid main()float cfclrscr()To convert Centigrade to Fahrenheitprintf(Enter the temperature in centigrade)scanf(fampc)f=9050c+32printf(nt2f Centigrade=2f Fahrenheitcf)To convert Fahrenheit to centigradeprintf(nnEnter the temperature in Fahrenheit)scanf(fampf)c=5090(f-32)printf(nt2f Fahrenheit=2f Centigradefc)getch()OutputEnter the temperature in centigrade454500 Centigrade=11300 FahrenheitEnter the temperature in Fahrenheit11411400 Fahrenheit=4556 Centigrade

1B Simple Interest and Compound Interest CalculationAim

To write a lsquoCrsquo program to find the simple interest and Compound interestfor the Amount (P) Rate of Interest (R) and Number of years (N)Flowchart

Algorithm1 Read Principal (P) Rate of Interest (R) and Number of years (N)2 Calculate Simple Interest (SI) and Compound Interest using theformulaSI=(PNR)100CI=P ((1+R)100)^N ndashP3 Display the result4 Stop

Program Program to calculate Simple Interest and Compound Interest includeltconiohgtincludeltstdiohgt

includeltmathhgt For pow functionvoid main()double pnrsicixclrscr()printf(Enter the principalRs )scanf(lfampp)printf(Enter rate of interest)scanf(lfampr)printf(Enter number of years)scanf(lfampn) To calculate Simple Interestsi=pnr100 To calculate Compound Interestci=pow((1+r100)n)p-p Display the resultprintf(nnSimple interest =Rs 2lfnnsi)printf(Compound Interest =Rs 2lfci)getch()OutputEnter the principalRs 1000Enter rate of interest3Enter number of years5Simple interest =Rs 15000Compound Interest =Rs 15927

1C To perform arithmetic operation of two numbers

AimTo write a program to read two numbers and print the sum differenceproduct and quotient of the two numbers

Flowchart

Algorithm1 Read the numbers ab2 CalculateSum=a+bDifference=a-bProduct=abQuotient=ab3 Print sum difference product and the quotient4 Stop

Program Program to find sum difference product and quotient includeltconiohgtincludeltstdiohgtvoid main()float absumdiffproquo

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 2: C_&_DS_Lab_record

Program to convert Centigrade to Fahrenheit and vice versa include ltstdiohgtincludeltconiohgtvoid main()float cfclrscr()To convert Centigrade to Fahrenheitprintf(Enter the temperature in centigrade)scanf(fampc)f=9050c+32printf(nt2f Centigrade=2f Fahrenheitcf)To convert Fahrenheit to centigradeprintf(nnEnter the temperature in Fahrenheit)scanf(fampf)c=5090(f-32)printf(nt2f Fahrenheit=2f Centigradefc)getch()OutputEnter the temperature in centigrade454500 Centigrade=11300 FahrenheitEnter the temperature in Fahrenheit11411400 Fahrenheit=4556 Centigrade

1B Simple Interest and Compound Interest CalculationAim

To write a lsquoCrsquo program to find the simple interest and Compound interestfor the Amount (P) Rate of Interest (R) and Number of years (N)Flowchart

Algorithm1 Read Principal (P) Rate of Interest (R) and Number of years (N)2 Calculate Simple Interest (SI) and Compound Interest using theformulaSI=(PNR)100CI=P ((1+R)100)^N ndashP3 Display the result4 Stop

Program Program to calculate Simple Interest and Compound Interest includeltconiohgtincludeltstdiohgt

includeltmathhgt For pow functionvoid main()double pnrsicixclrscr()printf(Enter the principalRs )scanf(lfampp)printf(Enter rate of interest)scanf(lfampr)printf(Enter number of years)scanf(lfampn) To calculate Simple Interestsi=pnr100 To calculate Compound Interestci=pow((1+r100)n)p-p Display the resultprintf(nnSimple interest =Rs 2lfnnsi)printf(Compound Interest =Rs 2lfci)getch()OutputEnter the principalRs 1000Enter rate of interest3Enter number of years5Simple interest =Rs 15000Compound Interest =Rs 15927

1C To perform arithmetic operation of two numbers

AimTo write a program to read two numbers and print the sum differenceproduct and quotient of the two numbers

Flowchart

Algorithm1 Read the numbers ab2 CalculateSum=a+bDifference=a-bProduct=abQuotient=ab3 Print sum difference product and the quotient4 Stop

Program Program to find sum difference product and quotient includeltconiohgtincludeltstdiohgtvoid main()float absumdiffproquo

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 3: C_&_DS_Lab_record

To write a lsquoCrsquo program to find the simple interest and Compound interestfor the Amount (P) Rate of Interest (R) and Number of years (N)Flowchart

Algorithm1 Read Principal (P) Rate of Interest (R) and Number of years (N)2 Calculate Simple Interest (SI) and Compound Interest using theformulaSI=(PNR)100CI=P ((1+R)100)^N ndashP3 Display the result4 Stop

Program Program to calculate Simple Interest and Compound Interest includeltconiohgtincludeltstdiohgt

includeltmathhgt For pow functionvoid main()double pnrsicixclrscr()printf(Enter the principalRs )scanf(lfampp)printf(Enter rate of interest)scanf(lfampr)printf(Enter number of years)scanf(lfampn) To calculate Simple Interestsi=pnr100 To calculate Compound Interestci=pow((1+r100)n)p-p Display the resultprintf(nnSimple interest =Rs 2lfnnsi)printf(Compound Interest =Rs 2lfci)getch()OutputEnter the principalRs 1000Enter rate of interest3Enter number of years5Simple interest =Rs 15000Compound Interest =Rs 15927

1C To perform arithmetic operation of two numbers

AimTo write a program to read two numbers and print the sum differenceproduct and quotient of the two numbers

Flowchart

Algorithm1 Read the numbers ab2 CalculateSum=a+bDifference=a-bProduct=abQuotient=ab3 Print sum difference product and the quotient4 Stop

Program Program to find sum difference product and quotient includeltconiohgtincludeltstdiohgtvoid main()float absumdiffproquo

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 4: C_&_DS_Lab_record

includeltmathhgt For pow functionvoid main()double pnrsicixclrscr()printf(Enter the principalRs )scanf(lfampp)printf(Enter rate of interest)scanf(lfampr)printf(Enter number of years)scanf(lfampn) To calculate Simple Interestsi=pnr100 To calculate Compound Interestci=pow((1+r100)n)p-p Display the resultprintf(nnSimple interest =Rs 2lfnnsi)printf(Compound Interest =Rs 2lfci)getch()OutputEnter the principalRs 1000Enter rate of interest3Enter number of years5Simple interest =Rs 15000Compound Interest =Rs 15927

1C To perform arithmetic operation of two numbers

AimTo write a program to read two numbers and print the sum differenceproduct and quotient of the two numbers

Flowchart

Algorithm1 Read the numbers ab2 CalculateSum=a+bDifference=a-bProduct=abQuotient=ab3 Print sum difference product and the quotient4 Stop

Program Program to find sum difference product and quotient includeltconiohgtincludeltstdiohgtvoid main()float absumdiffproquo

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 5: C_&_DS_Lab_record

Flowchart

Algorithm1 Read the numbers ab2 CalculateSum=a+bDifference=a-bProduct=abQuotient=ab3 Print sum difference product and the quotient4 Stop

Program Program to find sum difference product and quotient includeltconiohgtincludeltstdiohgtvoid main()float absumdiffproquo

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 6: C_&_DS_Lab_record

clrscr()printf(Enter the value for A)scanf(fampa)printf(Enter the value for B(Bltgt0))scanf(fampb)sum=a+bdiff=a-bpro=abquo=abprintf(ntThe sum of 2f and 2f = 2fabsum)printf(ntThe difference of 2f and 2f= 2fabdiff)printf(ntThe product of 2f and 2f = 2fabpro)printf(ntThe quotient of 2f by 2f = 2fabquo)getch()OutputEnter the value for A7Enter the value for B(Bltgt0)5The sum of 700 and 500 = 1200The difference of 700 and 500= 200The product of 700 and 500 = 3500The quotient of 700 by 500 = 140

Viva Questions1) What are the various arithmetic operators+ Addition- Subtraction Multiplication Divison modulus2) What is an arithmetic expressionAn arithmetic expression is a combination operators and operands

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 7: C_&_DS_Lab_record

3) What are the various relational operatorslt Less thangt Greater than= Equal= Not equalgt= Greater than or equal tolt= Lesser than or equal to4) What are the various logical operatorsampamp - Logical AND|| - Logical OR - Logical NOT5) Explain the ternary operatorThe ternary opearor is also known as Conditional opearatorSyntax

The expr-1 is evaluated first If it is true the expr-2 is evaluatedand it is the value of expr-1 If expr-1 is false expr-3 is evaluated and itis the value for expr-1ExampleA=10B= 15Max =(AgtB ) A B

Ex 2A Identification of Even and Odd number

AimTo write a program to find whether the given number is even or odd

Flowchart

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 8: C_&_DS_Lab_record

Algorithm1 Read the number N2 Find the remainder of N divided by 2 using the Modulus operator(N2)3 If the remainder is zeroThe number is Even numberOtherwiseThe number is Odd number4 Print the result5 Stop

Program To find whether the number is even or oddincludeltconiohgtincludeltstdiohgtvoid main()int nrclrscr()

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 9: C_&_DS_Lab_record

printf(Enter a number)scanf(dampn)r=n2if(r= =0)printf(ntThe given number d is evenn)elseprintf(ntThe given number d is oddn)getch()Output 1Enter a number8The given number 8 is evenOutput 2Enter a number-7The given number -7 is odd

2B To display studentrsquos Grade

AimTo write a lsquoCrsquo program to read the mark of the student and display gradebased on the following normsgt=75 Grade A gt=50 and lt75 Grade B gt=25 and lt50 Grade Clt25 Grade F

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 10: C_&_DS_Lab_record

Flowchart

Algorithm1 Read the average mark of the student2 If the mark is gt=75 print ldquoGRADE Ardquo3 If the mark is between 50 to 75 print ldquoGRADE Brdquo4 If the mark is between 25 to 50 print ldquoGRADE Crdquo5 If the mark is less than 25 print ldquoGRADE Frdquo6 Stop

Program To display the grade of the student includeltstdiohgtincludeltconiohgtvoid main()float avgclrscr()printf(Enter the average mark of the student)

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 11: C_&_DS_Lab_record

scanf(fampavg)if(avggt=75)printf(ntThe students grade - A)else if(avggt=50)printf(ntThe students grade - B)else if(avggt=25)printf(ntThe students grade - C)elseprintf(ntThe students grade -F)getch()Output 1Enter the average mark of the student78The students grade - AOutput 2Enter the average mark of the student50The students grade ndash BOutput 3Enter the average mark of the student30The students grade - COutput 4Enter the average mark of the student24The students grade -F

Viva Questions1) What is a decision making statementDecision making statement is used to break the normal flow of theprogram and execute part of the statement based on some condition2) What are the various decision making statements available in C 1048766 If statement1048766 If else statement1048766 Nested if statement1048766 If else ladder statement1048766 Switch statement3) Write the program logic to find biggest among three without using

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 12: C_&_DS_Lab_record

rdquo =rdquoreturn (agtb) (agtc ac) (bgtc b c)

3A To check for perfect NumberAimTo write a lsquoCrsquo program to find whether the given number is perfect numberor notA number is a perfect number if the sum of the factors of the numberother than itself is equal to that numberExample 28=1+2+4+7+14 is a perfect numberFlowchart

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 13: C_&_DS_Lab_record

Algorithm1 Read the number N2 If the number is less than 0 goto step 73 Initialize sum=1 i=24 if N i=0 then sum=sum+i5 Increment i If ilt=N2 goto step 46 if sum=NPrint the number is a perfect numberelsePrint the number is not a perfect number7 StopProgram To find whether the given number is perfect number includeltstdiohgtincludeltconiohgtvoid main()int nsum=1iclrscr()printf(Enter a number)

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 14: C_&_DS_Lab_record

scanf(dampn)if(ngt0)for(i=2ilt=n2i++)if(ni==0) sum=sum+iif(sum==n)printf(ntd is a perfect numbern)elseprintf(ntd is not a perfect numbern)elseprintf(ntThe input number should be greater than zero)getch()Output -1Enter a number2828 is a perfect numberOutput-2Enter a number5656 is not a perfect numberOutput-3Enter a number-28The input number should be greater than zero

3B To design simple CalculatorAimTo 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 userrsquos choice Perform the operation and display the result using switch statement

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 15: C_&_DS_Lab_record

Algorithm1 Read the two floating point numbers A B2 Display the menu1 - Add2 - Subtract3 - Multiply4 - Divide3 Get the userrsquos choice4 If choice =1 then Result=A+B Goto step 85 If choice =2 then Result=A-B Goto step 86 If choice =3 then Result=AB Goto step 87 If choice =4 then Result=AB Goto step 88 Display the result9 StopProgram To design simple calculator includeltstdiohgtincludeltconiohgtvoid main()float abres

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 16: C_&_DS_Lab_record

int chclrscr()printf(Enter the value of A)scanf(fampa)printf(Enter the value of B(Bltgt0))scanf(fampb)printf(nnMathematical Operations)printf(n)printf(nt1-gtAdd)printf(nt2-gtSubtract)printf(nt3-gtMultiply)printf(nt4-gtDivide)printf(nnEnter your choice)scanf(dampch)switch(ch)case 1res=a+bbreakcase 2res=a-bbreakcase 3res=abbreakcase 4res=abbreakprintf(Answer =2fres)getch()Output 1Enter the value of A5Enter the value of B(Bltgt0)7Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice1Answer =1200Output 2Enter the value of A7Enter the value of B(Bltgt0)56Mathematical Operations

1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice2Answer =-4900Output 3Enter the value of A52Enter the value of B(Bltgt0)3Mathematical Operations1-gtAdd2-gtSubtract3-gtMultiply4-gtDivideEnter your choice3Answer =1560

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 17: C_&_DS_Lab_record

4A To find sum of integers between A and BAimTo write a lsquoCrsquo program to find the sum of all integers between any twonumbersFlowchart

Algorithm1 Read the two numbers A and B2 Initialize sum=0 i=A3 Repeat step 4 and 5 until i lt=B4 Sum=Sum+i5 i=i+16 Print Sum7 Stop

Program Sum of integers between given two ranges includeltstdiohgtincludeltconiohgtvoid main()int abisum=0clrscr()printf(Enter the starting number)scanf(dampa)printf(Enter the ending number)scanf(dampb)for(i=ailt=bi++)sum=sum+iprintf(ntThe sum of integers between d and d=dabsum)getch()Output

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 18: C_&_DS_Lab_record

Enter the starting number5Enter the ending number12The sum of integers between 5 and 12=68

4B To print Fibonacci numbersAimTo write a lsquoCrsquo program to print the first ten terms of the FibonacciSequence assuming the first two terms as 0 and 1Flowchart

Algorithm1 Initialize f1=0 f2=1 i=32 Print f1f23 Repeat steps 4 to 8 until ilt=104 f3=f1+f25 Print f36 f1=f2 f2=f37 i= i +18 StopProgram Fibonacci series includeltstdiohgtincludeltconiohgtvoid main()int f1=0f2=1f3iclrscr()printf(Fibonacci series)printf(nnt)printf(5d5df1f2)for(i=3ilt=10i++)f3=f1+f2printf(5df3)f1=f2f2=f3getch()

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 19: C_&_DS_Lab_record

OutputFibonacci series0 1 1 2 3 5 8 13 21 34

4C To find number of positive negative and zero in N elementsAimTo find the number of positive negative and zeros in given N elementsFlowchart

Algorithm1 Read the number of elements N2 Initialize pos=0 neg=0 ze=03 Repeat steps 4 to 5 N times4 Read the number X5 If X =0ze++else if Xgt0pos++elseneg++6 Print pos neg ze7 Stop

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 20: C_&_DS_Lab_record

Program To find number of Positive Negative and Zeros in given N numbers includeltstdiohgtincludeltconiohgtvoid main()int nxipos=0neg=0ze=0clrscr()printf(Enter number of terms)scanf(dampn)printf(nnEnter d numbersnn)printf(n)for(i=1ilt=ni++)scanf(dampx)if(x==0)ze++else if(xgt0)pos++elseneg++C and Data Structures Lab ManualMSPVL Polytechnic College Pavoorchatram Page 27printf(ntNumber of positive numbers=dpos)printf(ntNumber of negative number=dneg)printf(ntNumber of zeros=dze)getch()OutputEnter number of terms7Enter 7 numbers230-64-1203Number of positive numbers=3Number of negative number=2Number of zeros=2

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 21: C_&_DS_Lab_record

Viva Questions1) What are the various looping statements available in Ca) While statementb) Dowhile statementc) For statement2) What is the difference between while and dowhile statementWhile is an entry controlled statement The statements inside thewhile may not be executed at all when the condition becomes false at thefirst attempt itselfThe dowhile is an exit controlled statement The statements in theblock are executed at least once

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 22: C_&_DS_Lab_record

5A To calculate amp display the Total and Average of integersAim To calculate and display the total and the average of 10 integer numbersFlowchart

Algorithm1 Define main Function amp Declare all variables required2 Assign Initial value to the variable sum=03 Read 10 numbers and store it in an array variable a[i]4 Calculate the total of 10 numbers and find the average5 Sum=sum + a[i]6 Avg=sum 107 Display the array elements and the total8 Stop

Program

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 23: C_&_DS_Lab_record

Program to find sum and average of 10 numbers includeltstdiohgtvoid main()int ia[10]float sumavgsum=0clrscr()printf(---------- INPUT------------nn)printf(Enter the Array Elements (10 Nos)n)for (i=0ilt10i++)scanf(dampa[i])for(i=0ilt10i++)sum=sum+a[i]printf(----------- OUTPUT----------nn)printf(The Array Elements aren)for(i=0ilt10i++)printf(dna[i])printf(Sum of 10 Numbers=== 0fnnsum)avg=sum10printf(Average of 10 Numbers=== 2favg)getch()Output---------- INPUT------------Enter the Array Elements (10 Nos)12345678910----------- OUTPUT----------The Array Elements areSum of 10 Numbers=== 55Average of 10 Numbers=== 550

5B To calculate amp display the Total marks using 2D arrayAim

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 24: C_&_DS_Lab_record

Read 3 subject marks of 4 students Write a program to calculate anddisplay the total marks of each student Use a 2D (two-dimensional) array tostore the marksFlowchart

Algorithm1 Define main Function2 Declare all variables in specified data type3 Get the details for 4 students Rno amp Name of the students using asingle dimensional array4 And a inner for loop is to be used to get 3 marks of each students5 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 includeltstdiohgt

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 25: C_&_DS_Lab_record

void main()int ijkrno[10]sum[10]mark[10][10]tot[10]float avg[10]char name[10][10]sub[10]clrscr()for(i=0ilt4i++)sum[i]=0printf(nStudent Detail No dni)printf(Enter the Student Rno )scanf(damprno[i])printf(Enter the Student Name )scanf(sname[i])for(j=0jlt3j++)printf(Enter the Mark d j)scanf(dampmark[i][j])sum[i]=sum[i]+mark[i][j]avg[i]=sum[i]3printf(n---------OUTPUT--------nn)for(i=0ilt4i++)printf(nStudent No di)printf(nt Rno t )printf(drno[i])printf(nt Namet )printf(sname[i])for(j=0jlt3j++)printf(nt Subdttj)printf(dmark[i][j])printf(n)printf(ntTotal Marks )printf(dsum[i])printf(ntAverage 2favg[i])getch()OutputStudent Detail No 0Enter the Student Rno 1001Enter the Student Name MuthuKumarEnter the Mark 0 89Enter the Mark 1 78Enter the Mark 2 82Student Detail No 1Enter the Student Rno 1002Enter the Student Name ShivaKumarEnter the Mark 0 76Enter the Mark 1 80Enter the Mark 2 83Student Detail No 2Enter the Student Rno 1003Enter the Student Name RamKumarEnter the Mark 0 89Enter the Mark 1 90Enter the Mark 2 91Student Detail No 3Enter the Student Rno 1004

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 26: C_&_DS_Lab_record

Enter the Student Name NanthaKumarEnter the Mark 0 86Enter the Mark 1 56Enter the Mark 2 73--------------OUTPUT------------------Student No 0Rno 1001Name MuthuKumarSub0 89Sub1 78Sub2 82Total Marks 249Average 8300Student No 1Rno 1002Name ShivaKumarSub0 76Sub1 80Sub2 83Total Marks 239Average 7966Student No 2Rno 1003Name RamKumarSub0 89Sub1 90Sub2 91Total Marks 270Average 9000Student No 3Rno 1004Name NanthaKumarSub0 86Sub1 56Sub2 73Total Marks 215Average 7166

Viva questions1) What is an arrayAn array is a collection of data of same data type The elements of thearray are stored in consecutive memory locationsThe array elements can be processed using its index2) What is the starting index of an array in lsquoCrsquoThe starting index of an array in lsquoCrsquo is 03) What are the types of array

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 27: C_&_DS_Lab_record

1048766 One dimensional array1048766 Two dimensional array1048766 Multidimensional array4) What is a two dimensional arrayTwo dimensional is n array of one dimensional array The elements in thearray are referenced with the help of its row and column index5) What are the advantages of the functions1048766 Debugging is easier1048766 It is easier to understand the logic involved in the program1048766 Testing is easier1048766 Recursive call is possible1048766 Irrelevant details in the user point of view are hidden in functions1048766 Functions are helpful in generalizing the program

6A To find minimum of two numbers using functionAimDevise a function called min (x y) that returns the smaller of two doublevalues Test the function with a simple dataFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 28: C_&_DS_Lab_record

Algorithm1 Define main Function amp Declare all variables required2 Define a function prototype called double min(doubledouble)3 Read two values XY4 Call Function min(XY) and store the return value in a variable5 Print the result6 In Function Definitionbull Check the smallest number by using a relational Operator(lt)bull Return the smallest value to step 6Program Program to write a function to find minimum value includeltconiohgtincludeltstdiohgt Main Function void main()double xymmdouble min(doubledouble) Function Prototype clrscr()printf(Enter the value of x)scanf(lfampx)printf(Enter the value of y)scanf(lfampy)mm=min(xy) Calling the function min(ab) printf(nntThe minimum of 4lf and 4lf is 4lfxymm)getch() Function to return the minimum of two numbers double min(double adouble b)if(altb)return(a)elsereturn(b)

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 29: C_&_DS_Lab_record

Output 1Enter the value of x45565Enter the value of y3223The minimum of 455650 and 322300 is 322300Output 2Enter the value of x-12Enter the value of y12The minimum of -12000 and 12000 is -12000

6B To calculate factorial using recursive functionAimTo calculate the factorial of given number using recursive functionFlow chart

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 30: C_&_DS_Lab_record

Algorithm1 Define main Function amp Declare all variables required2 Define a Function prototype with one argument and return value3 Read an integer value and store it in a variable 4 Call the function called factorial( ) and pass the value as argument5 Print the return valueIn function DefinitionA) Calculate the value for given numberNfactorial(N - 1)Repeat step A until n becomes 0 or 1Program Program to find Factorial of Given No using Recursive Function include ltstdiohgtlong factorial(long)void main()long number=0fclrscr()printf(nEnter an integer value )scanf(ldampnumber)f=factorial(number) Calling Function printf(nThe Factorial of ld is ldnnumberf)getch()long factorial(long N)if(Nlt2) Terminating Condition return Nelsereturn Nfactorial(N-1) Recursive call OutputEnter an integer value6 The Factorial of 6 is 720Viva Questions1) What is a functionFunctions are group of statements that can perform a taskFunctions reduce the amount of coding and the functions can be calledfrom another program2) Write the syntax of a function definition

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 31: C_&_DS_Lab_record

return-value-type function-name( parameter-list )declarations and statementsndash Function-name any valid identifierndash Return-value-type data type of the result (default int)bull void ndash indicates that the function returns nothingndash Parameter-list comma separated list declares parametersbull A type must be listed explicitly for each parameter unlessthe parameter is of type int3) What is a recursive functionA function that calls itself is called a recursive function4) How the functions can be called1048766 Call by valueo Copy of argument passed to functiono Changes in function do not effect originalo Use when function does not need to modify argumento Avoids accidental changes1048766 Call by referenceo Passes original argumento Changes in function effect originalo Only used with trusted functions5) What is the use of return statementThe return statement is used to exit from the function and return avalue

7A To calculate the number of vowels in a stringAimWrite a C program to find the number of vowels present in the string[Assume your string contains both uppercase and lowercase characters]

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 32: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Assign the vowels to an array variable

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 33: C_&_DS_Lab_record

A[ ] = ldquoaeiouAEIOUrdquo5 Get the String and store it in a variable6 In a nested for Loop Check the given string is equal to the value assigned in the arrayvariable This is done until the string becomes NULL(o) If the character in a string is equal increment the COUNT variableby 17 Print the Count variable which gives the resultProgram Program to count Noof Vowels in a String includeltstdiohgtincludeltstringhgtvoid main()char strchar a[]=aeiouAEIOUint ijcount=0clrscr()printf(nEnter the stringhellipn)gets(str)for(i=0str[i]=0i++)for(j=0a[j]=0j++)if(a[j] == str[i])count++breakprintf(n d vowels are present in the string -gt scountstr)getch()OutputEnter the StringhellipProgramming3 Vowels are present in the string -gt Programming

7B To find given string is palindrome or notAimWrite a program to find whether a given string is palindrome or not

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 34: C_&_DS_Lab_record

Algorithm1 Define main Function amp Declare all variables required2 Let flag =03 Read a String and Find the Length of the String as n4 Using a for loop check the character str[i] and str[n-1-i]

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 35: C_&_DS_Lab_record

5 if equalcontinue the for loop until i=n2elseset flag=1 and break the for loop6 If flag =0Print ldquoThe string is PalindromerdquoElsePrint ldquoThe string is not palindromerdquo7 StopProgram Program to find whether the string is Palindrome includeltstdiohgtincludeltconiohgtincludeltctypehgtvoid main()char str[20]int niflag=0clrscr()printf(Enter the string)gets(str)n=strlen(str) calculate string length Loop to check the charactersfor(i=0iltn2i++)if(toupper(str[i])=toupper(str[n-1-i]))flag=1break Check the resultif(flag==0)printf(ntThe string s is a palindromestr)elseprintf(ntThe string s is not a palindromestr)getch()OutputEnter the StringhellipmalayalamThe Given String is PalindromeEnter the StringhellipTamilNaduThe Given String is not Palindrome

7C To convert the lowercase into uppercaseAimRead a string which consists of both lower case characters and upper casecharacters Convert the lowercase character into upper case and vice versaDisplay the new string

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 36: C_&_DS_Lab_record

Algorithm1 Define main Function amp Declare all variables required2 Read a String and Find the Length of the String3 Check the characters ASCII value whether it lies between 97 and 1224 If the Condition is truea Change the ASCII value of the character by subtracting 325 Else check the ASCII value lies between 65 and 90a If the condition becomes truei Add 32 to the value for the character6 Repeat the step 4 amp step 5 until the length of the string becomes NULL7 Print the result8 StopProgram Convert the lowercase character into upper case and vice versa includeltstdiohgtvoid main()char str[20]

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 37: C_&_DS_Lab_record

int iclrscr()printf(n--------INPUT---------n)printf(Enter any string-gt)scanf(sstr)printf(nn---------OUTPUT--------nn)printf(The Entered string is----gtsnnstr)for(i=0ilt=strlen(str)i++)if(str[i]gt=65 ampamp str[i]lt=90) Checking for upper case letters

str[i]=str[i]+32else if(str[i]gt=97 ampamp str[i]lt=122) Checking for lowercase letters

str[i]=str[i]-32printf(nThe Converted string is----gtsstr)getch()Output--------INPUT---------Enter any string-gtjAVAiNTERFACE---------OUTPUT--------The Entered string is----gtjAVAiNTERFACEThe Converted string is----gtJavaInterface

Viva Questions1) What is a stringString is a sequence of characters2) What is the use of getchar() and gets() functionsThe getchar() function is used to read a single character from the keyboardThe gets() function is used to read a sequence of characters from thekeyboard

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 38: C_&_DS_Lab_record

3) What is the use of puts() functionThe puts() function is used to display a string in the standard outputdevice4) What is the difference between getchar() and getch() functionBoth the functions are used to read a single character from the keyboardWhen we use getchar() the character read is displayed on the screen When weuse getch() the character is not echoed on the screen5) What is the difference between strings and character arraysA major difference is string will have static storage duration whereas asa character array will not unless it is explicity specified by using the statickeyword6) Give some string processing functionsstrcmp() - Used to compare two stringsstrcat() ndash Used to concatenate two stringstrlen() ndash Returns the length of the stringstrcpy() ndash Copies one string to anothertoupper() ndashConverts the lowercase letters to uppercasetolower() ndashConverts the uppercase letters to lower case7) What is the delimiter for stringlsquo0rsquo is the string delimiter

8A Display the students detail using nested structureAimWrite a program for nested structure the two structures are declaredwithin a single structure The two inner structures are ldquodobrdquo ( fields dd mmyy) and ldquoaddressrdquo (st cty) and the outer structure ldquoStudentrdquo ( fields rollnoname)Write a main program to get and display the details of N students

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 39: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define the Structure called student and structure members (Rno ampName)4 Define a nested structure called dob and define the structuremembers(day month amp year) Also define a structure variable d5 Define another nested structure called address and define the structuremembers (street amp City) Also define a structure variable ad6 Define main Function amp Define a structure of array variable Stu [ ]7 Read N for number of students8 Get the studentrsquos details by structure referencing operator ()Eg Stu[ ]ddayStu[ ] adstreet9 Repeat step 8 until N number of values10 Display the students detail by structure referencing operator ()11 Repeat step 10 for N timesProgram program to get and display the details of N students Using structure includeltstdiohgtstruct studentint rnochar name[10]struct dob

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 40: C_&_DS_Lab_record

int daychar mon[10]int yeardstruct addresschar stcityadvoid main()struct student stu[10]int niclrscr()printf(Enter No of Students)scanf(dampn)for(i=0iltni++)printf(Student Detail No di)printf(nEnter The Student Rnot)scanf(dampstu[i]rno)printf(nEnter the Student Namet)scanf(sstu[i]name)printf(nEnter the Date of Birtht)printf(nttDay t )scanf(dampstu[i]dday)printf(nttMonth t)scanf(sstu[i]dmon)printf(nttYear t)scanf(dampstu[i]dyear)printf(nEnter The Addressn)printf(nt Enter the Street Namet)scanf(sstu[i]adst)printf(n tEnter the City Name t)scanf(sstu[i]adcity)clrscr()printf(nn ----------OUTPUT----------nn)for(i=0iltni++)printf(Student No dnni)printf(ttStudent RNott)printf(dstu[i]rno)printf(nttStudent Namett)printf(sstu[i]name)printf(nttDate of Birthtt)printf(d- s - d stu[i]ddaystu[i]dmonstu[i]dyear)printf(nttAddressn)printf(nttt Street tsstu[i]adst)printf(nttt City tsnstu[i]adcity)getch()OutputEnter No of Students2Student Detail No 0Enter The Student Rno 552001Enter the Student Name ArunKumarEnter the Date of BirthDay 06Month 11Year 1979Enter The AddressEnter the Street Name SakthiNagar

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 41: C_&_DS_Lab_record

Enter the City Name TenkasiStudent Detail No 1Enter The Student Rno 552002Enter the Student Name BanuMathiKEnter the Date of BirthDay 07Month NovemberYear 1979Enter The AddressEnter the Street Name FirstStreetEnter the City Name Madurai----------OUTPUT----------Student No 0Student RNo 27713Student Name ArunKumarDate of Birth 6- 11 - 1979AddressStreet SakthiNagarCity TenkasiStudent No 1Student RNo 27714Student Name BanuMathiDate of Birth 7- November - 1979AddressStreet FirstStreetCity Madurai

8B To print the students name rollno using unionsAimWrite a Program to print the student name rollno marks using unions

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 42: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define union called student and structure members (Rno Name ampmark[ ])4 Define the main function and all variables5 Read the student rno and name6 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 unionsincludeltstdiohgtunion student

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 43: C_&_DS_Lab_record

int rnochar nameint mark[10]stuvoid main()int iclrscr()printf(nEnter the Student Rno t)scanf(dampsturno)printf(nEnter the Student Name t)scanf(sstuname)for(i=0ilt3i++)printf(nEnter the Markd ti)scanf(dampstumark[i])printf(n--------OUTPUT-----------n)printf(Students Record)printf(nttRno )printf(dsturno)printf(nttName )printf(sstuname)for(i=0ilt3i++)printf(nttMarkd i)printf(dstumark[i])getch()OutputEnter the Student Rno 100Enter the Student Name ShivaEnter the Mark0 87Enter the Mark1 78Enter the Mark2 90--------OUTPUT-----------Students RecordRno 87Name ShivaMark0 87Mark1 78Mark2 90

Viva Questions1) What is a structure1048766 Structure is a collections of related variables under one name and Cancontain variables of different data types1048766 Commonly used to define records to be stored in files1048766 Combined with pointers can create linked lists stacks queues andtrees

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 44: C_&_DS_Lab_record

2) What is an union1048766 Memory that contains a variety of objects over time1048766 Only contains one data member at a time1048766 Members of a union share space1048766 Conserves storage1048766 Only the last data member defined can be accessed3) How the members of structures and unions can be accessedThe Members of structures and unions can be accessed with the help ofdot operator asStructure variablename structure member4) What is a nested structureDefining a structure within structure is called nested structure

9A To swap two integer using pointersAimWrite a program to swap two integer numbers using pointers

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 45: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Define a function prototype swap(intint) with two pointer argument5 Read two values as input6 Print the two values before swapping process7 Function call by passing the address using referencing operator (amp)8 Print two numbers after swapping process9 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 valueProgram Program to Swap two Numbers Using Pointers includeltstdiohgtvoid main()int ab Function Declaration with two arguments void swap(intint)clrscr()printf(Enter the First Numbern)scanf(dampa)printf(Enter the Second Numbern)scanf(dampb)printf( Result Before Swappingn)printf(A=== dna)printf(B=== dnb)swap(ampaampb) Call of Function printf( Result After Swappingn)printf(A=== dna)printf(B=== dnb)getch() Function Definition

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 46: C_&_DS_Lab_record

void swap(int x int y)int temptemp = x contents of pointer x = yy = tempOutputEnter the First Number28Enter the Second Number42Result Before SwappingA=== 28B=== 42Result After SwappingA=== 42B=== 28

9B To read a string use pointerAimRead a string Print the above string such that each line contains a singlecharacter ( Use pointers)Flow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 47: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function and string function3 Define main Function amp Declare all variables required4 Get the string to print character by character5 Find the length of the string6 Assign the first pointer address content to the character variable7 Print the character variable8 Repeat step 6 and step 7 until length of the string becomes 0Program Program to Print the string such that each line contains a single character includeltstdiohgtincludeltstringhgtvoid main()int ilenchar strcptrclrscr()printf(Enter the Stringn)scanf(sstr)ptr=strlen=strlen(ptr)printf(---------OUTPUT----------nn)printf(Entered String is --gt stnnstr)printf(Output character by charactern)for(i=0iltleni++)

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 48: C_&_DS_Lab_record

c=ptrprintf(cnc)ptr++getch()OutputEnter the Stringprogramming---------OUTPUT----------Entered String is --gt programmingOutput character by characterprogramming

9C To print the elements in reverse order using pointersAimRead an integer array consist of N elements Print the elements in reverseorder using pointersFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 49: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function3 Define main Function amp Declare all variables required4 Get the array number N5 Read N number of elements and store it in the array variable num[ ] )6 Print the array list7 Print the value using pointer operator 8 Repeat step 7 for N times from N to 0

Program Program to print the elements in reverse order using pointers include ltstdiohgtvoid main()int innum[10]

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 50: C_&_DS_Lab_record

clrscr()printf(Enter the number of elements in the array)scanf(dampn)printf(Enter the Array Numbersn)for (i= 0 iltn i++ )scanf(dnum+i)printf(nnThe Array Numbers aren)for(i=0iltni++)printf(5d(num+i))printf(nnReversed Array List n)for (i = n-1 i gt= 0 i-- )printf(5d( num+i))getch()OutputEnter the number of elements in the array5Enter the Array Numbers23 78 45 23 8The Array Numbers are23 78 45 23 8Reversed Array List 8 23 45 78 23

10A To read an array using pointerAimWrite a C program to read through an array of any type using pointersWrite a C program to scan through this array to find a particular valueFlowchart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 51: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard IO function Conversion and Stringfunction3 Define a function prototype called search( )4 Define main Function amp Declare all variables required

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 52: C_&_DS_Lab_record

5 Allocate dynamic memory for a variable using malloc( ) function6 Read a string7 Repeat step 5 and step 6 until n number of array elements8 Print the array elements9 Call the function Search ( ) by passing N number of strings10 In function DefinitionDefine a temporary variable and allocate the memory space usingmalloc( ) Read the String to search and store it in the temporary variable Check the value with the array element by using string comparefunction If they are equal set flag = 0 else set flag = 111 Check the condition if flag = 0 Print the value is found Otherwise printthe value given to search is not foundProgram Pointer and Array of any data type to search a given value includeltstdiohgt includeltstringhgt includeltctypehgtint flag FUNCTION PROTOTYPE int search(char int ) Function main void main( )char choiceint i n = 0char string[100]clrscr()dostring[n] = (char ) malloc(50)printf(Input string )gets(string[n])n++printf(n Input another YN )choice = getchar()fflush(stdin)while(toupper(choice) == Y)printf(nArray list n)printf( n)for (i = 0 i lt n i++)printf(sn string[i]) Function CALL search(string n)if (flag==0)printf(The String Given is FOUND)elseprintf(The String Given is Not Found)getch() Definition of function int search(char str int n)int ijchar temp[10] temp[0]= (char )malloc(50)printf(Enter the string to Findn)gets(temp)printf(nThe String to Findn)puts(temp)

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 53: C_&_DS_Lab_record

for(i=0iltni++)if(strcmp(str[i]temp)==0)flag=0elseflag=1return(flag)OutputInput string ManiInput another YN yInput string RaajuInput another YN yInput string 123Input another YN yInput string 5634Input another YN nArray listManiRaaju1235634Enter the string to Find5634The String to Find5634The String Given is FOUND

10B To find the length of the string using pointerAimTo find the length of the string using pointerFlow chart

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 54: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read the String5 Increase the pointer value of the variable using increment operator6 The count variable is incremented by 17 Repeat step 5 and step until the string pointer is NULL8 Print the counted numbers which is the length of the stringProgram Program to Find Length of Strings using Pointers includeltstdiohgtvoid main()int xchar strx=0clrscr()printf(Enter the Stringn)scanf(sstr)printf(Length of s is str)while (str = 0)x++str++printf(dx)getch()OutputEnter the StringProgrammingLength of Programming is 11

10C To concatenate two string using pointerAimTo concatenate two string using pointer

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 55: C_&_DS_Lab_record

Algorithm1 Begin a program with a comment line2 Include Header Files for standard input output function3 Define main Function amp Declare all variables required4 Read two strings s1 and s25 Move to the end of first string using a temporary pointer6 Add the second string to the end of first string pointed bytemporary variable7 Print the concatenated string s1Program String Concatenation includeltstdiohgtincludeltconiohgtvoid main()char s1s2tempclrscr()printf(Enter the first string)gets(s1)

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 56: C_&_DS_Lab_record

printf(Enter the second string)gets(s2)printf(ntThe string s1 before concatenationss1)printf(ntThe string s2 before concatenationss2)temp=s1while(temp=0) Move to end of string1 temp++while(s2=0) Add second string to the end of string2 temp=s2temp++s2++temp=0printf(ntThe concatenated string s1ss1)getch()OutputEnter the first stringOperatingEnter the second stringSystemThe string s1 before concatenationOperatingThe string s2 before concatenationSystemThe concatenated string s1OperatingSystem

Viva Questions1) What is a pointerPointer is a variable that holds the address of another variable2) What is called the indirection operatorslsquorsquo is called the indirection operator since it is used to indirectly access thevalue of a variable through its pointer

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 57: C_&_DS_Lab_record

3) What are the advantages of pointer1048766 As pointer enables us to access a variable that is defined outside thefunction1048766 Pointers are more efficient in handling arrays1048766 Pointers reduce the program length and complexity of the program1048766 Pointers increase the execution speed1048766 Use of pointers to character strings results in saving of data storagespace in memory4) What is the use of void pointerVoid pointer is used to point a variable of any data type5) What is the relationship between arrays and pointerThe arrays can be easily manipulated with the help of the pointers ofappropriate type The array name can be assigned to a pointer and theelements in the array can be accessed by incrementing the pointerFor exampleint a[5]= 23671int p=aThen 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 VowelsAimTo write a lsquoCrsquo program to create a linked list to contain the vowels lsquoarsquo lsquoersquo lsquoirsquo lsquoorsquo lsquoursquo in the data field of the nodes

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 58: C_&_DS_Lab_record

Algorithm1 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 lsquonewnodersquo3 Define function insafter( px) to insert a node after a given nodeLet the address for the previous node be lsquoprenodersquo and data to beinserted as X1048766 Get a new node newnode1048766 newnode1048766data=X1048766 newnode1048766next= prenode1048766 next1048766 prenode1048766next=newnode1048766 Return the address of the new node4 Define the function to create the list1048766 Store the vowels in a character array1048766 Get a new node and save its address1048766 Store the first data Let the next field be NULL1048766 Store the remaining data in the link list by using thefunction insafter( ) that inserts a node after the given node5 Define a function Show to print the linked list6 Define the main function that calls the function to create the list and toprint the list 7 StopProgram To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 59: C_&_DS_Lab_record

struct nodechar datastruct node nexttypedef struct node nodeptrnodeptr prenodefirstnodeptr getnode()nodeptr d =(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pchar x)nodeptr newnodeif (p==NULL)printf(n Void insertion)exit(1)newnode=getnode() newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnode return newnodevoid createlist() Function for creation char vow[]=aeiouint i prenode=first=getnode()prenode-gtdata=vow[0] prenode-gtnext=NULLfflush(stdin)for(i=1ilt6i++)prenode=insafter(prenodevow[i])void show() Function for displaying the list prenode=firstwhile (prenode-gtnext= NULL) printf(c----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL)void main() Main Function clrscr()createlist()printf(nThe created List)printf(nnn)show()getch()OutputThe created Lista----gte----gti----gto----gtu----gtNULL

11B To delete the first node in the linked list of integersAimTo write a lsquoCrsquo program to delete the first node that contains an integerdata item of a single linked list

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 60: C_&_DS_Lab_record

Algorithm1 Define functions getnode() insafter() and createlist() to get a newnode insert a node after a node and create the linked list respectively2 The first pointer points the address of the first node3 Define a function delfirst() that deletes the first node and returns thedata in the first node using the algorithm given below1048766 Store the data pointed by the first node in a variable1048766 Make first pointer to point the next node asfirst=first1048766next1048766 Return the address of the new first node4 Define a function show to print the linked list5 Define the main function as1048766 Create the linked list using the function createlist()1048766 Print the list using the function show()1048766 Delete the first node using the function delfirst()1048766 Print the list using the function show()6 Stop

Program To create and print linked list includeltstdiohgtincludeltconiohgt Node structure definition struct node

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 61: C_&_DS_Lab_record

int datastruct node nexttypedef struct node nodeptrnodeptr prenodefirst Get node Function nodeptr getnode()nodeptr dd=(nodeptr) malloc(sizeof(struct node))return d Function for insertion after a node nodeptr insafter(nodeptr pint x)nodeptr newnodeif (prenode==NULL)printf(n Void insertion)exit(1)newnode=getnode()newnode-gtdata=xnewnode-gtnext=prenode-gtnextprenode-gtnext=newnodereturn newnode Function for creation void createlist()int nochar ans=yprenode=first=getnode()printf(n Enter the data)scanf(dampno)prenode-gtdata=noprenode-gtnext=NULLfflush(stdin)while(ans==y || ans==Y)printf(n Any more data(YN))fflush(stdin)ans=getchar()if(ans==Y || ans==y)printf(n Enter the data)scanf(dampno)prenode=insafter(prenodeno)elsebreak Function to delete the first node int delfirst()int xx=first-gtdatafirst=first-gtnextreturn x Function for displaying the list void show()

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 62: C_&_DS_Lab_record

prenode=firstwhile (prenode= NULL)printf(d----gtprenode-gtdata)prenode=prenode-gtnextprintf(NULL) Main Function void main()int delclrscr()printf(n Creating the list)printf(n)createlist()printf(n Displaying the list)printf(n--------------------nn)show()del=delfirst()printf(nnnThe list after deleting the first node)printf(n---------------------------------------nt)show()printf(nnThe deleted data ddel)getch()OutputCreating the listEnter the data5Any more data(YN)yEnter the data34Any more data(YN)yEnter the data23Any more data(YN)yEnter the data1Any more data(YN)nDisplaying the list--------------------5----gt34----gt23----gt1----gtNULLThe list after deleting the first node---------------------------------------34----gt23----gt1----gtNULLThe deleted data 5

Viva Questions1) What is data structureAn organization and representation of data is called data structure2) What are the two types of data structureData structures can be classified into two typesa) Linear data structuresb) Non-linear data structures3) What is the linear structureIn linear data structure the elements are stored in sequential order Thelinear data structures are1048766 Array1048766 Linked list

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 63: C_&_DS_Lab_record

1048766 Stack1048766 Queue4) What is a linked listLinked list Linked list is a collection of data of same data type but thedata items need not be stored in consecutive memory locations

A Linked list with 3 Nodes5) What are the operations that can be performed on a linked list1048766 Insertion1048766 Deletion1048766 Searching6) What are the possible locations where the data can be inserted into alinked listData can be inserted into the linked list in the beginning in themiddle and at the end7) What are the possible locations where the data can be deleted in alinked listData can be deleted from the first from the last and from themiddle8) What is a doubly linked list or two way listThe linked list which has two pointer which points to the previous nodeand the next node is called a doubly linked listWhen we use doubly linked lilst we can traverse the node in both thedirections9) What is a circular listThe linked list in which the last node points back to the first node is calledcircular list

12 To perform stack operations in Stack using arrayAimTo write a ldquoCrdquo program to perform operations in stack using array

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 64: C_&_DS_Lab_record

Algorithm1 Declare the structure of stack with an array of size 20 to hold the stackand the initialize top =-12 Define a function push( ) to add the data to the stack as1048766 Check if the stack is full if so display ldquoStack Fullrdquo and return1048766 OtherwiseIncrement the top value1048766 Store the data in the stack[top] and return3 Define a function pop( ) that deletes the value in the top of the stackas1048766 If top=-1 print ldquoStack Emptyrdquo and return1048766 Otherwise Print the element at stack[top] and decrement topvalue and return4 Define a function show that prints the elements in the stack5 Define the main function as1048766 Display the menu to the user1 - Push2 - Pop3 ndash List the stack4 ndash Exit1048766 Get the choice from the user1048766 If choice =1 read the data and add it to the stackusing push( ) function1048766 If the choice = 2 delete the data from the stack usingpop ( ) function1048766 If the choice is 3 display the data in the stack1048766 If choice = 4 exit from the program1048766 Else repeat the above steps6 StopProgram stack using array includeltstdiohgtincludeltconiohgtStructure to hold the stackstruct stackint a[20] topsFunction to add element to the stackvoid push(int x)

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 65: C_&_DS_Lab_record

if(stop==20)printf(Stack full)elsestop++sa[stop]=xprintf(ntData is added to stackn)Function to delete element from the stackvoid pop()int xif(stop==-1)printf(ntStack empty)elseprintf(ntThe deleted data is dsa[stop])stop--Function to display the stack datavoid show()int iif(stop==-1)printf(nStack Empty)elseprintf(nThe stack elements)printf(n-------------------nt)for(i=0ilt=stopi++)printf(dtsa[i])printf(lt---topn)Main functionvoid main()int chdataclrscr()stop=-1doprintf(nttt Menu)printf(ntt1-gtPush)printf(ntt2-gtPop)printf(ntt3-gtList stack)printf(ntt4-gtExit)printf(nEnter your choice)scanf(dampch)switch(ch)case 1 printf(Enter the data)scanf(dampdata)push(data)breakcase 2 pop()

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 66: C_&_DS_Lab_record

breakcase 3 show()breakcase 4 exit(0)while(chlt4)getch()OutputMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data67Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice1Enter the data11Data is added to stackMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements-------------------------67 11 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice2The deleted data is 11Menu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice3The stack elements------------------------67 lt---topMenu1-gtPush2-gtPop3-gtList stack4-gtExitEnter your choice4

Viva Questions1) What is stackA stack is a Last-In-First-Out linear data structure in which insertion anddeletion takes place at only one end called the top of the stack2) What are the operations that can be performed on the stackPUSH ndash To add a new element to the top of the stack

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 67: C_&_DS_Lab_record

POP ndash To remove an element at the top of the stack3) What are the applications of the stack1048766 The stack data structure is used in applications where Last-In-First-Out operations are carried out1048766 Stack is used in implementing subroutine calls recursion evaluationof arithmetic expression compilers etc4) What is an arithmetic expressionAn arithmetic expression is a collection of operators and operands5) What is infix postfix prefix notation1048766 Infix Notation If the operator appears between the operands iscalled infix notationExample A+B1048766 Postfix Notation ( Reverse Polish notation)If the operatorcomes after the operand then the notation is called postfixnotationExample AB+1048766 Prefix Notation(Polish notation) If the operator comes beforethe operand then the notation is called prefix notationExample +AB6) What is the infix prefix post fix form of the following expressiona) A + B + C b) (A+B) (C+D) c) A-B C-D

7) Features of Prefix and Postfix expression1048766 The operands are in the same order as the infix notation1048766 Parenthesis is not needed to represent the precedence of operation1048766 The priority of operators is irrelevant

13 Implementation of Queue using arrayAimTo write a ldquoCrdquo program to perform operations in queue using array

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 68: C_&_DS_Lab_record

Algorithm1 Declare the array to hold the queue elements and the variables to holdthe front and rear index2 Define functions to insert data into the rear end of queue as1048766 If the rear=Q-SIZE-1 thenPrint ldquoQueue FullrdquoElseRear=Rear+1Store the s=date in the rear positionPrint the queue3 Define functions to delete the data from the queue1048766 If front=rearPrint ldquoQueue EmptyrdquoElsefront=front+1Print the deleted element and the queue

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 69: C_&_DS_Lab_record

4 Define function to print the elements in the queue5 Define main function1048766 Initialize front = rear =-11048766 Create a queue with elements1048766 Display the menu to the user1-gtInsertion2-gtDeletion3-gtExit1048766 Get the users choiceIf choice = 1 call the function to add elementIf choice = 2 call the function to delete the elementIf choice = 3 then Exit the program1048766 Repeat the step 5 till choice = 36 StopProgram Inserting and deleting elements from the queue includeltstdiohgtincludeltconiohgtdefine Q_SIZE 20Declaration of array for queuestruct queue

int a[Q_SIZE]int frontrear

q Function to insert element into the queue void insert()int xif (qrear==Q_SIZE-1)printf(nnQueue full Insertion not possible)elseprintf(n Enter data to insert)scanf(dampx)qrear++qa[qrear]=xFunction to delete the elements in the queue void deleteq()if(qfront==qrear)printf(nnQueue is empty Deletion not possible)else++qfrontprintf(nn The deleted element is dqa[qfront])Function to display the elements in the queuevoid show()int iif (qfront==qrear)printf(nnQueue Emptyn)elseprintf(nn The elements in the queuen)printf(n)printf(tFront---gt)for(i=qfront+1ilt=qreari++)printf(d qa[i])

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 70: C_&_DS_Lab_record

printf(lt---Rearn) Main programvoid main()int nichclrscr()qfront=qrear=-1printf(n No of elements initially in the queue)scanf(dampn) Creating a queue with n elements for (i=0iltni++)qrear++printf(ntEnter the element)scanf(dampqa[i])show()while(1)printf(nntt Select your choice)printf(nt1-gtInsertion)printf(nt2-gtDeletion)printf(nt3-gtExit)printf(nnEnter your choice)scanf(dampch)switch (ch)case 1insert()show()breakcase 2deleteq()show()breakcase 3exit(0)OutputNo of elements initially in the queue3Enter the element2Enter the element4Enter the element5The elements in the queueFront---gt2 4 5 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice1Enter data to insert45The elements in the queue

Front---gt2 4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtexitEnter your choice2The deleted element is 2The elements in the queueFront---gt4 5 45 lt---RearSelect your choice1-gtInsertion2-gtDeletion3-gtExitEnter your choice3

Viva Questions1) What is a queueQueue is a linear data structure in which insertions are done endone end called the Rear of the queue and Deletions are done at anotherend called the Front The queue is referred as First-In-First-Out datastructure2) What is a circular queueA queue in which both the front and the rear wrap around to thebeginning of the array when they reached the MAX size of the queue iscalled circular queue

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue

Page 71: C_&_DS_Lab_record

3) What is a priority queueA queue where insertions and deletions are performed based onsome priority is called priority queue