CP Lab Manual
CP Lab Manual
LAB OBJECTIVE
• To introduce the student to simple linear and non linear data structures such as lists,
stacks, queues, trees and graphs.
• To enable effective use of arrays, structures, functions, pointers and to implement the
memory management concepts
• To teach the issues in file organization and the usage of file systems
Lab Outcome
Upon successful completion of this Lab the student will be able to:
To obtain the knowledge about the number systems this will be very useful for bitwise
operations.
To develop programs using the basic elements like control statements, Arrays and
Strings.
To solve the memory access problems by using pointers
To understand about the dynamic memory allocation using pointers which is essential for
utilizing memory
To understand about the code reusability with the help of user defined functions.
To develop advanced applications using enumerated data types, function pointers and
nested structures.
To learn the basics of file handling mechanism that is essential for understanding the
concepts in database management systems.
To implement the concepts in data structure like linked lists.
There are 60 systems (Compaq Presario) installed in this Lab. Their configurations are as
follows:
Software
All systems are configured in DUAL BOOT mode i.e., Students can boot from
Windows XP or Linux as per their lab requirement. This is very useful for students
because they are familiar with different Operating Systems so that they can
execute their programs in different programming environments.
Each student has a separate login for database access Oracle 9i client version is
installed in all systems. On the server, account for each student has been created.
This is very useful because students can save their work (scenarios’, PL / SQL
programs, data related projects, etc) in their own accounts. Each student work is
safe and secure from other students.
Students can execute ETL process using this tool. They can import the Meta data
from different source definition into the data warehouse by applying the business
logics.
Students can generate reports using this tool from different Business Objects in
different formats.
Students can execute their assembly language programs using MASM. MASM is
very useful students because when they execute their programs they can see
contents of Processor Registers and how each instruction is being executed in
the CPU.
Using this software, students can depict UML diagrams of their projects.
Systems are assigned numbers and same system is allotted for students when they
do the lab.
a) Explanation on today’s experiment by the concerned faculty using OHP/PPT covering the
following aspects: 25 mins.
100 mins.
Writing of the experiment in the Observation Book:
The students will write the today’s experiment in the Observation book as per the
following format:
a) Name of the experiment/Aim
b) Software/Hardware required
c) Syntax with suitable Options
d) C Programs
e) Test Data
a. Valid data sets
b. Limiting value sets
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 4
c. Invalid data sets
f) Results for different data sets
g) Viva-Voice Questions and Answers
h) Errors observed (if any) during compilation/execution
i) Signature of the Faculty
Students are required to carry their lab observation book and record book with completed
experiments while entering the lab.
Students must use the equipment with care. Any damage is caused student is punishable
Students are not allowed to use their cell phones/pen drives/ CDs in labs.
Students need to be maintain proper dress code along with ID Card
Students are supposed to occupy the computers allotted to them and are not supposed to
talk or make noise in the lab.
Students, after completion of each experiment they need to be updated in observation
notes and same to be updated in the record.
Lab records need to be submitted after completion of experiment and get it corrected with
the concerned lab faculty.
If a student is absent for any lab, they need to be completed the same experiment in the
free time before attending next lab.
Step1: Students have to write the date, aim, S/W & H/W requirements for that experiment in the
observation book.
Step2: Students have to listen and understand the experiment explained by the faculty and note
down the important points in the observation book.
Step3: Students need to write procedure/algorithm in the observation book.
Step4: Analyze and Develop/implement the logic of the program by the student in respective
platform
Step5: after approval of logic of the experiment by the faculty then the experiment has to be
executed on the system.
Step6: After successful execution the results are to be shown to the faculty and noted the same in
the observation book.
Before start of the first lab they have to buy the record and bring the record to the lab.
Regularly (Weekly) update the record after completion of the experiment and get it
corrected with concerned lab in-charge for continuous evaluation.
In case the record is lost inform the same day to the faculty in charge and get the new
record within 2 days the record has to be submitted and get it corrected by the faculty.
If record is not submitted in time or record is not written properly, the evaluation marks
(5M) will be deducted.
Record 5 Marks
5. JNTU SYLLABUS
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
0 -/3/- 4
Week l
a) Write a C program to find the sum of individual digits of a positive integer.
b) A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms
in the sequence. Write a C program to generate the first n terms of the sequence.
c) Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
Week 2
a) Write a C program to calculate the following Sum:
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!
b) Write a C program to find the roots of a quadratic equation.
Week 3
a) The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at2
where ‘u’ and ‘a’ are the initial velocity (m/sec.) and acceleration (m/sec2). Write C
program to find the distance travelled at regular intervals of time given the values of ‘u’
and ‘a’. The program should provide the flexibility to the user to select his own time
intervals and repeat the calculations for different values of ‘u’ and ‘a’.
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 7
b) Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result. (Consider the operators +,-,*, /,
% and use Switch Statement)
Week 4
a) Write C programs that use both recursive and non-recursive functions
i) To find the factorial of a given integer.
ii) To find the GCD (greatest common divisor) of two given integers.
Week 5
a) Write a C program to find the largest integer in a list of integers.
b) Write a C program that uses functions to perform the following:
i) Addition of Two Matrices
ii) Multiplication of Two Matrices
Week 6
a) Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n Characters from a given position in a given string.
b) Write a C program to determine if the given string is a palindrome or not
Week 7
a) Write a C program that displays the position or index in the string S where the string
T begins, or – 1 if S doesn’t contain T.
b) Write a C program to count the lines, words and characters in a given text.
Week 8
a) Write a C program to generate Pascal’s triangle.
b) Write a C program to construct a pyramid of numbers.
Week 9
Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression:
1+x+x2+x3+………….+xn
For example: if n is 3 and x is 5, then the program computes 1+5+25+125. Print x, n, the
sum Perform error checking. For example, the formula does not make sense for
negative exponents – if n is less than 0. Have your program print an error message if
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 8
n<0, then go back and read in the next pair of numbers of without computing the sum.
Are any values of x also illegal? If so, test for them too.
Week 10
a) 2’s complement of a number is obtained by scanning it from right to left and
complementing all the bits after the first appearance of a 1. Thus 2’s complement of
11100 is 00100. Write a C program to find the 2’s complement of a binary number.
b) Write a C program to convert a Roman numeral to its decimal equivalent.
Week 11
Write a C program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
(Note: represent complex number using a structure.)
Week 12
a) Write a C program which copies one file to another.
b) Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)
Week 13
a) Write a C program to display the contents of a file.
b) Write a C program to merge two files into a third file (i.e., the contents of the first file
followed by those of the second are put in the third file)
Week 14
a) Write a C program that uses non recursive function to search for a Key value in a
given list of integers using Linear search.
b) Write a C program that uses non recursive function to search for a Key value in a
given sorted list of integers using Binary search.
Week 15
a) Write a C program that implements the Selection sort method to sort a given array of
integers in ascending order.
Week 17
Write a C program that implements stack (its operations) using a singly linked list to
display a given list of integers in reverse order. Ex. input: 10 23 4 6 output: 6 4 23 10
Week 18
Write a C program that implements Queue (its operations) using a singly linked list to
display a given list of integers in the same order. Ex. input: 10 23 4 6 output: 10 23 4 6
Week 19
Write a C program to implement the linear regression algorithm.
Week 20
Write a C program to implement the polynomial regression algorithm.
Week 21
Write a C program to implement the Lagrange interpolation.
Week 22
Write C program to implement the Newton- Gregory forward interpolation.
Week 23
Write a C program to implement Trapezoidal method.
Week 24
Write a C program to implement Simpson method.
COMPUTER PROGRAMMING
WEEK 1:
1.1.a)a)Write
WriteaaCCprogram
programtotofind
findthe
thesum
sumofofindividual
individualdigits
digitsofofpositive
positive
integer.
integer.
Aim:
Implementation of c program to find the sum of individual digits of positive integer.
Description:
Summation of digits of a number
Ex: 1234
Summation =1+2+3+4=10
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Initialize sum ← 0
Step 4: while(n!=0)
Begin
Read n
Sum = 0
whil False
e
n!=0
True
r=n%10
sum=sum+r
n=n/10
Print Sum
Stop
Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum=0;
clrscr();
printf("ENTER A POSITIVE INTEGER \n");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("THE SUMOF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..%d",sum);
getch();
}
Program Output
THE SUM OF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..10
Output screen:
Fig.1.1
Aim:
Implementation of c program to generate the first n terms of the Fibonacci sequence..
Description:
Initial Fibonacci numbers are 0 and 1. Next number can be generated by adding two
numbers. So 0+1=1. Therefore next number can be generated by adding two previous . so
Fibonacci series is 0 1 1 2 3 5 ……
Algorithm:
Step 1 : Start
Step 2 : Read n
Step 3 : Initialize f0 ← 0, f1 ← 1, f ← 0
Step 4 : i=0
Step 5 : while(i<=n) do as follows
printf("%d\t",f0);
f=f0+f1;
f0=f1;
f1=f;
i=i+1;
If not goto step 7
Step 6 : Stop
f0=0, f1=1
i=0
FALSE
whil
e
i<n
TRUE Print f0
Stop
f=f0+f1;
Print f0 f0=f1;
f1=f;
i=i+1;
Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
int f0,f1,f,n,i;
clrscr();
printf("ENTER THE VALUE FOR n \n");
scanf("%d",&n);
f0=0;
f1=1;
printf("FIBONACCI SEQUENCE FOR THE FIRST %d TERMS:\n",n);
i=0;
while(i<n)
{
printf("%d\t",f0);
f=f0+f1;
f0=f1;
f1=f;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 17
i=i+1;
}
}
Program Input:
ENTER THE VALUE FOR n
10
Program output:
FIBONACCI SEQUENCE FOR THE FIRST 10 TERMS:
0 1 1 2 3 5 8 13 21 34
Output screen:
Fig.1.2
Aim:
Implementation of c program to print a prime numbers up to 1 to n
Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3,5,7,………;
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5
If not goto step 10
Step 5: initialize j=1
Step 6: if j<=i do the following. If no goto step 7
i)if i%j==0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop
Start
Read n
false I=1
I<=n
I++
false J = 1 J++
J<=i
false true
false
If
fact==2
If I % j ==
0
Output i true
Fact ++
stop
Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact,j;
clrscr();
printf("enter the number:");
Program Input:
Program output:
2 3 5
Output screen:
Fig.1.3
Viva Voice Questions
Aim:
Implementation of C program to calculate the sum. Of 1-x2/2!+ x4/4!- x6/6!+ x8/8!- x10/10!
Description:
Ex: Let x=2
Sum=1-22/2!+24/4!-26/6!+28/8!-210/10!
Algorithm:
Main program:
Step 1: start
Step 2: declare x,i,n,s=0,c
Step 3: read x value
Step 4: for i=0 , n=0; i<=10; i=i+2, n++ goto step 5
Step 5: s=s+(pow(-1,n)*pow(x,i)/fact(i))
Step 6: print s value
Step 7: stop
Sub program: fact( x)
Step 1: while x!=0 goto Step 2
Step 2: y=y+x; x—
Step 3: return y
Step 4: return to main program
#include<stdio.h>
#include<math.h>
long fact(int);
void main()
{
int x,i,n;
float s=0,c;
clrscr();
printf("\n enter the value of x\t");
scanf("%d",&x);
/*perform the looping operation*/
for(i=0,n=0;i<=10;i=i+2,n++)
s=s+(pow(-1,n)*pow(x,i)/fact(i));
printf("\n the result is %f",s);
getch();
}
/* calling sub program*/
long fact(int x)
{
long int y=1;
while(x!=0)
{
y=y*x;
x--;
}
Program Input:
Program Output:
The result is 0.540302
Output Screen:
Fig.2.1
Aim:
Implementation of C program to find the roots of a quadratic equation.
Description:
Algorithm:
Step 1: Start
Step 2: Read a,b,c
Step 3: calculate disc = b*b-4*a*c
Step 4: if(disc>0)
Begin
Step 5: root1=(-b+sqrt(disc))/(2*a)
Step 6: root2=(-b-sqrt(disc))/(2*a)
Step 7: Print “Root1” , “Root2”
End
Step 8: else if(disc=0)
Begin
Step 9: root1=-b/(2*a)
Step 10: root2=root1;
Step 11: Print “Root1” , “Root2”
End
Step 12: else
Step 13: Print Roots are imaginary
Step 14: Stop
Program Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int a,b,c;
float disc,root1,root2;
float img,real;
printf("ENTER VALUES FOR a,b,c:\n");
if(disc>0)
{ printf("THE ROOTS ARE REAL & UNEQUAL:\n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("Root1=%f\n",root1);
printf("Root2=%f\n",root2);
}
else if(disc==0)
{
printf("THE ROOTS ARE REAL AND EQUAL:\n");
root1=-b/(2*a);
root2=root1;
printf("Root1=%f\n",root1);
printf("Root2=%f\n",root2);
}
else
{ printf("THE ROOTS ARE IMAGINARY:\n");
disc=-disc;
img=(float)disc/2*a;
real=(float)-b/2*a;
if (img>0)
{ printf("Root1=%f + i%f\n",real,img);
printf("Root2=%f - i%f\n",real,img);
}
else
{ img=-img;
printf("Root1=%f + i%f\n",real,img);
printf("Root2=%f - i%f\n",real,img);
}
}
return 0;
}
Program Input:
1 4 4
Program Output:
Output Screen:
Fig.2.2
33 a)The
a)The total
total distance
distance traveled
traveled by by vehicle
vehicle inin ‘t’‘t’seconds
seconds isis given
given by
by
2
distance=ut+1/2at where ‘u’ and ‘a’ are the initial velocity(m/sec) and
distance=ut+1/2at2 where ‘u’ and ‘a’ are the initial velocity(m/sec) and
acceleration(m/sec2).2).Write
WriteCCprogram
programtotofind findthe thedistance
distancetraveled
traveledatat
acceleration(m/sec
regular intervals of time given the values of ‘u’ and ‘a’. The program
regular intervals of time given the values of ‘u’ and ‘a’. The program
shouldprovide
providethetheflexibility
flexibilitytotothe
theuser
usertotoselect
selecthis hisown
owntimetimeintervals
intervals
should
and repeat the calculations for different values of ‘u’ and ‘a’.
and repeat the calculations for different values of ‘u’ and ‘a’.
Aim:
Implementation of C program to calculate s=u*t+1/2*a*t2
Recommended Hardware / Software Requirements:
Description:
The inputs like u (initial velocity), a (acceleration) and t (time) will be supplied by the
user and these will be substituted in the equation to find s=u*t+1/2*a*t2
Algorithm:
Step 1: Start
Step 2: read a,u, t, t1, t2
Step 3: for i is t1, i less than or equal to t2 and i=i+t
Begin
Step 4: calculate s = u*i+1/2*a*i2
Step 5: Print i,s
End
Step6: Stop
Read a,u,
t, t1, t2
i=0 i<=n F
i++
T
S=u*i+1/2*a*i2
Print i, s
Stop
Program Code:
#include<stdio.h>
#include<math.h>
void main()
{
int a,u,t,t1,t2,i;
float s;
clrscr();
printf("ENTER THE VALUES OF a,u,t,t1,t2:");
scanf("%d%d%d%d%d",&a,&u,&t,&t1,&t2);
for(i=t1;i<=t2;i=i+t) // performing the looping operation for time intervals
{
s=(u*i)+(0.5*a*i*i); // calculate the total distance
printf("\n\nthe distance travelled in %d seconds is %f ",i,s);
}
getch();
}
Program Input:
ENTER THE VALUES OF a, u, t, t1, t2:
1 2 3 1 5
Program Output:
Output Screen:
33b)b)Write
WriteaaCCprogram
program whichtakes
takestwo
twointeger
integeroperands
operandsand
andone
one
GNIT/CSE/LAB MANUALS/ CPwhich
MASTER MANUAL Page 31
operator from the user, performs the operation and then prints the
operator from the user, performs the operation and then prints the
result.(Considerthe
theoperators
operators+,-,*,/,%
+,-,*,/,%and
anduse
useSwitch
SwitchStatement.)
Statement.)
result.(Consider
Aim:
To perform arithmetic operations using switch statement.
Description:
The user will supply the two operand values to perform all arithmetic operations like
+,-,*,/,% by using switch statement.
Algorithm:
case 2:
Begin
Calculate c = a-b
Print “c”
break;
End
case 3:
Begin
Calculate c = a*b
Print “c”
break;
End
Flowchart:
Start
Read
a,b,ch
switch(ch)
Print c
Stop
case 4: c=a/b;
printf("The division of %d and %d is..%d\n",a,b,c);
break;
case 5: c=a%b;
printf("The modulus of %d and %d is..%d\n",a,b,c);
break;
case 6:exit(0);
default: printf("INVALID CHOICE\n");
}
}
getch();
Program Input:
20 16
Program Output:
MENU OPTIONS
***************
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit
ENTER UR CHOICE 1
The addition of 20 and 16 is..36
ENTER UR CHOICE 2
The subtraction of 20 and 16 is..4
ENTER UR CHOICE 3
The multiplication of 20 and 16 is..320
ENTER UR CHOICE 4
The division of 20 and 16 is..1
ENTER UR CHOICE 5
The modulus of 20 and 16 is..4
ENTER UR CHOICE 6
Fig.3.2
1. What is a pointer?
2. What is a structure?
3. What are the differences between structures and arrays?
4. What is the use of &operator in scanf statement
5. What is the use of %d, %f, %c in printf statement
6. What are the arguments of main function
Aim:
Implementation of C program to find the factorial of a given number using non-recursive
function.
Description:
The user will supply an integer value and for that value need to calculate the factorial
without using recursion.
Let value=4
4!=4*3*2*1=24
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Call fact(n) goto step 6
Step 4: Store result in “f”
Step 5: Print “f” goto step 10
Step 6: Begin //sub program
Initialize f ← 1
Step 7: for i is 1 to n by step 2
Step 8: Calculate f = f*i
Step 9: return “f”
End
Step 10: Stop
Start
Read n
f = fact(n)
f=1
Print
“f”
For i is 1 to n
by
Step 1
FALSE
Stop TRUE
f = f*i
Program Code:
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n,i,f;
clrscr();
printf("ENTER A VALUE FOR n:\n");
scanf("%d",&n);
f=fact(n);
printf("THE FACTORIAL OF A GIVEN NO IS..%d",f);
getch();
}
Program Output:
Output Screen:
Fig.4.1
Viva Voice Questions
Aim:
Implementation of C program to find the factorial of a given number using recursive
function.
Description:
The user will supply an integer value and for that value need to calculate the factorial by
using recursion.
Let value=4
4!=4*3*2*1=24
Algorithm:
Main program
Step 1: start
Step 2: read n
Step 3: call sub program as f=fact(n)
Step 4: print f value
Step 5: stop
Sub program:
Step 1: initialize the f
Step 2: if n= = 0 or n == 1 return 1 to main program if not goto step 3
Step 3: return n*fact(n-1) to main program
Start
Fact ()
Read n
False
If n=0 || n=1
Call subprogram
F = fact(n) True
Return
n*fact(n-1)
Print f
Return n to
main program
Stop
Program code:
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n,res;
clrscr();
printf("ENETR A NUMBER:\n");
scanf("%d",&n);
res=fact(n);
printf("THE FACTORIAL OF A GIVEN NUMBER IS..%d",res);
getch();
}
Program Output:
THE FACTORIAL OF A GIVEN NUMBER IS ..120
Output Screen:
Fig.4.2
Viva Voice Questions
Aim:
Implementation of C program to find the Gcd of two given integers by using the
recursive function
Description:
GCD (Greatest Common Divisor) of two numbers is a largest positive numbers which
can divide both numbers without any remainder. For example GCD of two numbers 4 and 8 is 2
since 2 is the largest positive number which can dived 4 as well as 8 without a remainder.
Algorithm:
Main program:
Step 1: start
Step 2: read a,b
Step 3: call the sub program GCD(a,b) for print the value
Step 4: stop
Sub program:
GCD(n,m)
Main Program:
Start
Read a,b
Print gcdvalue
Stop
Program Code:
#include<stdio.h>
#include<conio.h>
int gcdrecursive(int m,int n)
{
if(n>m)
return gcdrecursive(n,m);
if(n==0)
return m;
else
return gcdrecursive(n,m%n); // return to the main program
}
void main()
{
int a,b,igcd;
clrscr();
printf("enter the two numbers whose gcd is to be found:");
scanf("%d%d",&a,&b);
printf("GCD of a,b is %d",gcdrecursive(a,b)); // return to the sub program
getch();
}
Program Input:
Enter the two numbers whose gcd is to be found: 5 25
Pgrogram Output:
Output Screen:
Fig.4.3
1.what is gcd
register variables?
Aim:
Implementation of C program to find the GCD of two given integers by using the non
recursive function
Description:
GCD means Greatest Common Divisor. i.e the highest number which divides the given
number
Ex: GCD(12,24) is 12
Formula: GCD= product of numbers/ LCM of numbers
Algorithm:
Step 1: start
Step 2: read a,b
Step 3: call sub program g=GCD(a,b)
Step 4: print the g value
Step 5: stop
Sub Program:
Program Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int gcdnonrecursive(int m,int n)
{
int remainder;
remainder=m-(m/n*n);
if(remainder==0)
return n;
else
gcdnonrecursive(n,remainder);
}
void main()
{
int a,b,igcd;
clrscr();
printf("enter the two numbers whose gcd is to be found:");
scanf("%d%d",&a,&b);
printf("GCD of %d",gcdnonrecursive(a,b));
getch();
}
Program Output:
GCD of a,b is : 5
Output Screen:
Fig.4.4
Viva Voice Questions
1.what is gcd
register variables?
WEEK 5:
5.5. a)a)Write
WriteaaCCprogram
programtotofind findboth
boththe
thelargest
largestand
andsmallest
smallest
numberininaalist
listofofintegers.
integers.
number
Aim:
Implementation of C program to find the largest and smallest number in a list of integers.
Description:
The user will supply the list of integers among them largest and smallest number must be
find. For example the list is 2,4,6,8,12
Smallest number=2 Largest number=12
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=0
Step 4: if i<n do as follows. If not goto step 5
Read a[i]
Increment i
Goto step 4
Step 5: small=a[0], large=a[0]
Step 6: initialize i=0
Step 7: if i<n do as follows. If
not goto step 8
If a[i]<small
Assign small=a[i]
If a[i]>large
Flowchart:
Program Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,small,large;
clrscr();
printf("Enter The Array Size:");
scanf("%d",&n);
printf("ENTER ELEMENTS OF ARRAY");
for(i=0;i<n;i++) // read the elements of an array
scanf("%d",&a[i]);
small=a[0];
large=a[0];
Program Output:
largest value is : 10
smallest value is : 1
Output Screen:
Fig.5.1
Viva Voice Questions
5.5.b)i)
b)i)Write
WriteaaCCprogram
programtotoperform
performaddition
additionofoftwo
twomatrices.
matrices.
Aim:
Implementation of C program to perform addition of two matrices.
Description:
The sum A+B of two m-by-n matrices A and B is calculated entrywise:
Algorithm:
Step 1: Start
Step2: for i is 0 to 2 by step 1
for j is 0 to 2 by step 1
Step 3: Read a[i][j],b[i][j]
Step 4: goto step 2
Step 5: calculate c[i][j]=a[i][j]+b[i][j]
Step 6: goto step 2
Step 7: Print c[i][j]
Step 8: Stop
Start
For F
i=0;i<3;i++
For T
j=0;j<3;j++
Read a[i][j], b[i][j]
For
i=0;i<3;i++
For F
T
j=0;j<3;j++
c[i][j]=a[i][j]+b[i][j]
For
i=0;i<3;i++
For F
T
j=0;j<3;j++
Print c[i][j] Stop
Program Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("ENTER A MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf(" After addition of two matrices :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Program Input:
ENTER a MATRIX
1 2 3
4 5 6
7 8 9
ENTER b MATRIX
1 1 1
1 1 1
1 1 1
Program Output:
Fig.5.2
Aim:
Implementation of C program to perform multiplication of two matrices.
Description:
Algorithm:
Step 1: Start
Step21: for i is 0 to 2 by step 1
for j is 0 to 2 by step 1
Step 3: Read a[i][j],b[i][j]
Step 4: goto step 2
Step 5: calculate c[i][j]=a[i][j]+b[i][j]
Step 6: goto step 2
Step 7: Print c[i][j]
Step 8: Stop
Program Input:
ENTER a MATRIX
1 2 3
4 5 6
7 8 9
ENTER b MATRIX
1 1 1
1 1 1
1 1 1
Program Output:
The addition of two matrices is..
2 3 4
5 6 7
8 9 10
Fig. 5.3
Description:
The user will supply two strings(main string and sub string) and also the position where
the second string will be inserted will be given by the user.
Ex: main string= comter substring=pu position to insert sub string=3
Result=computer
Flowchart :
Step 1: start
Step 2: read main string and sub string
Step 3: find the length of main string(r)
Step 4: find length of sub string(n)
Step 5: copy main string into sub string
Step 6: read the position to insert the sub string( p)
Step 7: copy sub string into main string from position p-1
Step 8: copy temporary string into main string from position p+n-1
Step 9: print the strings
Step 10: stop
Program Code:
#include<stdio.h>
#include<string.h>
main()
{
char a[3qq0],b[30],c[30];
int pos=0,i=0,l,la,lb,lc,j;
puts("Enter a string");
gets(a);
puts("Enter sub string");
gets(b);
puts("enter position for insertion");
scanf("%d",&pos);
la=strlen(a);
lb=strlen(b);
l=pos+lb;
lc=la+lb;
Program Input:
Enter First String:
Comer
Enter Second String:
put
Program Output:
Computer
Fig.6.1
Viva Voice Questions
Description:
The user will supply string and the position from where to start deletion and the number
of characters to be deleted.
Ex: string= computer position to start deletion=2 position to insert sub string=2
Result=couter
Algorithm:
Step 1: start
Step 2: read string
Step 3: find the length of the string
Step 4: read the value of number of characters to be deleted and positioned
Step 5: string copy part of string from position to end, and
(position + number of characters to end)
Step 6: stop
Program code:
#include<stdio.h>
#include<string.h>
main()
{
char a[30],c[30];
int pos=0,i=0,L,La,j,n;
puts("Enter a string");
gets(a);
puts("enter position for deletion");
scanf("%d",&pos);
puts("Enter number of characters to be deleted");
scanf("%d",&n);
La=strlen(a);
L=pos+n;
for(i=0;i<pos;i++)
{
c[i]=a[i];
}
Program Input:
Enter the string
Raviraju
Enter the position from where to delete:4
Enter the number of characters to be deleted 4
Program Output:
Ravi
Output Screen:
Fig.6.2
Viva Voice Questions
6.6.b)b)Write
WriteaaCCprogram
programtotodetermine
determineififthe
thegiven
givenstring
stringisispalindrome
palindromeorornot.
not.
Aim:
Implementation of C program to determine if the given string is palindrome or not.
Description :
Palindrome means string on reversal should be same as original
Ex: madam on reversal is also madam
Algorithm:
Step 1: start
Step 2: read string A
Step 3: copy string A into B
Step 4: reverse string B
Step 5: compare A &B
If A equals B to got step 6
Else goto step 7
Step 6:print given string A is pallindrom
Step 7:print given string is not pallindroma
Step 8:
stop
Flowchart:
Program Input:
Enter a string madam
Program Output:
palindrome
Output Screen:
3. What are bit fields? What is the use of bit fields in a Structure
declaration?
Aim:
Implementation of C program to display the position or index in the string S where the
string T begins, or - 1 if S doesn't contain T
Description:
The user will supply two strings one is main string and second is sub string to be
searched in main string and where the sub string is found that position is to be printed.
Ex: string= computer sub string to be found=puter
Sub string found at position=3
Algorithm:
Step 1: start
Step 2: read the string and then displayed
Step 3: read the string to be searched and then displayed
Step 4: searching the string T in string S and then perform the following steps
i. found=strstr(S,T)
ii. if found print the second string is found in the first string at the
position. If not goto step 5
Step 5: print the -1
Step 6: stop
Start
Display string
Found = strstr(s,t)
No if found Yes
Stop
Programcode:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
Program Output:
Second string is found in the first string at 2 position
Output Screen:
Fig.7.1
Viva Voice Questions
1.what is the difference between strcmp() and strcpy()
2. how to declare string using pointer
3.what is the default header file
4.is for loop is terminated with semicolon or not
5.what is the difference between strcat() and strlen()
Aim:
Implementation of C program to count the number of lines, words and characters in a given
list.
Description:
The user will supply some text where we need to find the number of lines in the text,
number of words and characters.
Ex: Input = ramu is good boy
Number of lines=1
Number of words=4
Number of characters=16
Algorithm:
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with newline char ‘\n’ to count no of lines
Step 4: Compare each character with tab char ‘\t\’ or space char ‘ ‘ to count no of words
Step 5: Compare first character with NULL char ‘\0’ to find the end of text
Step 6: No of characters = length of each line of text
Step 7: Print no of lines, no of words, no of chars
Step 8: Stop
Start
Initialize end=0,chars=0,words=0,lines=0
While
End==0
true
C=0
false
If (ctr=getchar())!=’\n’
True Line[c]=’\0’
Line[c++]=ctr
true If line[0]=’\0’
Words ++
Program Code:
#include <stdio.h>
void main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
printf("TYPE ANY TEXT.\n");
printf("GIVE ONE SPACE AFTER EACH WORD.\n");
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 74
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
}
Program Input:
Program Output:
NUMBER OF LINES=1
NUMBER OF WORDS=5
NUMBER OF CHARACTERS=18
Fig.7.2
Aim:
Implementation of C program to generate Pascal’s triangle.
Description:
A triangular array of numbers in which those at the ends of the rows are 1 and each of the
others is the sum of the nearest two numbers in the row above (the apex, 1, being at the top).
Ex: 1
1 1
1 2 1
Algorithm:
Step 1: Start
Step 2: Read r
Step 3: Initialize b=1, q=0
Step 4: while q<=r
Begin
Step 5: for(p=30-3*q;p>0;p--)
Step 6: for(x=0;x<=q;x++)
Begin
Step 7: if x==0 or q==0
Flowchart:
Program Code:
#include<stdio.h>
#include<conio.h>
void main()
{
for(x=0;x<=q;x++)
{
if(x==0||q==0)
b=1;
else
b=(b*(q-x+1)/x);
printf(" %d",b);
}
printf("\n");
q++;
}
getch();
}
Program Input:
Program Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Fig.8.1
Viva Voice Questions
Aim:
Implementation of C program to construct a pyramid of numbers
Description:
The user will supply the length of the pyramid then the numbers will be printed in
the pyramid form.
Ex: length=3
1
12
123
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: i:=0
Step 4: if(i<n) goto step 5
else goto step 15
Step 5: k=n
Step 6: if(k>i) goto step 7
else goto step 10
step 7:print blank
step 8:k:=k-1
step 9:goto step 6
step 10:j=1;
#include<stdio.h>
int main()
{
int i,n,j,k;
printf("Enter how many rows to be printed: ")
scanf(" %d",&n);
for(i=0;i<=n;i++)
{
for(k=n;k>i;k--)
printf(" ");
for(j=1;j<=i;j++)
{
printf("%2d",j);
}
printf("\n");
}
return 0;
}
Program Input:
Program Output:
1
12
123
1234
Fig.8.2
9.9. WriteaaCCprogram
programtotoread
readinintwo
twonumbers,
numbers,xxand
andn,n,and
andthen
thencompute
compute
Write
the sum of this geometric progression.
the sum of this geometric progression.
Aim:
Implementation of C program to compute the sum of geometric progression.
Description:
The user will supply two numbers, x and n, and then compute the sum of this geometric
progression: 1+x+x2+x3+………….+xn
Ex: if n is 3 and x is 5, then the program computes 1+5+25+125. Print x, n, the sum Perform
error checking. For example, the formula does not make sense for negative exponents – if n is
less than 0. Have your program print an error message if n<0, then go back and read in the next
pair of numbers of without computing the sum. Are any values of x also illegal? If so, test for
them too.
Algorithm:
Step 1: Start
Step 2: Declare sum,i,x,n variables
Step 3: Read x,n values
Step 4: if(n<=0 || x<=0) then go to step 5 else go to step 6
Step 5: Print Value is not valid
Step 6: Initialize Sum =1
Step 7: for(i=1;i<=n;i++) then go to step 8 else go to step 9
Step 8: sum=sum+pow(x,i);
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int sum,i,x,n;
clrscr();
printf("Enter the values for x and n:");
scanf("%d %d",&x,&n);
if(n<=0 || x<=0)
{
printf("Value is not valid\n");
}
else
{
sum=1;
for(i=1;i<=n;i++)
{
sum=sum+pow(x,i);
}
printf("Sum of series=%d\n",sum);
}
getch();
}
Program Input:
Fig.9
Aim:
To compute the 2’s complement of a binary number
Description:
To calculate the 2's complement of an integer, invert the binary equivalent of the number
by changing all of the ones to zeroes and all of the zeroes to ones and then add one.
Step 1: Start
Step 2: Declare numbin Char variable, len, x, and y Integer variables
Step 3: Read numbin
Step 4: len=strlen(numbin); x=len-1;
Step 5: while(numbin!=’1’) condition true go to step 6 else go to step 7
Step 6: if(numbin[x]!=’0’ && numbin[x]!=’1’) if condition true print not a binary number else
decrement x value then go to step 5
Step 7: x=x-1;
Step 8: while(x>=0) condition true goes step 9 else go to step
Step 9:if(numbin[x]==’0’) condition true go to step 10 else go to step 11
Step 10:numbin[x]=’1’ , decrement x value then go to step 8
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char numbin[50];
int len,x,y;
clrscr();
printf("enter binary digits\n");
scanf("%s",numbin);
len=strlen(numbin);
x=len-1;
while(numbin[x]!='1')
{
if(numbin[x]!='0'&&numbin[x]!='1')
{
puts("not a binary number");
}
x--;
}
x=x-1;
while(x>=0)
{
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 91
if(numbin[x]=='0')
numbin[x]='1';
else
numbin[x]='0';
x--;
}
printf("2's complement of given binary num is%s\n",numbin);
getch();
}
Program Input:
Enter the binary number1111
Program Output:
The 2's complement is 0001
Output Screen:
Fig.10.1
Aim:
Implementaion of C program to convert roman number to it’s decimal equivalent
Description:
The user will supply roman numeral and that is printed in its equivalent decimal numeral.
Ex: if roman numeral=IV, Its decimal numeral=4
Algorithm:
Step 1: Start
Step 2: Declare a, len, i, j, k Variables and read the roman numerical as string
Step 3: find length of roman numerical
Step 4: for(i=0;i<len;i++) to check each character in the string
i)if(char=I) then decimal=1
ii)if(char=V) then decimal=5
iii)if(char=X) then decimal=10
iv)if(char=L) then decimal=50
v)if(char=C) then decimal=100
vi)if(char=D) then decimal=500
vii)if(char=M) then decimal=1000
viii) otherwise invalid character
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 93
Step 5: repeat step 4 until the condition i<len stratifies else go to step 6.
Step 6: k=char[length-1]
Step 7: for(i=len-1;i>0;i--) to convert each roman to decimal equivalent
i) if(a[i]>a[i-1]) then k=k-a[i-1];
ii)else if(a[i]==a[i-1] || a[i]<a[i-1]) then k=k+a[i-1];
Step 8: Repeat step 7 until the condition false then go to step 9
Step 9: print decimal value
Step 10: Stop
FLOW CHART:
getch();
}
Program Input:
Enter the Roman Numeral:IV
Output Screen:
Fig.10.2
WEEK 11:
WriteaaCCprogram
programthatthatuses
usesfunctions
functionstotoperform
performthe
thefollowing
followingoperations:
operations:
Write
i)i)Reading
Readingaacomplex
complexnumber
number
ii) Writing a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iii) Addition of two complex numbers
iv)Multiplication
Multiplication ofoftwo
GNIT/CSE/LAB MANUALS/ twocomplex
complex
CP MASTERnumbers
MANUAL Page 97
iv) numbers
Aim:
Implementation of C program to perform arithmetic operations on complex numbers
Description:
Complex numbers of type a+ib
Addition: (a+ib)+(x+iy)=a+x+i(b+y)
Subtraction: (a+ib)-(x+iy)=a-x+i(b-y)
Multiplication: (a+ib)*(x+iy)= ax-by+i(ay+bx)
Algorithm:
void main()
{
complex c1,c2,c3;
printf("read first complex number c1\n");
c1=readdata(c1);
writedata(c1);
printf("read second complex number c2\n");
c2=readdata(c2);
writedata(c2);
c3=addcomplex(c1,c2);
puts("\nafter addition\n");
writedata(c3);
c3=mulcomplex(c1,c2);
puts("after multiplication\n");
writedata(c3);
getch();
}
complex readdata(complex c)
{
printf("enter real and imaginary values\n");
scanf("%d%d",&c.real,&c.img);
return c;
}
void writedata(complex c)
{
printf("%d+i%d",c.real,c.img);
}
complex addcomplex(complex c1,complex c2)
{
complex c3;
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
complex mulcomplex(complex c1,complex c2)
{
complex c3;
c3.real=(c1.real*c2.real)-(c1.img*c2.img);
c3.img=(c1.real*c2.img)+(c1.img*c2.real);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 102
return c3;
}
Program Input:
Read first complex number c1
Enter real and imaginary values 2 2
2+i2 read
Second complex number c2
Enter real and imaginary values 2 2
2+i2
Program Output:
After addition 4+i4
After multiplication 0+i8
Output Screen:
Fig.11
Viva Voice Questions
1.define structure. which keyword is used to declare structure
2.declare and initialize structure with example.
3.what is the array of structure. why it is used
4.how memory is allocated for structure. what is the size of structure
5.what is the difference between structure and union
6.What is the structure within structure
WEEK 12:
12a)a)Write
WriteaaCCprogram
programtotocopy
copythe
thecontents
contentsofofone
onefile
filetotoanother.
another.
12
Description:
Program which copies contents of one file to another
Algorithm:
Step 1: Start
Step 2: read command line arguments
Step 3: check if no of arguments =3 or not. If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print source file can not be open
Step 6: open destination file in write mode
Step 7: if NULL pointer, then print destination file can not be open
Step 8 : read a character from source file and write to destination file until EOF
Step 9: Close source file and destination file
Step 10: Stop
Program Input:
a.txt
Program Output:
Aim:
Implementation of C program to reverse the first n characters in a file
Description:
Contents in the supplied source file will be written in reverse order to the output file
Algorithm:
Step 1: Start
Step 2: read the command line arguments
Step 3: check if arguments=3 or not
If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print file can not be open
Step 6: Store no of chars to reverse in k
K= *argv[2]-48
Step 7: read the item from file stream using fread
Step 8: Store chars from last position to initial position in another string(temp)
Step 9: print the temp string
Step 10: Stop
4.DEFINE STREAMS
5.WHAT ARE THE STANDARD I/O FUNCTIONS OF FILE
Aim:
Implementation of C program to display the contents of a file.
Description:
The user will supply the source file name as input and the contents in the source file will
be displayed as output.
Algorithm:
Step 1: Start
Step 2: Declare File pointer fp and character variable ch;
Step 3: Open a file in read mode and assign to fp pointer variable
Step 4: Check the condition if(fp==NULL) if true print file doesn’t exist else go to step 5
Step 5: Check the condition while(ch=getc(fp))!=EOF) if the condition true go to step 6 until the
condition false. If condition false then go to step step7
Step 6: Print ch value and go to step 5
Step 7: Close the fp file.
Step 8: Stop
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("frev.c","r");
if(fp==NULL)
printf("File Doesnot Exist");
else
printf("The File Contents are:\n");
printf("____________________\n");
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
}
Program Input:
Enter the file name :sample.txt
Program Output:
this is my first program
1. how would you use the functions fseek(), freed(), fwrite() and ftell()?
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 112
13. b) Write a C program to merge two files into a third file (i.e., the contents of
13.
2. b) Write a C program to merge two files into a third file (i.e., the contents of
the first file followed by those of the second are put in the third).
the first file followed by those of the second are put in the third).
Aim:
Implementation of C program to merge two files into a third file
Description:
The user will create three text files and enter contents in two files, the program will
merges the contents of these two files in to third file.
Algorithm:
Step 1: Start
Step 2: Declare File pointers fp1, fp2, fp3 and character variable ch;
Step 3: Open a file in read mode and assign to fp1 pointer variable
Step 4: Open a file in write mode and assign to fp3 pointer variable
Step 5: Check the condition while(ch=getc(fp1))!=EOF) if the condition true go to step 6
until the condition false. If condition false then go to step step7
Step 6: Write individual character of a file into fp3 and print the character value and then go
to step 5
Step 7: Close all opened files.
Step 8: Open a file in read mode and assign to fp2 pointer variable
Step 9: Open a file in append mode and assign to fp3 pointer variable
Step 10: Check the condition while(ch=getc(fp1))!=EOF) if the condition true go to step 11
until the condition false. If condition false then go to step step12
Step 11: Write individual character of a file into fp2, next write individual characters to fp3
and print the character value and then go to step 10
Step 12: Close all opened files.
Step 13: Stop.
Program Output:
The program creates the third file r.txt and its contents are the contents of two source files after
merging.
Aim:
implementation of C program to use non recursive function to search for a Key value in
a given list of integers using Linear search.
Description:
Linear search or sequential search is a process of searching elements in a array in linear
fashion. Compare key with each element in the array . if element if found its index is returned
else -1 is returned to indicate that element is not found
Algorithm:
Step 1. Start
Step 2. Read the value of n
Step 3. for i=1 to n increment in steps of 1
Read the value of ith element into array
Step 4. Read the element(b) to be searched
Step 5. c<--lsearch(a,n,b)
Step 6. if c equal to 0 goto step 7 otherwise goto step 8
Step 7. print unsuccessful search
Step 8. print successful search
Step 9. Stop
lsearch(k[],n,m)
step 1. start
step 2. for i=1 to n increment in steps of 1
step 3. if m equal to k[i] goto step 4 otherwise goto step 2
step 4. return i
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 116
Flowchart:
Linear search()
Program Code:
#include<stdio.h>
void lsearch(int list[],int n,int key);
void main()
{
int n,i,key,list[25];
clrscr();
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)
scanf("%d",&list[i]);
printf("enter key to search");
scanf("%d",&key);
lsearch(list,n,key);
getch();
}
void lsearch(int list[],int n,int key)
{
int i,pos=-1;
for(i=0;i<n;i++)
Program Input:
Enter no of elements 5
Enter 5 elements 1 5 3 4 2
Enter key to search 3
Program Output:
Element found at index 2
Output Screen:
Fig. 14.1
14b)b)Write
14 WriteaaCCprogram
programthat
thatuses
usesnon
nonrecursive
recursivefunction
functiontotosearch
searchfor
foraa
Keyvalue
Key valueininaagiven
givensorted
sortedlist
listofofintegers
integersusing
usingBinary
BinarySearch
Search
Description:
For binary search to work, the item in the list must be in assorted order. The approach
employed in the binary search is divid and conquer. If the list to be sorted for a specific item is
not sorted, binary search fails.The given list is divided into two halves and searched in the
halves basing on key value. If key value is less than middle element then searching is done in
first half of the list else next half is searched
Algorithm:
Step 1: Start
Step2: Declare a [10], i, key, n; variables
Step 3: Read the size of the array list, elements of the list, and the key element to search
Step4: Call Sub Function binarysearch (a, n, key);
Step 5: Stop
Flowchart:
Program Code:
#include <stdio.h>
Program Input:
Enter number of elements 3
Enter 3 integers 2 6 7
Enter value to find 6
Program Output:
6 found at location 2
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 122
Output Screen:
Fig. 14.2
Week 15:
15a)a)Write
15 WriteaaCCprogram
programthat thatimplements
implementsthe
theSelection
Selectionsort
sortmethod
methodtoto
sortaagiven
sort givenarray
arrayofofintegers
integersininascending
ascendingorder.
order.
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 123
Aim:
Implementation of C program to implement the Selection sort method to sort a given
array of integers.
Description:
This is the simplest method of sorting. In this method, to sort the data in
ascending order, the 0th element is compared with all other eements. If the 0 th element is found
to be greater than the compared element then they are interchanged.
Algorithm:
step 1) Start
step 2) Initiliaze the variables I,j,temp and arr[]
step 3) Read the loop and check the condition. If the condition is true
print the array elements and increment the I value. Else goto step 4
step 4) Read the loop and check the condition. If the condition true
then goto next loop.
step 5) Read the loop and check the condition. If the condition true
then goto if condition
step 6) If the condition if(arr[i]>arr[j]) is true then do the following steps
i) temp=arr[i]
ii) arr[i]=arr[j]
iii) arr[j]=temp
step 7) increment the j value
step 8) perform the loop operation for the displaying the sorted elements.
step 9) print the sorted elements
step 10) stop
Program Input:
Enter no of elements 4
Enter 4 elements 6 3 8 1
Program Output:
Fig.15.1
Aim:
Implementation of c program to Bubble sort method to sort a given list of names in
ascending order.
Description:
Bubble sort is the simplest and oldest sorting technique. This method takes two elements
at a time. It compare these two elements. If first elements is less than second one, they are left
undistrurbed. If the first element is greater then second one then they are swapped. The
procedure continues with the next two elements goes and ends when all the elements are sorted.
But bubble sort is an inefficient algorithm. The order of bubble sort algorithm is O(n2)
Algorithm:
Bubble Sort:
step 1. start
step 2. read the value of n
step 3. for i= 1 to n increment in steps of 1
Read the value of ith String into array
step 4. call function to sort (bubble_sort(a,n))
step 5. for i= 1 to n increment in steps of 1
print the value of ith String in the array
step 6. stop
#include<stdio.h>
#include<string.h>
#include<conio.h>
void bubble_sort(char list[ ][30],int n);
int main()
{
int n,i;
char list[25][30];
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)
scanf("%s",&list[i]);
bubble_sort (list,n);
printf("List of names after sorting\n");
for(i=0;i<n;i++)
printf("%s\n",list[i]);
getch();
return 0;
}
void bubble_sort (char list[ ][30],int n)
{
char temp[30];
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(strcmp(list[j],list[j+1])>0)
{
strcpy(temp,list[j]);
strcpy(list[j],list[j+1]);
strcpy(list[j+1],temp);
}
}
Program Input:
Enter no of elements 4
Enter 4 elements 1 5 3 7
Program output:
List of names after sorting 1 3 5 7
Fig.15.2
Viva Voice Questions
Aim:
Implementation of c program to perform Various operations on singly linked list.
Description:
we have to create a single linked list, insert the elements into that list ,delete the some
elements from that list and then perform the sorting operation and traversal operation on that
created linkedlist
Algorithm :
Step 1: Start
Step 2: Declare a structure named linked-list
Step 3: Declare the pointers next, first, fresh, ptr
Step 4: Print main menu
Step 5: Read choice
Step 6: Switch(choice)
Step 7: If(choice==1)
7.1 Assign fresh=malloc(size of (node))
7.2 Read the element fresh->data
7.3 Read the choice where to insert
Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode * lptr;
Program Input/Output:
Enter choice
1.insert end
2.insert front
3.insert after
4.insert before
5.del end
6.del front
7.display
8.node count
9.clear screen
10.exit
Enter ur choice:1
Enter value into new node:3
Element inserted at end
Enter choice
1.insert end
2.insert front
3.insert after
4.insert before
5.del end
6.del front
7.display
8.node count
9.clear screen
10.exit
Enter ur choice:2
Enter value into new node:4
Element inserted at front
Enter choice
1.insert end
2.insert front
3.insert after
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 139
4.insert before
5.del end
6.del front
7.display
8.node count
9.clear screen
10.exit
Enter ur choice:7
4->3
Enter choice
1.insert end
2.insert front
3.insert
4.insert before
5.del end
6.del front
7.display
8.node count
9.clear screen
10.exit
Enter ur choice:10
Output Screen:
Fig.16
Viva Voice Questions
1. Explain concept of linked list
2. What are the types of linked list
3. How to declare single linked list
4. What is self referential structure.
5. What is the use of typedef
6. How to insert and delete the elements from singly linkedList
17 .Write a C program that implements stack (its operations) using a singly linked
list to display a given list of integers in reverse order. Ex. input: 10 23 4 6 output:
6 4 23 10
Aim:
Implementation Of C Program To implement stack (its operations) using a singly linked
list to display a given list of integers in reverse order.
Description:
Stack operations are implemented by using the arrays. Here they stack operation are
push and pop. Push operation is used to insert the elements into a stack and pop operation is used
to remove the elements in to a stack
Algorithm:
Algorithm For Push Operation
Function Push(s,top,x)
Step 1: [Check for stack overflow]
If top>=n
Then printf(“stack overflow”)
Return
Step 2: [Increment Top]
Top<-top+1
Step 3: [ Insert element]
S[top]<-x
Step 4:[finished]
Return
Function POP(s,top)
Step 1: [Check for stack underflow]
If top=0
Then printf(“stack underflow”)
Exit
Step 2: [Decrement Top]
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 141
Top<-top-1
Step 3: [Return former top element of stack]
Return(S[top+1])
Step 4:[finished]
Return
Flowchart:
Output Screen:
Fig. 17
Aim:
To implement Queue (its operations) using a singly linked list to display a given list of
integers in the same order
Description:
we have to implement the Queue operation by using the arrays. Here they Queue
operation are push and pop. Insert operation is used to insert the elements into a Queue and
Delete operation is used to remove the elements in to a Queue.
Ex. Input: 10 23 4 6 output: 10 23 4 6
Algorithm:
Flowchart:
qptr createnode()
{
qptr node;
node=(qptr)malloc(sizeof(struct queue));
return node;
}
qptr insert_q(qptr r,qptr *f,int x)
{
qptr p,temp;
p=createnode();
p->data=x;
p->next=NULL;
if(*f==NULL)
{ r=p;
*f=r;
}
else
{
while(r->next!=NULL)
r=r->next;
r->next=p;
}
return r;
}
void delete_q(qptr *front)
{
qptr temp;
temp=*front;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 149
*front=(*front)->next;
printf ("\n\n%d is deleted",temp->data);
free(temp);
}
void display(qptr front)
{
qptr temp;
temp=front;
while(temp!=NULL)
{
printf("\t%d\n",temp->data);
temp=temp->next;
}
}
void main()
{
qptr rear,front;
int choice,item;
clrscr();
front=rear=NULL;
while(1)
{
printf("\n-----------------------------\n");
printf("|MENU FOR OPERATIONS ON QUEUE|");
printf("\n-----------------------------\n");
printf("1.INSERT \n 2.DELETE\n3.DISPLAY\n4.EXIT\n Enter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n enter element to insert");
scanf("%d",&item);
rear=insert_q(rear,&front,item);
printf("\n\nelement %d is inserted succesfully" ,item);
break;
case 2: if(front==NULL)
printf("\n\nqueue is empty");
else
delete_q(&front);
break;
case 3: if(front==NULL)
printf("\n\nqueue is empty");
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 150
else
display(front);
break;
case 4: exit(0);
default:printf("Invalid choice...Try Again\n");
break;
}
}
}
Program Input/Ouput:
---------------------------------------------
| MENU FOR OPERATIONS ON QUEUE |
---------------------------------------------
1.INSERT
2.DELETE
3.DISPLAY
4.Exit
Enter your choice:1
Ente element to insert 2
Element 2 is inserted successfully
---------------------------------------------
| MENU FOR OPERATIONS ON QUEUE |
---------------------------------------------
1.INSERT
2.DELETE
3.DISPLAY
4.Exit
Enter your choice:3
2
---------------------------------------------
| MENU FOR OPERATIONS ON QUEUE |
---------------------------------------------
1.INSERT
2.DELETE
3.DISPLAY
4.Exit
Enter your choice:2
2 is deleted
---------------------------------------------
| MENU FOR OPERATIONS ON QUEUE |
---------------------------------------------
1.INSERT
Fig.18
Aim:
C program to implement the linear regression algorithm.
Algorithm :
Step1: Start
Step2: input float a[20],b[20],dx[20],dy[20]
float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0
float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0
char type_coff[7]
int n=0,i=0
Step3: enter the value of n
Step4: enter the values of x and y
Step5: for(i=0;i<n;i++)
read a[i],b[i]
mean_x=mean(a,n)
mean_y=mean(b,n)
deviation(a,mean_x,n,dx,&sx)
deviation(b,mean_y,n,dy,&sy)
Step6: for(i=0;i<n;i++)
sum_xy=sum_xy+dx[i]*dy[i];
corr_coff=sum_xy/(n*sx*sy);
Step7: enter the type of regression coefficient as 'x on y' or
'y on x':
gets(type_coff)
if(strcmp(type_coff,"x on y")==1)
reg_coff_xy=corr_coff*(sx/sy)
print ‘The value of linear regression coefficient is %f’ ,reg_coff_xy
else if(strcmp(type_coff,"y on x")==1)
reg_coff_yx=corr_coff*(sy/sx)
print ‘The value of linear regression coefficient is %f’,reg_coff_yx
else
print ’enter the correct type of regression coefficient’
Step8: float sum=0, i=0
for(i=0;i<n;i++)
sum=sum+a[i]
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 153
sum=sum/n
return (sum)
Step9: void deviation(float *a, float mean, int n, float *d, float *s)
float sum=0,t=0
int i=0
for(i=0;i<n;i++)
d[i]=a[i]-mean
t=d[i]*d[i]
sum=sum+t
sum=sum/n
*s=sqrt(sum)
Step10: Stop
Program code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
void main()
{
float a[20],b[20],dx[20],dy[20];
float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0;
float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0;
char type_coff[7];
int n=0,i=0;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter the values of x and y:\n");
for(i=0;i<n;i++)
scanf("%f%f",&a[i],&b[i]);
mean_x=mean(a,n);
mean_y=mean(b,n);
deviation(a,mean_x,n,dx,&sx);
deviation(b,mean_y,n,dy,&sy);
for(i=0;i<n;i++)
sum_xy=sum_xy+dx[i]*dy[i];
corr_coff=sum_xy/(n*sx*sy);
printf("Enter the type of regression coefficient as 'x on y' or 'y on x': ");
fflush(stdin);
gets(type_coff);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 154
if(strcmp(type_coff,"x on y")==1)
{
reg_coff_xy=corr_coff*(sx/sy);
printf("\nThe value of linear regression coefficient is %f",reg_coff_xy);
}
Program Input/Output:
Enter the value of n: 2
Enter the values of x and y:
2
3
4
5
Enter the type of regression coefficient as 'x on y' or 'y on x': x on y
The value of linear regression coefficient is 1
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 155
Enter the value of n: 2
Enter the values of x and y:
2
3
8
6
Enter the type of regression coefficient as 'x on y' or 'y on x': x
Output Screen:
Fig:19
Aim:
To implement the polynomial regression algorithm
Decription:
polynomial regression is a form of in which the relationship between the independent
variable x and the dependent variable y is modelled as an nth degree .
Ex: x2+x+1
Algorithm:
Sep 1: Strart
Step 2: Read n
Step 3: Initialize sumx = 0, sumxsq = 0, sumy = 0, sumxy = 0, sumx
sumx4 = 0, sumxsq =0
Step 4: Intialize i=0
Step 5: Repeat steps 5 to 7 until i<n
Step 6: Read x,y
Step 7: Sumx = sumx + x
Sumxsq =sumxsq + pow(x,2)
Sumx3 = sumx3 + pow(x,3)
Sumx4 = sumx4 + pow(x,4)
Sumy = sumy + y
Sumxy = Sumxy + x*y
Sumxsqy = Sumxsqy + pow(x,2) *y
Step 8: Increment I by 1
Step 9: Assign
a[0][0] = n
a[0][1] = n
a[0][2] = n
a[0][3] = n
a[1][0] = n
a[1][1] = n
a[1][2] = n
a[1][3] = n
a[2][0] = n
a[2][1] = n
Program Code:
#include<stdio.h>
#include<math.h>
void main()
{
int n, I, j, k;
float sumx, sumxsq, sumy, sumxy, x, y;
float sumx3, sumx4, sumxsqy, a[20][20], u=0.0, b[20];
printf(“\n Enter the n value”);
scanf(“%d”, &n);
sumx = 0;
sumxsq = 0;
sumy = 0;
sumxy = 0;
sumx3 = 0;
sumx4 = 0;
sumxsqy = 0;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 158
for(i=0; i<n; i++)
{
scanf(“%f %f”, &x, &y);
sumx +=x;
sumxsq += pow(x,2);
sumx3 += pow(x,3);
sumx4 += pow(x,4);
sumy +=y;
sumxy += x * y;
sumxsqy += pow(x,2) *y;
}
a[0][0] = n;
a [0][1] = sumx;
a [0][2] = sumxsq;
a [0][3] = sumy;
a [1][0] = sumx;
a [1][1] = sumxsq;
a [1][2] = sumx3;
a [1][3] = sumxy;
a [2][0] = sumxsq;
a [2][1] = sumx3;
a [2][2] = sumx4;
a [2][3] = sumxsqy;
for(i=0; i<3; i++)
{
for(j=0; j<=3; j++)
printf(“%10.2f”,a[i][j]);
printf(“\n”);
}
for(k=0; k<=2; k++)
{
for(i=0;i<=2;i++)
{
if(i!=k)
u=a[i][k]/a[k][k];
for(j = k; j<=3; j++)
a[i][j]=a[i][j] – u * a[k][j];
}
}
for(i=0;i<3;i++)
{
b[i] = a[i][3]/a[i][i];
printf(“\nx[%d] = %f”, I, b[i]);
}
printf(“\n”);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 159
printf(“y= %10.4fx +10.4 fx +%10.4f”,b[2],b[i],b[0]);
}
Program Input:
Enter the n value 10
-4 21
-3 12
-2 4
-1 1
02
17
2 15
3 30
4 45
5 67
Program Output:
10.00 5.00 85.00 204.00
5.00 85.00 125.00 513.00
85.00 125.00 1333.00 3193.00
X[0] = 2.030303
X[1] = 2.996970
X[2] = 1.984848
Y= 1.9848xsq + 2.9979x + 2.0303
Output Screen:
Fig.20
Viva Voice Questions
1.what is the polynomial regression formula
2.define minimal spanning tree
3.what are various traversals in a tree
4.what are the advantages and disadvantages of stack
5.what do you mean by sorting and searching
6.what are the unary operators
Aim:
To implement the Lagrange interpolation.
Description:
It is the polynomial interpolation. It is the process of passing a polynomial of degree n-1
through n points.
Algorithm:
Step 1: Read n
Step 2: for i=1 to n by 1 do
Read xi,yi
End for
Step 3: read xp
Step 4: for i=1 to n-1 by 1 do
Set p=1;
For j=1 to n-1 by 1 do
If i<>j then
Set P=P*(xp-xj)/xi-xj)
End for
Set sum = sum + yi*P
End for
Program Code:
#include<stdio.h>
#include<conio.h>
#define MaxN 90
void main()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator, denominator, x, y=0;
int i, j, n;
clrscr();
printf("Enter the value of n: \n");
scanf("%d", &n);
printf("Enter the values of x and y: \n");
Program output:
Enter the value of n:
3
Enter the values of X and Y:
1 2
2 3
3 4
4 5
Enter the value of x at which value of y is to be calculated:2
Program Output:
When x=2.0 y=3.0
Output screen:
Aim:
To implement the Newton- Gregory forward interpolation.
Description:
Very often it so happens in practice that the given data set (xi,yi), i=0,1,..,n correspond to a sequence
of equally spaced points. Here we can assume that
Xi=x0+ih, i=0,1,2…n
Algorithm:
Step1: Start
Step2: input float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y,
p, h, diff_table[MaxN+1][Order_of_diff+1],int i,j,n,k
Step3: enter the value of n
Step4: enter the values of x and y
Step5: for(i=0; i<=n; i++)
read arr_x[i], arr_y[i]
enter the value of x at which value of y is to be calculated
Step6: read x
h=arr_x[1]-arr_x[0]
Step7: for(i=0; i<=n-1; i++)
/*Creating the difference table and calculating first order differences*/
diff_table[i][1]=arr_y[i+1]-arr_y[i]
Step8: /*Calculating higher order differences*/
for(j=2; j<=Order_of_diff; j++) for(i=0; i<=n-j; i++)
diff_table[i][j]=diff_table[i+1][j-1] - diff_table[i][j-1]
i=0
while(!(arr_x[i]>x)) /* Finding x0 */
i++
i--
p=(x-arr_x[i])/h
Program Code:
#include<stdio.h>
#include<conio.h>
#define MaxN 100
#define Order_of_diff 4
void main ()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y, p, h,
diff_table[MaxN+1][Order_of_diff+1];
int i,j,n,k;
clrscr();
printf("Enter the value of n \n");
scanf("%d",&n);
printf("Enter the values of x and y");
for(i=0; i<=n; i++)
scanf("%f%f", &arr_x[i], &arr_y[i]);
printf("Enter the value of x at which value of y is to be calculated");
scanf("%f", &x);
h=arr_x[1]-arr_x[0];
for(i=0; i<=n-1; i++)
diff_table[i][1]=arr_y[i+1]-arr_y[i];/*Creating the difference table and calculating first order
differences*/
for(j=2; j<=Order_of_diff; j++)/*Calculating higher order differences*/
for(i=0; i<=n-j; i++)
diff_table[i][j]=diff_table[i+1][j-1] - diff_table[i][j-1];
i=0;
while(!(arr_x[i]>x)) /* Finding x0 */
i++;
i--;
p=(x-arr_x[i])/h;
y=arr_y[i];
for (k=1; k<=Order_of_diff; k++)
{
numerator *=p-k+1;
denominator *=k;
y +=(numerator/denominator)*diff_table[i][k];
}
printf("When x=%6.1f, y=%6.2f\n",x, y);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 165
getch();}
Program Input/Output:
Output Screen:
Fig:22
Aim:
To implement Trapezoidal method.
Description:
The trapezoidal rule (also known as the trapezoid rule or trapezium rule) is a technique
for approximating the
Algorithm:
Step 1. Read x1, x2, e { x1 and x2 are the two end points of the
internal the allowed error in integral is e}
Step 2. h=x2-x1
Step 3. SI = (f(x1) + f(x2))/2;
Step 4. I = h-si
Step 5. i=1 Repeat
Step 6. x=x1 + h/2
Step 7. for J= 1 to I do
Step 8. SI= SI + f(x)
Step 9. x=x+h
Endfor
Step 10. i=21
Step 11. h=h/2
Step 12.i0=i1
Step 13. i1 = h.si
Step 14. until / I1-i0 / <=c./i1/
Step 15. Write I1,h,i
Step 16. Stop
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 167
Program Code:
#include<stdio.h>
#include<math.h>
main()
{
float h,a,b,n,x[20],y[20],sum=0,integral;
int i;
clrscr();
printf("enter the value ofa,b,n:");
scanf("%f %f %f",&a,&b,&n);
printf("enter the values of x:");
for(i=0;i<=(n-1);i++)
{
scanf("%f",&x[i]);
}
printf("\n enter the values of y:");
for(i=0;i<=(n-1);i++)
{
scanf("%f",&y[i]);
}
h=(b-a)/n;
x[0]=a;
for(i=1;i<=n-1;i++)
{
x[i]=x[i-1]+h;
sum=sum+2*y[i];
}s
um=sum+y[b];
integral=sum*(h/2);
printf("approximate integral value is: %f",integral);
getch();
}
Program Input:
Enter the values of a,b,n
123
Enter the values of x:
123
Enter the values of y:
123
Program output:
Approximate integral value is 2.166667
Fig:23
WEEK 24:
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 169
24.Write
WriteaaCCprogram
programtotoimplement
implementSimpson
Simpsonmethod.
method.
24.
Aim:
To implement Simpson method.
Description:
Simpson’s rule is a numerical method that approximates the value of a definite integral
by using quadratic polynomials.
Algorithm:
Step 1. Read x1,x2,e
Step 2. h=(x2-x1)/2
Step 3. i=2
Step 4. si=f(x1) + f(x2)
Step 5. s2=0
Step 6. s4=f(x1+h)
Step 7. I0=0
Step 8. In =(s+4s4). (h/3)
Repeat
Step 9. s2=s2+s4 {s2 stores already computed functional value and s4
the value computed in the new nitration }
Step 10. s4=0
Step 11. x=x1+h/2
Step 12. for j=1 to I do
Step 13. s4=s4+f(x)
Step 14. x=x+h
Step 15. h=h/2
Step 16. i=2i
Step 17. io=in
Step 18. in= (s1+2s2+4s4) . (h/3)
Step 19. until |In-Io|≤e. /in
Step 20. Write In,h,i
Step 21. STOP
Program Code:
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 170
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float h,a,b,n,x[20],y[20],sum=0,itgl;
int i;
clrscr();
printf("enter the values of a,b,n");
scanf("%f%f%f",&a,&b,&n);
printf("enter the values of x");
for(i=0;i<=n;i++)
{
scanf("%f",&x[i]);
}
printf("\n enter the values of y");
for(i=0;i<=n;i++)
{
scanf("%f",&y[i]);
}
h=(b-a)/n;
a=x[0];
b=x[n];
for(i=0;i<=(n-2);i++)
{
x[i]=x[i]+h;
if(i%2==0)
{
sum=sum+4*y[i];
}else
{
sum=sum+2*y[i];
}
}itgl=sum*(h/3);
printf("integral value%f",itgl);
getch();
}
Program Input:
Program Output:
Output Screen:
Fig:24
Algorithm:
Step1: Start
Step2: input st[100], st_top=-1,char in[100],post[100]
Step3: print ‘Enter the Infix Expression’
Step4: if(st_top==99)
print ’STACK is Full’
Step5: st[++st_top]=it
Step6: if(st_top==-1)
return(st[st_top--])
Step7: /*Function for converting an infix expression to a postfix expression. */
input int x=0,y=0,z,result=0,char a, c, post[100],char t
push_item('\0')
t=in[x]
while(t!='\0')
if(isalnum(t))
Step8: /*For checking whether the value in t is an alphabet or number. */
post[y]=t
y++
Step9: else if(t=='(')
push_item('(')
else if(t==')')
while(st[st_top]!='(')
c=pop_item()
post[y]=c
y++
c=pop_item()
else
while(st_ISP(st[st_top])>=st_ICP(t))
c=pop_item()
post[y]=c
y++
push_item(t)
x++
Program Code:
#include<stdio.h>
#include<conio.h>
int st[100];
int st_top=-1;
/*main function*/
void main()
{
char in[100],post[100];
clrscr();
printf("\n\tEnter the Infix Expression: ");
gets(in);
in_post(in);
getch();
}
/*end main*/
int pop_item()
{
int it;
if(st_top==-1)
{
getch();
}
return(st[st_top--]);
}
while(st_top!=-1)
{
c=pop_item();
post[y]=c;
y++;
}
printf("\n\tThe Postfix Expression is:");
for(z=0;z<y;z++)
printf("%c",post[z]);
printf("\n\nDo you want to evaluate the Result of Postfix Expression?(Y/N):");
scanf("%c",&a);
if(a=='y' || a=='Y')
{
result=cal(post);
printf("\n\n\tResult is: %d\n",result);
getch();
}
else if(a=='n' || a=='N')
{
exit(0);
}
}
Result is: 13
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 179
Output Screen:
Fig.8.1
Aim:
To Write a C program that uses functions to perform the following:
a) Create a doubly linked list of integers.
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
Algorithm:
Step1: Start
Step2: read number, linked-list *next, ch, node *head
Step3: create(node *p)
Step4: read count(node *p)
print node *p
Step5: create(head);
Step6: print head
Step7: print count(head)
Step8: print ‘enter1-insert,2-delete’
Step9: print list->next
Step10: if(list->next==null)
return 0
else
return(1+count(list->next))
Step11:node insert(node *head)
Step12:read y,x;
Step13:read x,key
Step14:if(head->number==key)
new=(node*)malloc(sizeof(node))
new->number=x
new->next=head;
Step16:if(list->next->number==key)
return(list)
else
if(list->next->next==null)
return(null)
else
find(list->next,key)
Step17:node *delete(node *head)
Step18:node *find(node *p, int a)
Step19:print’enter the num to be deleted’
Step20:read key
Step21:if(head->number==key)
p=head->next
free(head)
head=p
else
n1=find(head,key)
Step22:if(n1==null)
print’key not found’
else
p=n1->next->next
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 182
free(n1->next)
n1->next=p
return(head)
Step23: Stop
Program code:
#include "stdio.h"
#include "alloc.h"
DUBLL high,temp_node,low,last,pntr;
int flag=0;
DUBLL NodeAlloc();
DUBLL Search(int,int);
void CreateItem();
void AppendItem();
void PrintItem();
void DeleteItem();
DUBLL Search(int item,int flag);
DUBLL NodeAlloc();
void InsertItem();
void main(void)
{
int choice,Item;
high=NULL;
while(1)
{
clrscr();
printf("\n \t\t\t***** M A I N M E N U *****\n\n");
printf("\n 1: Create Linked List \n 2: Append a Node to the List \n 3: Traverse the List \n 4:
Delete a Node from the List \n 5: Search a Node \n 6: Insert a Node to the List \n 7: Close
\n\n\t\t Enter your Option [ ]\b\b");
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 183
scanf("%d",&choice);
switch(choice)
{
case 1:
CreateItem();
puts("\nPress any key to go back to main menu.");
getch();
break;
case 2:
AppendItem();
break;
case 3:
PrintItem();
puts("\nPress any key to go back to main menu.");
getch();
break;
case 4:
DeleteItem();
break;
case 5:
printf("Find an Item: ");
scanf("%d",&Item);
temp_node=Search(Item,0);
if(temp_node)
{
puts("The item is available in the Linked List.");
}
else
{
puts("The item is not found in the Linked List.");
}
getch();
break;
case 6:
InsertItem();
break;
case 7:
exit();
default:
puts("Invalid choice.");
puts("\nPress any key to go back to main menu.");
getch();
break;
}
}
}
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 184
/* Function to Create the list*/
void CreateItem()
{
if(high==NULL)
{
printf("\n --Creating the list--");
temp_node=NodeAlloc();
printf("\n Enter starting data (as integer value) :");
scanf("%d",&temp_node->data);
high=temp_node;
}
else{ printf("\n List already created @ %d with %d as data.",high,high->data);}
}
while(low->rightlink!=NULL)
low=low->rightlink;
low->rightlink=temp_node;
temp_node->leftlink=low;
last=low->rightlink;
}
}
/* Function to Traverse the list both ways and print the data*/
void PrintItem()
{
DUBLL temp_node;
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 185
getch();
CreateItem();
}
temp_node=high;
last=low->rightlink;
printf("\n--Printing The List In Forward direction--\n");
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 187
getch();
CreateItem();
}
temp_node=NodeAlloc();
printf("Position At which node to be inserted: ___ & New Item Value: ___ ");
scanf("%d",&node);
scanf("%d",&temp_node->data);
pntr=Search(node,1);
pntr->rightlink->leftlink=temp_node;
pntr->rightlink=temp_node;
***** M A I N M E N U *****
OutputScreen:
Conclusion: students are able to implement the doubly linked list operations.