0% found this document useful (0 votes)
286 views

CP Lab Manual

The document provides information about the objectives, outcomes and introduction of the Computer Programming Lab course. The objectives of the lab are to teach students programming languages like C, data structures and concepts of file handling. Upon completion, students will be able to develop programs using control statements, arrays, pointers, functions and linked lists. The lab contains 60 computer systems configured with software like Windows, Linux, Oracle, Informatica and Cognos to teach students different programming environments and tools. Strict procedures are outlined for students to perform experiments, maintain records and be evaluated. The JNTU syllabus for the course also lists out experiments to be performed by students over weeks involving writing programs to calculate sums, Fibonacci
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
286 views

CP Lab Manual

The document provides information about the objectives, outcomes and introduction of the Computer Programming Lab course. The objectives of the lab are to teach students programming languages like C, data structures and concepts of file handling. Upon completion, students will be able to develop programs using control statements, arrays, pointers, functions and linked lists. The lab contains 60 computer systems configured with software like Windows, Linux, Oracle, Informatica and Cognos to teach students different programming environments and tools. Strict procedures are outlined for students to perform experiments, maintain records and be evaluated. The JNTU syllabus for the course also lists out experiments to be performed by students over weeks involving writing programs to calculate sums, Fibonacci
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 190

1.

COMPUTER PROGRAMMING LAB

LAB OBJECTIVE

• To make the student learn a programming language.

• To teach the student to write programs in C solve the problems

• To introduce the student to simple linear and non linear data structures such as lists,
stacks, queues, trees and graphs.

• 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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 1


2. Computer Programming Lab

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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 2


3. INTRODUCTION ABOUT COMPUTER PROGRAMMING LAB

There are 60 systems (Compaq Presario) installed in this Lab. Their configurations are as
follows:

Processor : Intel(R) Pentium(R) Dual CPU 2.0GHz


RAM : 2 GB
Hard Disk : 160 GB
Mouse : Optical Mouse

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.

 ETL TOOL: Informatica 7.1.1 is installed in all the systems.

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.

 Reporting TOOL: COGONS is installed in all the systems.

Students can generate reports using this tool from different Business Objects in
different formats.

 MASM (Macro Assembler) is installed in all the systems

 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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 3


 Softwares installed: C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT NET,
Rational Rose.

 Systems are provided for students in the 1:1 ratio.

 Systems are assigned numbers and same system is allotted for students when they
do the lab.

A. STANDARD OPERATING PROCEDURE – SOP

a) Explanation on today’s experiment by the concerned faculty using OHP/PPT covering the
following aspects: 25 mins.

1) Name of the experiment/Aim


2) Software/Hardware required
3) Description about the program
4) Test Data
1) Valid data sets
2) Limiting value sets
3) Invalid data sets
b) Writing of C programs by the students 25 min.
c) Compiling and execution of the program

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

4.B. Guide Lines to Students in Lab

Disciplinary to be maintained by the students in the Lab:

 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.

Steps to perform experiments in the lab by the student

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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 5


Step7: Students need to attend the Viva-Voice on that experiment and write the same in the
observation book.
Step8: Update the completed experiment in the record and submit to the concerned faculty in-
charge.

Instructions to maintain the record

 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.

Awarding the marks for day to day evaluation:

Total marks for day to day evaluation is 15 Marks as per JNTUH.


These 15 Marks are distributed as:

Record 5 Marks

Exp setup/program written 5 Marks


and execution
Result and Viva-Voice 5 Marks

Allocation of Marks for Lab Internal

Total marks for lab internal is 25 Marks as per JNTUH.


These 25 Marks are distributed as:
Average of day to day evaluation marks : 15 Marks
Lab Mid exam: 10 Marks

Allocation of Marks for Lab External

Total marks for lab internal is 50 Marks as per JNTUH.


These 50 Marks are distributed as:
Program Written: 20 Marks
Program Execution and Result: 15 Marks
Viva-Voice: 10 Marks

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 6


Record: 5 Marks

5. JNTU SYLLABUS
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD

I Year B.Tech. L T/P/D C

0 -/3/- 4

COMPUTER PROGRAMMING LAB

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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 9


b) Write a C program that implements the Bubble sort method to sort a given list of
names in ascending order.
Week 16
Write a C program that uses functions to perform the following operations:
i) Create a singly linked list of integer elements.
ii) Traverse the above list and display the elements.

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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 10


6. List of Additional Lab Programms

S. No Name of the experiment


1 Program on stack application (Infix to Postfix Conversion)
2 Program on Doubly linked list.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 11


7. Content of Lab Experiments

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 12


Step 5: r←n%10
Step 6: sum←sum+r
Step 7: n←n/10
End
Step 8: Print “sum”
Step 9: Stop

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 13


Flowchart:
Start

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 14


Program Input:
ENTER A POSITIVE INTEGER
532

Program Output
THE SUM OF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..10

Output screen:

Fig.1.1

Viva Voice Questions

1.who developed c programming language?


2.what is the program
3.Differentiate between a for loop and a while loop?
4.what are the types of errors in c
5 What are the types of operators in c
6.what is the use of stdio.h header file

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 15


1.1. b)b) AAFibonacci
Fibonacci Sequence
Sequence isis defined
defined asas follows:
follows: the
the first
first and
and
second terms in the sequence are 0 and 1. Subsequent terms are
second terms in the sequence are 0 and 1. Subsequent terms are
foundby
byadding
addingthe
thepreceding
precedingtwo twoterms
termsininthethesequence.
sequence.WriteWriteaa
found
sequence. .
CCprogram
programtotogenerate
generatethe
thefirst
firstnnterms
termsofofthe
thesequence

Aim:
Implementation of c program to generate the first n terms of the Fibonacci sequence..

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 16


Flowchart:
Start

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

Viva Voice Questions

1. What is the Fibonacci sequence explain logic


2.what are the basic data types and sizes
3.What are the conditional statements and loop statements
4.What are the arithmetic operators explain each
5.What is the general form and flowchart of while statement
6.what is the algorithm/pseudo code

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 18


1.1.c)c)Write
WriteaaCCprogram
programtotogenerate
generateall
allprime
primenumbers
numbersbetween
between
1 and n. Where n is the value supplied by the user.
1 and n. Where n is the value supplied by the user.

Aim:
Implementation of c program to print a prime numbers up to 1 to n

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 19


Flowchart:

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:");

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 20


scanf("%d",&n);
for(i=1;i<=n;i++)
{ fact=0;
//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.
for(j=1;j<=i;j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("\n %d",i);
}
getch( );
}

Program Input:

Enter the number: 5

Program output:

2 3 5
Output screen:

Fig.1.3
Viva Voice Questions

1.what is prime number


2.What is the general form and flowchart of for statement
3.what is the structure of c language
4 What are the relational operators explain each
5. what is the difference of syntax error and run time error
6.what is the use of printf() function
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 21
WEEK2:
2 4 6
2.2.a)a)Write
WriteaaCCprogram programtotocalculate
calculatethe
theSum=1-x
Sum=1-x2/2!+
/2!+xx4/4!-
/4!-xx
6 /6!+
8 /6!+
/8!-xx1010/10!
xx8/8!- /10!

Aim:
Implementation of C program to calculate the sum. Of 1-x2/2!+ x4/4!- x6/6!+ x8/8!- x10/10!

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

Flowchart: Main Program:


GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 22
Program code:

#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--;
}

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 23


return y;
}

Program Input:

Enter the value of x : 1

Program Output:
The result is 0.540302

Output Screen:

Fig.2.1

Viva Voice Questions

1.what are the program development steps


2.what is the use of scanf() function
3.What is the difference between library functions and user defined functions
4.what is the use of math.h header file
5.What is the flowchart? which symbols are used to construct flowchart
6.what is the difference between compiler and interpreter

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 24


2.2.b)b) Write
WriteaaCCprogram
programtotofind
findthe
theroots
rootsofofaaquadratic
quadraticequation.
equation.

Aim:
Implementation of C program to find the roots of a quadratic equation.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

Description:

roots of quadratic equation are

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 25


Flow chart:

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");

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 26


scanf("%d%d%d",&a,&b,&c);
disc=(float)b*b-4*a*c;

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:

ENTER VALUES FOR a,b,c

1 4 4

Program Output:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 27


THE ROOTS ARE EQUAL AND THEY ARE.. Root1=-2 Root2=-2

Output Screen:

Fig.2.2

Viva Voice Questions

1.What is the general form and flowchart of if statement


2.what is the difference between for and while statement
3.what is the use of clrscr() function
4.define keywords. How many keywords are there explain with examples
5.explain increment and decrement operators with example
6.what is the difference between while and do while explain
with flowchart

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 28


WEEK 3:

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:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 29


Flowchart:
Start

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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 30


The distance travelled in 1 second is 2.500000

Output Screen:

Viva Voice Questions:

1. explain general form of switch case statement


2.what is the use of break in switch case statement
3.what is the general form and flowchart of do while statement
4.which operator is called ternary operator
5.define operator. what are types of operators. explain arithmetic operators
6.which statement is known as multiway decision statement.explain the flow of
logic

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

Description:
The user will supply the two operand values to perform all arithmetic operations like
+,-,*,/,% by using switch statement.

Algorithm:

Step 1: Read a,b


Step 2: Print “Menu Options”
Step 3: do
Begin
Step 4: Read ch
Step 5: switch(ch)
Begin
Step 6: case 1:
Begin
Calculate c = a+b
Print “c”
break;
End

case 2:
Begin
Calculate c = a-b
Print “c”
break;
End
case 3:
Begin
Calculate c = a*b
Print “c”
break;
End

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 32


case 4:
Begin
Calculate c = a/b
Print “c”
break;
End
case 5:
Begin
Calculate c = a%b
Print “c”
break;
End
default:Print “Invalid choice”
End
End

Flowchart:

Start

Read

a,b,ch

switch(ch)

c=a+b c=a-b c=a*b c=a/b c=a%b

Print c

Stop

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 33


Program Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,ch;
clrscr();
printf("ENTER TWO VALUES FOR a & b\n");
scanf("%d %d",&a,&b);
while(1)
{
printf("MENU OPTIONS \n");
printf("************\n");
printf("1.Addition\n");
printf("2.Subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("5.Modulus\n");
printf(“6.Exit\n”);
printf("\n");
printf("ENTER UR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: c=a+b;
printf("The addition of %d and %d is..%d\n",a,b,c);
break;
case 2: c=a-b;
printf("The subtraction of %d and %d is..%d\n",a,b,c);
break;
case 3: c=a*b;
printf("The multiplication of %d and %d is..%d\n",a,b,c);
break;

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 34


}

Program Input:

ENTER TWO VALUES FOR a & b:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 35


Output screen:

Fig.3.2

Viva Voice Questions

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 36


WEEK4:
4.a.i)Write
WriteaaCCprogram
programtotofind
findthe
thefactorial
factorialofofaagiven
giveninteger
integerusing
using
4.a.i)
non-recursive function.
non-recursive function.

Aim:
Implementation of C program to find the factorial of a given number using non-recursive
function.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 37


Flowchart:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 38


int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return(f);
}
Program Input:
ENTER A VALUE FOR n 5

Program Output:

THE FACTORIAL OF A GIVEN NUMBER IS..120

Output Screen:

Fig.4.1
Viva Voice Questions

1. what is the recursive and non-recursive function


2. what is factorial
3. what is the definition of function
4. Where are the auto variables stored?
5. Difference between pass by reference and pass by value?
6. What does static variable mean?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 39


4.4.a.ii)
a.ii)Write
WriteaaCCprogram
programtotofind
findthe
thefactorial
factorialofofaagiven
giveninteger
integerusing
using
recursive function.
recursive function.

Aim:
Implementation of C program to find the factorial of a given number using recursive
function.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 40


Flow chart:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 41


int fact(int n)
{
int r;
if(n==0)
return(1);
else
{
r=n*fact(n-1);
return(r);
}
}
Program Intput:
ENTER A VALUE FOR n 5

Program Output:
THE FACTORIAL OF A GIVEN NUMBER IS ..120

Output Screen:

Fig.4.2
Viva Voice Questions

1. what is the recursive and non-recursive function


2. what is factorial
3. what is the definition of function
4. Where are the auto variables stored?
5. Difference between pass by reference and pass by value?
6. What does static variable mean?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 42


4.b.i)Write
WriteaaCCprogram
programtotofind
findthe
theGCD
GCDofoftwo
twogiven
givenintegers
integersby
by
4.b.i)
Usingthe
therecursive
recursivefunction
function
Using

Aim:
Implementation of C program to find the Gcd of two given integers by using the
recursive function

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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)

Step 1: if n>m return GCD(n,m)


Step 2: if n==0 return m else goto step 3
Step 3: return GCD (n,m%n)
Step 4: return to main program

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 43


Flowchart:

Main Program:
Start

Read a,b

Call sub program


G=gcd(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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 44


GCD of a,b is : 5

Output Screen:

Fig.4.3

Viva Voice Questions

1.what is gcd

2. what is the difference between local variables and global variables

3.explain actual parameters and formal parameters

4. What are the different storage classes in C?

5. What are register variables? What are the advantage of using

register variables?

6. explain bitwise operators

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 45


b.ii) Write a C program to find the GCD of two given integers using
b.ii) Write a C program to find the GCD of two given integers using
non-recursivefunction.
function.
non-recursive

Aim:
Implementation of C program to find the GCD of two given integers by using the non
recursive function

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

Step 1: initialize the p=1, q, remainder


Step 2: remainder=p-(p/q*q)
Step 3: remainder=0 return q else goto step 4
Step 4: GCD(q,remainder) return to main program

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 46


Flowchart:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 47


Program Input:

enter the two numbers whose gcd is to be found:5,25

Program Output:

GCD of a,b is : 5

Output Screen:

Fig.4.4
Viva Voice Questions

1.what is gcd

2. what is the difference between local variables and global variables

3.explain actual parameters and formal parameters

4. What are the different storage classes in C?

5. What are register variables? What are the advantage of using

register variables?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 48


6. explain bitwise operators

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 49


Assign large=a[i]
Increment i goto Step 7
Step 8: print small, large
Step 9: stop

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];

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 50


for(i=0;i<n;i++)// read the elements of an array
{ if(a[i]<small)// check the condition for minimum value
small=a[i];
if(a[i]>large)//check the condition for maximum value
large=a[i];
}
printf("largest value is:%d\n",large);
printf("smallest value is:%d\n",small);
getch();
}
Program Input:
Enter The Array Size:10
ENTER THE ELEMENTS OF ARRAY
7 10 9 8 6 5 2 3 4 1

Program Output:
largest value is : 10
smallest value is : 1

Output Screen:

Fig.5.1
Viva Voice Questions

1. How would you use the functions sin(), pow(), sqrt()?


2. explain difference between for and while loop
3. What are the advantages of using pointers in a program?
4. What is the difference between Strings and Arrays?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 51


5. explain if and switch case statement
6. what are the assignment operators explain with example

5.5.b)i)
b)i)Write
WriteaaCCprogram
programtotoperform
performaddition
additionofoftwo
twomatrices.
matrices.

Aim:
Implementation of C program to perform addition of two matrices.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

Description:
The sum A+B of two m-by-n matrices A and B is calculated entrywise:

(A + B)i,j = Ai,j + Bi,j, where 1 ≤ i ≤ m and 1 ≤ j ≤ n.

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 52


Flowchart:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 53


printf("ENTER B MATRIX\n");

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:

After addition of two matrices is..


2 3 4
5 6 7
8 9 10

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 54


Output Screen:

Fig.5.2

Viva Voice Questions

1. what are the rules of adding two matrices?


2. What are advantages of arrays?
3. What is the difference between Strings and Arrays?
4. What is the difference between while and do while?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 55


5.5.b)ii)
b)ii)Write
WriteaaCCprogram
programtotomultiplication
multiplicationofoftwo
twomatrices
matrices

Aim:
Implementation of C program to perform multiplication of two matrices.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

Description:

Multiplication of two matrices is defined if and only if the number of columns of


the left matrix is the same as the number of rows of the right matrix. If A is an m-by-
n matrix and B is an n-by-p matrix, then their matrix product AB is the m-by-p matrix.

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 56


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");

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 57


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("ENTER B MATRIX\n");
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("The addition of two matrices is..\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:
The addition of two matrices is..
2 3 4
5 6 7
8 9 10

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 58


Output Screen:

Fig. 5.3

Viva Voice Questions

1.define array. explain one dimensional and two dimensional array


2.explain how to declare and initialize array
3.explain how to store the array elements and how to display
4.what is the difference of variable and array.
5.define pointer explain use of & operator
6.what are the storage classes. explain difference of static and automatic
variable

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 59


WEEK 6:

6.6. Write aa CC program


program thatthat uses
uses functions
functions toto perform
perform the
the
Write
followingoperations:
operations:
following
a. To insert aasub-string
a. To insert sub-stringinintotogiven
givenmain
mainstring
stringfrom
fromaagiven
given
position.
position.
Aim:
Imlementation of C program to insert a string into another string from a specified
position.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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 :

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 60


Algorithm:

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;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 61


for(i=0;i<pos;i++)
{
c[i]=a[i];
}
j=0;
for(i=pos;i<=l;i++)
{
c[i]=b[j];
j++;
}
j=pos;
for(i=l;i<lc;i++)
{
c[i]=a[j];
j++;
}
c[i]='\0';
puts("String after Insertion is:");
printf("%s",c);
}

Program Input:
Enter First String:
Comer
Enter Second String:
put

Enter the position where the item has to be inserted:3

Program Output:

Computer

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 62


Output Screen:

Fig.6.1
Viva Voice Questions

1.Define string. what is the use of null terminator


2.explain declaration and initialization of string variables
3.if the string contains 9 elements so what is the size of string
4.what are the most commonly used string-handling functions? explain each
5.which header file is used for string handling functions
6.what is the difference of pre increment and post increment .explain with
example

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 63


6.6. a)ii) To
To delete
delete nn Characters
Characters from
from aa given
givenposition
positionininaa given
given
a)ii)
string.
string.
Aim:
Implementation of C program to delete n Characters from a given position in a given
string.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 64


Flowchart:

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];
}

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 65


j=pos;
for(i=L;i<=La;i++)
{
c[j]=a[i];
j++;
}
puts("String after Deletion is:");
printf("%s",c);
}

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

1.how to declare and initialize two dimensional array.


2.what is the condition of multiplication of two matrices
3.what is the difference between arrays and pointers.
4.explain pointer to pointer with example
5.define identifiers with example

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 66


6.what are the applications of array

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 67


Program Code:
#include<stdio.h>
#include<string.h>
int main()
{
char a[30],b[30];
int pos=0,i=0,l,la,j,n;
puts("Enter a string");
gets(a);
strcpy(b,a);
strrev(b);
if(strcmp(a,b)==0)
printf("Pallindrome");
else
printf("Not Pallindrome") ;
return 0;
}

Program Input:
Enter a string madam

Program Output:
palindrome

Output Screen:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 68


Fig.6.3

Viva Voice Questions

1. Difference between strdup and strcpy?

2. What is the similarity between a Structure, Union and enumeration?

3. What are bit fields? What is the use of bit fields in a Structure

declaration?

4. What is the difference between character and array


5. How to declare character and string
6. How to print character and string

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 69


WEEK 7:
7.7. a)a)Write
WriteaaCCprogram
programthat
thatdisplays
displaysthe theposition
positionor
orindex
indexininthe
the
string S where the string T begins, or - 1 if S doesn't contain T.
string S where the string T begins, or - 1 if S doesn't contain T.

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

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 70


Flowchart:

Start

initialize s[],t[], found vars

Read First String

Display string

Read string to be searched


Display the string

Found = strstr(s,t)

No if found Yes

Print -1 print the string


Found –s

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 */

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 71


puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}
Program Input:
Enter the first string:
computer
Enter the string to be seareched:
mp

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 72


6.what is the difference between fflush and clrscr()
7. b)b)Write
7. WriteaaCCprogram
programtotocount
countthe
thenumber
numberofoflines,
lines,words
wordsand
and
charactersininaagiven
giventext.
text.
characters

Aim:
Implementation of C program to count the number of lines, words and characters in a given
list.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 73


Flowchart:

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’

Print lines, false


Words,chars i=0 Words ++
i++ line[i]!=’\0’
stop T F
If line[i]==’ ‘|| Lines++
Line[i]==’\t’ Chars+=strlen(line)

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:

TYPE ANY TEXT

GIVE ONE SPACE AFTER EACH WORD.

Ramu is a good boy.

Program Output:

NUMBER OF LINES=1

NUMBER OF WORDS=5

NUMBER OF CHARACTERS=18

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 75


Output Screen:

Fig.7.2

Viva Voice Questions:

1. What is the difference between void main() and main()


2. What symbol is used to represent condition in a
Flowchart?
3. How to declare multidimensional array
4. Which input and output functions are used for string
5. What is the size of string and character
6. Which conversion symbol is used to print the string.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 76


WEEK 8:
8.8.a)a)Write
WriteaaCCprogram
programtotogenerate
generatePascal’s
Pascal’striangle.
triangle.

Aim:
Implementation of C program to generate Pascal’s triangle.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 77


Step 8: Initialize b = 1
Step 9: else b=(b*(q-x+1)/x);
Step 10:Print b
End
Step 11:q=q+1
End
Step12: Stop
q++;

Flowchart:

Program Code:
#include<stdio.h>
#include<conio.h>
void main()
{

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 78


int b,p,q,r,x;
clrscr();
printf("ENTER NUMBER OF ROWS\n");
scanf("%d",&r);
b=1;
q=0;
while(q<r)
{ for(p=30-3*q;p>0;p--)
printf(" ");

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:

ENTER NUMBER OF ROWS 5

Program Output:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 79


Output Screen:

Fig.8.1
Viva Voice Questions

1.What are the list of unary operators


2.what is the advantages of function
3.what is the advantage of using array
4.how to access the member of structure explain
5.what is the general form and flow chart of if-else statement
6.what is the general form for declaring structure

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 80


8.8.b)b)Write
WriteaaCCprogram
programtotoconstruct
constructaapyramid
pyramidofofnumbers
numbers
as shown below.
as shown below.

Aim:
Implementation of C program to construct a pyramid of numbers

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 81


step 11:if(<=i) goto step 12
else goto step 15
step12:print j
step 13:j:=j+1
step 14: goto step 11
step 15:stop
Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 82


Program Code:

#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:

ENTER NUMBER OF ROWS 4

Program Output:

1
12
123
1234

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 83


Output Screen:

Fig.8.2

Viva Voice Questions

1.what is the use of \n


2.what is the use of \t
3.how to initialize the structure
4.what is the difference between malloc() and calloc() functions
5.what is the use of goto statement
6.what is the advantage of pointer

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 84


WEEK 9:

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 85


Step 9: Print Sum value of the series
Step 10: Stop
Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 86


Program Code:

#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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 87


Enter the values for x and n:3
6
Program Output:
Sum of series= 1093
Output Screen:

Fig.9

Viva Voice Questions

1.what are the assignment operators


2. what is the use of assignment operators
3.what is the difference of sizeof and & operator
4.what is the list of binary operators
5.how to declare and initialize the operator
6.what is the structure of c program

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 88


WEEK 10:

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.

Aim:
To compute the 2’s complement of a binary number

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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.

Ex: 0001 0001(binary 17)   = 1110 1111(two's complement -17)


Algorithm:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 89


Step 11: numbin[x]=’0’ ,decrement x value then go to step 8
Step 12: Print 2’s Compliment of a number
Step 13: Stop
Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 90


Program Code:

#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

Viva Voice Questions

1.one byte is how many bits.


2. explain binary ,decimal,octal,and hexadecimal number

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 92


3.what is the one’s complement and two’s complement of binary
number.explain with example
4.what are the arguments of main function
5.C statement ended with which operator
6.explain c tokens with example
10.b)b) Write
WriteaaCCprogram
programtotoconvert
convertaaRoman
Romannumeral
numeraltotoits
itsdecimal
decimal
10.
equivalent.
equivalent.

Aim:
Implementaion of C program to convert roman number to it’s decimal equivalent

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 94


Program Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 95
{
int a[10],len,i,j,k;
char *rom;
clrscr();
printf("Enter the Roman Numeral:");
scanf("%s",rom);
len=strlen(rom);
for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;
else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else if(rom[i]=='C')
a[i]=100;
else if(rom[i]=='D')
a[i]=500;
else if(rom[i]=='M')
a[i]=1000;
else
{
printf("\nInvalid Value");
exit(0);
}
}
k=a[len-1];
for(i=len-1;i>0;i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1] || a[i]<a[i-1])
k=k+a[i-1];
}
printf("\nIts Decimal Equivalent is:");
printf("%d",k);

getch();
}

Program Input:
Enter the Roman Numeral:IV

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 96


Program Output:
Its Decimal Equivalent is:4

Output Screen:

Fig.10.2

Viva Voice Questions

1.what is roman numeral


2.explain logic how to convert roman numeral into decimal
3.how to convert binary to decimal
4.how to convert decimal to binary
5.give the examples of hexadecimal nos
6.what is the ascii values? what is the use

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

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

Main Program Algorithm:


Step 1: Start
Step 2: Declare the Structure Complex and Declare c1, c2, c3 as structure variables
Step 3: To Read First Complex Number call sub function readdata(c1);
Step 4: Then call sub Function writedata(c1); to print the data of c1.
Step 5: To Read First Complex Number call sub function readdata(c2);
Step 6: Then call sub Function writedata(c2); to print the data of c2.
Step6: Call Sub function addcomplex(c1,c2); to add two complex numbers and call the sub
function writedata(c3); to print the result
Step 7: Call Sub function mulcomplex(c1,c2); to add two complex numbers and call the sub
function writedata(c3); to print the result
Step 8: Stop.
readdata(); sub function Algorithm

Step 1: Return from Main Function

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 98


Step 2: Declare c Structure Variable
Step 3: Read c.real, c.img values
Step 4: Return c value to main program

writedata(); sub function Algorithm

Step 1: Return from Main Function


Step 2: Print Resultant c.real, c.img values
Step 3: Return to Main Function

addcomplex(); sub function Algorithm

Step 1: Return from Main Function


Step 2: Declare c3 Structure Variable
Step 3: c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
Step 4: Return c3 value to main program

mulcomplex(); sub function Algorithm

Step 1: Return from Main Function


Step 2: Declare c3 Structure Variable
Step 3: c3.real=c1.real*c2.real-c1.img*c2.img;
c3.img= c1.img*c2.real+c2.img*c1.real;
Step 4: Return c3 value to main program

Main function flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 99


functions flowcharts:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 100


Program Code:
#include<stdio.h>
#include<conio.h>
typedef struct
{
int real;
int img;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 101


}complex;
/*Functions Declarations*/
complex readdata(complex);
void writedata(complex);
complex addcomplex(complex,complex);
complex mulcomplex(complex,complex);

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 103


Aim:
Implementation of C program to copy the contents of one file to another

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 104


Program Code:
#include<stdio.h>
#include<process.h>
#include<conio.h>
void main()
{
FILE *ft,*fs;
int c=0;
clrscr();
fs=fopen("a.txt","r");
ft=fopen("b.txt","w");
if(fs==NULL)
{
printf("Source file opening error\n");
exit(1);
}

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 105


else
if(ft==NULL)
{
printf("Target file opening error\n");
exit(1);
}
while(!feof(fs))
{
fputc(fgetc(fs),ft);
c++;
}
printf("%d bytes copied from 'a.txt' to 'b.txt'",c);
c=fcloseall();
printf("%d files closed",c);
}

Program Input:
a.txt

Program Output:

57 bytes copied from ‘a.txt’ to ‘b.txt’


2 files closed

Viva Voice Questions

1what are basic file operations


2.what are the text modes of a file
3.what are the binary modes of a file
4.what is the use of feof function
5.what is the use of fopen(),fclose(),fseek() functions
6.which data type is used in file programs

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 106


12.b)b)Write
WriteaaCCprogram
programtotoreverse
reversethe
thefirst
firstnncharacters
charactersininaafile.
file.
12.
(Note: The file name and n are specified on the command line.)
(Note: The file name and n are specified on the command line.)

Aim:
Implementation of C program to reverse the first n characters in a file

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 107


Program Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>
void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 108
if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
getch();
}
Program Input:
SOURCE.C THIS IS SOURCE
OUPUT.C THIS IS SOURCE
Program Output:
COMMAND LINE ARGUMENTS SOURCE.C OUPUT.C
SOURCE.C THIS IS SOURCE
ECRUOS SI SIHT

VIVA VOICE QUESTIONS

1. HOW WOULD YOU USE THE FUNCTIONS FWRITE() AND FTELL()?

2.WHAT IS THE PREPROCESSOR EXPLAIN

3.WHAT ARE THE FILE I/O OPERATIONS

4.DEFINE STREAMS
5.WHAT ARE THE STANDARD I/O FUNCTIONS OF FILE

6.WHAT ARE THE FORMATTED I/O FUNCTIONS OF FILE

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 109


WEEK 13:
13.a)a)write
writeaaccprogram
programtotodisplay
displaythe
thecontents
contentsofofaafile.
file.
13.

Aim:
Implementation of C program to display the contents of a file.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 110


Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 111


Program Code:

#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

VIVA VOICE QUESTIONS

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

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 113


Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 114


Programcode:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp1,*fp2,*fp3;
clrscr();
fp1=fopen("s.txt","r");
fp3=fopen("r.txt","w");
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp3);
printf("%c",ch);
}
fcloseall();
fp2=fopen("t.txt","r");
fp3=fopen("r.txt","a");
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
putc(ch,fp3);
printf("%c",ch);
}
fcloseall();
}
Program Input:
Create two text files in root directory and enter some text in the files
Files names are s.txt, t.txt

Program Output:

The program creates the third file r.txt and its contents are the contents of two source files after
merging.

Viva Voice Questions


1. How would you use the functions fseek(), freed(), fwrite() and ftell()?
2. what is the preprocessor explain
3. what are the file i/o operations
4. define streams
5. what are the standard i/o functions of file
6. what are the formatted i/o functions of file

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 115


WEEK 14:
14a)a)Write
14 WriteaaCCprogram
programthat thatuses
usesnon
nonrecursive
recursivefunction
functiontotosearch
searchfor
for
aaKey
Keyvalue
valueininaagiven
givenlist
listofofintegers
integersusing
usingLinear
Linear search.
search.

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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++)

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 117


if(key==list[i])
{
pos=i;
break;
}
if(pos==-1)
printf("\nelement not found");
else
printf("\n element found at index %d",pos);
}

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

Viva Voice Questions

1.what are the types of searching methods

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 118


2.how to search the value using linear search
3.In which search method elements should be in sorted order
4.what is advantages of pointer
5.what is advantage of linear search
6.what is the disadvantage of linear search

14b)b)Write
14 WriteaaCCprogram
programthat
thatuses
usesnon
nonrecursive
recursivefunction
functiontotosearch
searchfor
foraa
Keyvalue
Key valueininaagiven
givensorted
sortedlist
listofofintegers
integersusing
usingBinary
BinarySearch
Search

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 119


Aim:
Implementation of C program to search for a key element using binary search

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

Main Function 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

binarysearch(a,n,key) Sub Function Algorithm:

Step 1: Return from the Main Function


Step 2: Declare i, low, high, mid variables.
Step 3: Initialize low=0
Step 4: high=n-1;
mid=(low+high)/2;
Step 5: while (low<=high) if condition true goes to step 6, repeat the loop until false and then go
to step 9.
Step 6: check the condition a[mid]<key if true low = mid+1; else go to step 7
Step 7: a[mid]==key if condition true Print the element found at location else high=mid-1;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 120


Step 8: mid=(low+high)/2;
Then go to step 5
Step 9: Check condition low>high if condition true print element not found
Step 10: Return to Main Function.

Flowchart:

Program Code:

#include <stdio.h>

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 121


#include<conio.h>
void binarysearch(int [],int,int);
void main()
{
int i,n,key,a[20];
clrscr();
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("Enter value to find\n");
scanf("%d",&key);
binarysearch(a,n,key);
getch();
}
void binarysearch(int a[20],int n,int key)
{
int i,low,high,mid;
low=0;
high=n-1;
mid=(low+high)/2;
while(low<=high)
{
if(a[mid]<key)
low= mid+1;
else if(a[mid]==key)
{
printf("%d found at location %d.\n", key, mid+1);
break;
}
else
high=mid-1;
mid=(low+high)/2;
}
if(low>high)
printf("%d Not found, it is not present in the list.\n",key);
}

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

Viva Voice Questions

1.what is the advantage of binary search


2.what is the disadvantage of binary search
3.what is the use of free()in dynamic memory allocation
4.how to search the value using binary search
5.what is the diff between linear search and binary search
6.how to find the mid in binary search method

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.

Recommended Hardware / Software Requirements:


 A working intel bsed PC
 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 124


Program Code:
#include<stdio.h>
void selection_sort(int list[],int n);
void main()
{
int n,i,list[25];
lrscr();
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 125


scanf("%d",&list[i]);
selection_sort (list,n);
printf("elements after sorting\n");
for(i=0;i<n;i++)
printf("%3d\n",list[i]);
getch();
}

void selection_sort (int list[],int n)


{
int min,temp,i,j;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(list[j]<list[min])
min=j;
}
temp=list[i];
list[i]=list[min];
list[min]=temp;
}
}

Program Input:

Enter no of elements 4

Enter 4 elements 6 3 8 1

Program Output:

Elements after sorting 1 3 6 8

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 126


Output Screen:

Fig.15.1

Viva Voice Questions

1.explain logic how sort the elements in merge sort


2.what is the time complexity of merge sort in the best and worst cases
3.what is the difference between bubble sort and merge sort
4.what is the difference between quick sort and merge sort
5.what is the use of getch() in main().
6.The preprocessor command starts with which symbol?

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 127


15 b)Write
15 b)WriteaaCCprogram
programthat
thatimplements
implementsthe
theBubble
Bubblesort
sortmethod
methodtoto
sortaagiven
sort givenlist
listofofnames
namesininascending
ascendingorder.
order.

Aim:
Implementation of c program to Bubble sort method to sort a given list of names in
ascending order.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

Bubble Sort Function


step 1. start
step 2. initialise last to n
step 3. for i= 1 to n increment in steps of 1
begin
step 4. initialise ex to 0
step 5. for i= 1 to last-1 increment in steps of 1
begin
step 6. if k[i]>k[i+1] goto step 7 otherwise goto step 5
begin
step 7. assign k[i] to temp
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 128
assign k[i+1] to k[i]
assign temp to k[i+1]
increment ex by 1
end-if
end inner for loop
step 11. if ex!=0
assign last-1 to last
end for loop
step 12. stop.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 129


Program Code:

#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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 130


Output Screen:

Fig.15.2
Viva Voice Questions

1 what are the sorting methods


2.explain logic how sort the elements in bubble sort.
3.what is the use of dot operator in the structure
4.what is the size of structure
5.what is the use of sizeof operator
6.what is the time complexity of bubble sort in the best and worst cases

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 131


WEEK 16:
16.Write
WriteaaCCprogram
programthat
thatuses
usesfunctions
functionstotoperform
performVarious
Various
16.
operations on singly linked list.
operations on singly linked list.

Aim:
Implementation of c program to perform Various operations on singly linked list.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

Various operation on single linked list

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 132


7.4:Switch(choice)
7.4.1: If choice==1
7..4.2: Call the function IBegin()
7.4.3: If choice==2
7.4.4: Call the function Iend()
7.4.5: If choice==3
7.4.6: Call the function Imiddle()
Step 8: If(choice==2)
8.1: Read the position to delete
8.2: Switch(choice)
8.2.1: If choice==1
8..2.2: Call the function DBegin()
8.2.3: If choice==2
8.2.4: Call the function Dend()
8.2.5: If choice==3
8.2.6: Call the function Dmiddle()
Step 9: If choice==3
9.1 Call function view
114Step 10: If choice==4
10.1 Exit()
Step 11: Start insert function
Step 12: If(first==null)
Step 13: First->data=e
Step 14: First->next=null
Step 15: Else declare new node
Step 16:fresh->data=e
Step 17: If choice=1
Step 18: frsh->next=first
Step 19: first=fresh
Step 20:if choice=2
Step 21: ptr=first
Step 22: ptr->next=fresh
Step 23: fresh->next=full
Step 24: If choice =3
Step 25: Enter the position
Step 26:at p-1 node
Step 27: fresh->next= ptr->next
Step 28: ptr->next=fresh
Step 29: for delete function
Step 30: If first!=null
Step 31: Enter the position to delete
Step 32: If choice=1
115Step 33: d=first->data
Step 34: first=first->next
Step 35: if choice=2
Step 36: ptr=first
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 133
Step 37: Traverse to last node
Step 38: d=ptr->next->data
Step 39: ptr ->next=ptr->next->next
Step 40: Print d value
Step 41: for function view
Step 42: for ptr=first and ptr!=null and ptr=ptr->next
Step 43: Print ptr->data
Step 44: End

Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode * lptr;

/*function to create a node*/


lptr create_node()
{
lptr node;
node=(lptr)malloc(sizeof(struct lnode));
return node;
}

/*function to insert an element at end of list*/


lptr insert_end(lptr head,int x)
{
lptr p,temp;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=p;
return head;
}

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 134


}
/*function to insert an element at front of existing list*/
lptr insert_front(lptr head,int x)
{
lptr p,temp;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
p->next=head;
head=p;
return head;
}
}

/*function to insert element after a node*/


lptr insert_after(lptr head,int x,int pos)
{
lptr p,temp,q;
int c=1;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
temp=head;
while(c<=pos)
{
q=temp;
temp=temp->next;
c++;
}
q->next=p;
p->next=temp;
return head;
}
}
/* function to insert a node before a selected node*/
lptr insert_before(lptr head,int x,int pos)
{
lptr p,temp,q;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 135
int c=1;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{ temp=head;
while(c<=(pos-1))
{
q=temp;
temp=temp->next;
c++;
}
if(c==1)
{
p->next=head;
head=p;
}
else
{
q->next=p;
p->next=temp;
}
return head;
}
}
/*function to insert a node at end of list*/
lptr delete_end(lptr head)
{
lptr temp,prev;
temp=head;
if(head->next==NULL)
{
free(temp);
head=NULL;
return head;
}
else
{ while(temp->next!=NULL)
{
prev=temp;
temp=temp->next;
}
prev->next=NULL;
printf("\n %d is deleted from list",temp->data);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 136
free(temp);
return head;
}
}
/*function to delete a node from front of list*/
lptr delete_front(lptr head)
{
lptr temp;
temp=head;
head=head->next;
printf ("\n%d is deleted",temp->data);
free(temp);
return(head);
}
/*function to display data present in all nodes in a linked list*/
void display(lptr head)
{
lptr temp;
temp=head;
printf("\n\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next ;
}
}

/*function to print number of nodes present in a linked list*/


int node_count(lptr head)
{
lptr temp;
int ncount=0;
temp=head;
while(temp!=NULL)
{
temp=temp->next;
ncount++;
}
return ncount;
}
void main()
{
lptr head=NULL;
int choice,item,pos;
clrscr();
while(1)
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 137
{
printf("\nenter choice \n1.insert end \n2.insert front \n3.insert after\n4.insert before\n");
printf("5.del end\n6.del front\n7.dislay\n8.node count \n9.clear screen\n10.exit");
printf("\n Enter UR Choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nenter value into new node");
scanf("%d",&item);
head=insert_end(head,item);
printf("\n\nelement inserted at end");
break;
case 2 : printf("\n\nenter value into new node");
scanf("%d",&item);
head=insert_front(head,item);
printf("\n\nelement inserted at end");
break;
case 3 : printf("\nenter value into new node");
scanf("%d",&item);
printf("\n\nenter position from 1 to %d",node_count(head));
scanf("%d",&pos);
head=insert_after(head,item,pos);
printf("\n\nelement inserted after %d pos",pos);
break;
case 4 : printf("\nenter value into new node");
scanf("%d",&item);
printf("\nenter position from 1 to %d",node_count(head));
scanf("%d",&pos);
head=insert_before(head,item,pos);
printf("\nelement inserted before %d pos",pos);
break;
case 5 : if(head==NULL)
printf("\nempty list");
else
head=delete_end(head);
break;
case 6 : if(head==NULL)
printf("\nempty list");
else
head=delete_front(head);
break;
case 7 : if(head==NULL)
printf("\nempty list");
else
display(head);
break;
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 138
case 8 : if(head==NULL)
printf("\nempty list");
else
printf("\nno of nodes are %d",node_count(head));
break;
case 9 : clrscr();
break;
case 10 : exit(0);
default : printf("\ninvalid choice enter choice again ");
break;
}}}

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 140


WEEK17:

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

Algorithm For Pop Operation

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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 142


Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct stack
{
int data;
struct stack *next;
};
typedef struct stack * sptr;
sptr createnode()
{
sptr node;
node=(sptr)malloc(sizeof(struct stack));
return node;
}
sptr push(sptr head,int x)
{
sptr p,temp;
p=createnode();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
p->next=head;
head=p;
return head;
}
}
sptr pop(sptr head)
{
sptr temp;
temp=head;
head=head->next;
printf("%d is deleted",temp->data);
free(temp);
return(head);
}
void display(sptr head)
{
sptr temp;
temp=head;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 143


while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void main()
{
sptr top=NULL;
int choice,item;
clrscr();
while(1)
{
printf("\n--------------------------------\n");
printf("| MENU FOR OPERATIONS ON STACK |");
printf("\n--------------------------------\n");
printf("1.push\n2.pop\n3.display\n4.exit");
printf("\n-------------------------------\n");
printf("Enter Your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n enter element to push");
scanf("%d",&item);
top=push(top,item);
printf("element %d is pushed succesfully" ,item);
break;
case 2: if(top==NULL)
printf("stack is empty");
else
top=pop(top);
break;
case 3: if(top==NULL)
printf("stack is empty");
else
display(top);
break;
case 4: exit(0);
}
}
}

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 144


Program Input/Output:
---------------------------------------------
| MENU FOR OPERATIONS ON STACK |
---------------------------------------------
1.push
2.pop
3.display
4.exit
Enter your choice:1
Enter element to push 3
Element 3 is pushed successfully
---------------------------------------------
| MENU FOR OPERATIONS ON STACK |
---------------------------------------------
1.push
2.pop
3.display
4.exit
Enter your choice:3
3
---------------------------------------------
| MENU FOR OPERATIONS ON STACK |
---------------------------------------------
1.push
2.pop
3.display
4.exit
Enter your choice:2
3 is deleted
---------------------------------------------
| MENU FOR OPERATIONS ON STACK |
---------------------------------------------
1.push
2.pop
3.display
4.exit
Enter your choice:3
Stack is empty
---------------------------------------------
| MENU FOR OPERATIONS ON STACK |
---------------------------------------------
1.push
2.pop

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 145


3.display
4.exit
Enter your choice:4

Output Screen:

Fig. 17

Viva Voice Questions


1.what is the definition of data structure
2.explain linear data structure with examples
3.explain Non-linear data structure with examples
4.what are the operations performed on the stack
5.what is the difference between float and double
6.what is the difference of static and dynamic implementation

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 146


WEEK 18:
18Write
WriteaaCCprogram
programthat thatimplements
implementsQueueQueue(its
(itsoperations)
operations)using
using aa
18
singlylinked
linkedlist
listtotodisplay
display aagiven
givenlist
listofofintegers
integersininthe
thesame
sameorder.
order.Ex.
Ex.
singly
input: 10 23 4 6 output: 10 23 4 6
input: 10 23 4 6 output: 10 23 4 6

Aim:
To implement Queue (its operations) using a singly linked list to display a given list of
integers in the same order

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

Algorithm for inserting an element in to a queue:


Function QINSERET(Q,F,R,N,Y)
Step 1: [overflow]
If R>=N
Then printf(“ overflow”)
Return
Step 2: [Increment rear pointer]
R<-R+1
Step 3: [ Insert element]
Q[R]<-y
Step 4: [Is front pointer properly set?]
If F=0
Then f<-1
Return

Algorithm for deleting an element from a stack:


Function QDELETE(Q,F,R)
Step 1: [Underflow]
If F=0
Then printf(“Queue underflow”)
Return(0)

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 147


Step 2: [Delete element]
y<-q[f]
Step 3: [Is Queue Empty?]
If F=R
Then F=R=0
Else
F=F+1
Step 4:[Return element]
Return(r)

Flowchart:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 148


Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct queue
{
int data;
struct queue *next;
};
typedef struct queue * qptr;

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 151


2.DELETE
3.DISPLAY
4.Exit
Enter your choice:4
Output Screen:

Fig.18

Viva Voice Questions

1.what are the operations performed on the queue


2.what is the value of rear and front at each insertion and deletion of element
in the queue
3.how to know the queue is full or not
4.what is the difference between the stack and queue
5.what is the circular queue
6.what is the advantage of circular queue over linear queue

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 152


WEEK 19:
WriteaaCCprogram
Write programto
toimplement
implementthe
thelinear
linearregression
regressionalgorithm.
algorithm.

Aim:
C program to implement the linear regression algorithm.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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>

float mean(float *a, int n);


void deviation(float *a, float mean, int n, float *d, float *S);

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

else if(strcmp(type_coff,"y on x")==1)


{
reg_coff_yx=corr_coff*(sy/sx);
printf("\nThe value of linear regression coefficient is %f",reg_coff_yx);
}
else
printf("\nEnter the correct type of regression coefficient.");
getch();
}
float mean(float *a, int n)
{
float sum=0, i=0;
for(i=0;i<n;i++)
sum=sum+a[i];
sum=sum/n;
return (sum);
}
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);
}

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

Enter the correct type of regression coefficient.

Output Screen:

Fig:19

Viva Voice Questions

1.what is the linear 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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 156


WEEK 20
20.Write
WriteaaCCprogram
programtotoimplement
implementthe
thepolynomial
polynomialregression
regressionalgorithm.
algorithm.
20.

Aim:
To implement the polynomial regression algorithm

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 157


a[2][2] = n
a[2][3] = n
Step 10: Intialize i=0
Step 11: Repeat steps 11 to 15 until i<3
Step 12: Intialize j=0
Step 13: Repeat step 13 to 14 until j<=3
Step 14: Write a[i][j]
Step 15: Increment j by 1
Step 16: Increment I by 1
Step 17: Initialize k =0
Step 18: Repeat steps 18 to 27 until k<=2
Step 19: Intialize i=0
Step 20: Repeat step 20 to 26 until i<=2
Step 21: If I not equal to k
Step 22: Asign u=a[i][k]/a[k][k]
Step 23: Intialize j=k
Step 24: Repeat steps 24 and 25 until j<=3
Step 25: Assign a[i][j] = a[i][j] – u *a[k][j]
Step 26: Increment j by 1
Step 27: Increment i by 1
Step 28: Increment k by 1
Step 29: Initialize I =0
Step 30: Repeat steps 31 to 33 until i<3
Step 31: Assign b[i] = a[i][3]/a[i][i]
Step 32: Write I, b[i]
Step 33: Increment I by 1
Step 34: Write b[2],b[i],b[0]
Step 35: Stop

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 160


Week 21:
21.Write
WriteCCprogram
programtotoimplement
implementthe
theLagrange
Lagrangeinterpolation.
interpolation.
21.

Aim:
To implement the Lagrange interpolation.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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");

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 161


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);
for (i=0; i<=n; i++)
{
numerator=1;
denominator=1;
for (j=0; j<=n; j++)
if(j!=i)
{
numerator *= x-arr_x[j];
denominator *= arr_x[i]-arr_x[j];
}
y+=(numerator/denominator)*arr_y[i];
}
printf("When x=%4.1f y=%7.1f\n",x,y);
getch();
}

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:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 162


Fig.21
Viva Voice Questions

1.what is the lagrange interpolation formula


2.which formula is used to calculate the mid in binary search
3.give two examples of syntax errors
4.define array.what are the types of array
5.what is the use of flowchart
6.how to declare and initialize the pointer

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 163


WEEK 22:
22.Write
WriteCCprogram
programtotoimplement
implementthe
theNewton-
Newton-Gregory
Gregoryforward
forwardinterpolation.
interpolation.
22.

Aim:
To implement the Newton- Gregory forward interpolation.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

Description:

Gregory-Newton Forward Difference Approach:

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 164


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]
print ‘When x=%6.1f, y=%6.2f\n",x, y
Step9: Stop

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:

Enter the value of n 2


Enter the values of x and y
3 4 5.6 6.7 1.2 3.2
Enter the value of x at which value of y is to be calculated4
When x= 4.0, y= 5.77
Enter the value of n 110
Enter the values of x and y3
44 4 2 2 34 4 4 4
exit
Enter the value of x at which value of y is to be calculated Floating point error
: Overflow.
Abnormal program termination

Output Screen:

Fig:22

Viva Voice Questions

1.what is the interpolation


2.what is the Newton-Gregory forward interpolation formula
3.give two examples of run time errors
4.what is the meaning of LIFO and FIFO
5.what is a network
6.what is a spanning tree

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 166


WEEK 23:
23.Write
WriteaaCCprogram
programtotoimplement
implementTrapezoidal
Trapezoidalmethod.
method.
23.

Aim:
To implement Trapezoidal method.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 168


Output Screen:

Fig:23

Viva Voice Questions

1.What is the trapezoidal method


2.What is the difference between Syntax error and runtime error
3. How many types of linker errors are there?
4. What is the use of sizeof operator?
5. The preprocessor command starts with which symbol?
6. How would you use the functions fseek(), freed(), fwrite() and ftell()?

WEEK 24:
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 169
24.Write
WriteaaCCprogram
programtotoimplement
implementSimpson
Simpsonmethod.
method.
24.

Aim:
To implement Simpson method.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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:

Enter the values of a,b,n


123

Enter the value of x


4567

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 171


Enter the values of y
8912

Program Output:

Integral value is 5.555556

Output Screen:

Fig:24

Viva Voice Questions

1. which conversion symbol is used to print the string.


2.which input and output functions are used for string
3. explain actual parameters and formal parameters
4. What are the different storage classes in C?
5. What are the types of operators in c
6.What are the relational operators explain each

8.Contents of additional Lab Programs


Additional Program-1:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 172


AIM:
To implement a C program that uses Stack operations to perform the following:
i) Converting infix expression into postfix expression
ii) Evaluating the postfix expression

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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++

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 173


t=in[x]
while(st_top!=-1)
c=pop_item()
post[y]=c
y++
print ‘The Postfix Expression is’
for(z=0;z<y;z++)
print post[z]
print ‘Do you want to evaluate the Result of Postfix Expression?(Y/N)’
if(a=='y' || a=='Y')
result=cal(post)
print result
else if(a=='n' || a=='N')
Step10: /*Determining priority of inside elements*/
int st_ISP(char t)
switch(t)
case '(':return (10)
case ')':return (9)
case '+':return (7)
case '-':return (7)
case '*':return (8)
case '/':return (8)
case '\0':return (0)
default: print ‘Expression is invalid’
Step11: /*Determining priority of approaching elements*/
int st_ICP(char t)
switch(t)
case '(':return (10)
case ')':return (9)
case '+':return (7)
case '-':return (7)
case '*':return (8)
case '/':return (8)
case '\0':return (0)
default: print ‘Expression is invalid’
Step12: /*Evaluating the result of postfix expression*/
int cal(char post[])
int m,n,x,y,j=0,len
len=strlen(post)
while(j<len)
if(isdigit(post[j]))
x=post[j]-'0'
push_item(x)
else
m=pop_item()
n=pop_item()
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 174
switch(post[j])
case '+':x=n+m
case '-':x=n-m
case '*':x=n*m
case '/':x=n/m
push_item(x)
j++
if(st_top>0)
print ’Number of Operands are more than Operators’
else
y=pop_item()
return (y)
Step13: Stop

Program Code:

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

int st[100];
int st_top=-1;

int cal(char post[]);


void in_post(char in[]);
void push_item(int it);
int pop_item();
int st_ISP(char t);
int st_ICP(char t);

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

void push_item(int it)


{
if(st_top==99)
{

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 175


printf("\n\n\t*STACK is Full*");
getch();
exit(1);
}
st[++st_top]=it;
}

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

/*Function for converting an infix expression to a postfix expression. */


void in_post(char in[])
{
int x=0,y=0,z,result=0;
char a,c, post[100];
char t;
push_item('\0');
t=in[x];
while(t!='\0')
{
if(isalnum(t))
/*For checking whether the value in t is an alphabet or number. */
{
post[y]=t;
y++;
}
else if(t=='(')
{
push_item('(');
}
else if(t==')')
{
while(st[st_top]!='(')
{
c=pop_item();
post[y]=c;
y++;
}
c=pop_item();
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 176
}
else
{
while(st_ISP(st[st_top])>=st_ICP(t))
{
c=pop_item();
post[y]=c;
y++;
}
push_item(t);
}
x++;
t=in[x];
}

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

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

/*Determining priority of inside elements*/


int st_ISP(char t)
{
switch(t)
{
case '(':return (10);
case ')':return (9);
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 177
case '+':return (7);
case '-':return (7);
case '*':return (8);
case '/':return (8);
case '\0':return (0);
default: printf("Expression is invalid.");
break;
}
return 0;
}

/*Determining priority of approaching elements*/


int st_ICP(char t)
{
switch(t)
{

case '(':return (10);


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

/*Evaluating the result of postfix expression*/


int cal(char post[])
{
int m,n,x,y,j=0,len;
len=strlen(post);
while(j<len)
{
if(isdigit(post[j]))
{
x=post[j]-'0';
push_item(x);
}
else
{
m=pop_item();
n=pop_item();
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 178
switch(post[j])
{
case '+':x=n+m;
break;
case '-':x=n-m;
break;
case '*':x=n*m;
break;
case '/':x=n/m;
break;
}
push_item(x);
}
j++;
}
if(st_top>0)
{
printf("Number of Operands are more than Operators.");
exit(0);
}
else
{
y=pop_item();
return (y);
}
return 0;
}

Results for different Data Sets

Enter the Infix Expression: a*b+c-d

The Postfix Expression is:ab*c+d-

Do you want to evaluate the Result of Postfix Expression?(Y/N):y

Result is: 5728

Enter the Infix Expression: as*bn+cg/rty

The Postfix Expression is: asbn*cgrty/+

Do you want to evaluate the Result of Postfix Expression? (Y/N):y

Result is: 13
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 179
Output Screen:

Fig.8.1

Viva Voice Questions

1. what are the applications of stack


2. define infix, prefix and postfix with example
3. explain with algorithm to convert infix to prefix expression
4. explain with algorithm to convert infix to postfix expression
5. explain with algorithm to postfix evaluation
6. what is the order of precedence of operators

conclusion: students are able to implement the infix to postfix conversion.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 180


Additional Program-2:

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.

Recommended Hardware / Software Requirements:

 A working intel bsed PC


 ANSI C Compiler with Supporting Editors

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;

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 181


head=new;
else
n1=find(head,key)
if(n1==null)
print’key is not found’
else
new=(node*)malloc(sizeof(node))
new->number=x
new->next=n1->next
n1->next=new
return head
Step15:node *find(node *list,int key)

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"

typedef struct dubll


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

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

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

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

void main(void)
{
int choice,Item;
high=NULL;
while(1)
{
clrscr();
printf("\n \t\t\t***** M A I N M E N U *****\n\n");
printf("\n 1: Create Linked List \n 2: Append a Node to the List \n 3: Traverse the List \n 4:
Delete a Node from the List \n 5: Search a Node \n 6: Insert a Node to the List \n 7: Close
\n\n\t\t Enter your Option [ ]\b\b");
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);}
}

/* Function to Append items to the list*/


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

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

}
}

/* Function to Traverse the list both ways and print the data*/
void PrintItem()
{
DUBLL temp_node;
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
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");

while(temp_node!=NULL) //In forward direction


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

/* Function to Delete items of the list*/


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

/* Function to Search an item from the list*/


DUBLL Search(int item,int flag)
{
GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 186
temp_node = high;
if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
getch();
CreateItem();
}
while(temp_node!=NULL)
{
if(temp_node->data==item )
{
if(flag==0)
{
return(1);
}
else
{
return(temp_node);
}
}
temp_node=temp_node->rightlink;
}
}

/* Function to Allocate nodes*/


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

/* Function to Insert items in the middle of the list*/


void InsertItem()
{
int node;
DUBLL temp_node;

if(high==NULL)
{
printf("\n List is not available. Please create a list first.");
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);

if(pntr->rightlink==NULL){printf("\n The operation is not possible."); getch();return;}


temp_node->leftlink=pntr; //creating link to new node
temp_node->rightlink=pntr->rightlink;

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

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


getch();
}

Results for different Data Sets

***** M A I N M E N U *****

1: Create Linked List


2: Append a Node to the List
3: Traverse the List
4: Delete a Node from the List
5: Search a Node
6: Insert a Node to the List
7: Close
Enter your Option [ 3]

--Printing The List In Forward direction--


12 12

--Printing The List In Backward direction--


12 12
Press any key to go back to main menu.

OutputScreen:

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 188


Fig.8.2
Viva Voice Questions

1.what are the advantages of linked list


2.what is the difference between static and dynamic memory allocation
3.which fuctions are used for dynamic memory allocation
4.what is the use of arrow operator in the structure
5.how to insert and delete elements from doubly linked list
6.explain how traversal the elements in doubly linked list

Conclusion: students are able to implement the doubly linked list operations.

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 189


9. REFERNCE BOOKS:

1. C programming and Data Structures, P. Padmanabham, Third Edition, BS Publications


2. Computer Programming in C, V. Rajaraman, PHI Publishers.
3. C Programming, E.Balagurusamy, 3rd edition, TMH Publishers.
4. C Programming, M.V.S.S.N.Prasad, ACME Learning Pvt. Ltd.
5. C and Data Structures, N.B.Venkateswarlu and E.V.Prasad,S.Chand Publishers
6. Mastering C, K.R. Venugopal and S.R. Prasad, TMH Publishers

GNIT/CSE/LAB MANUALS/ CP MASTER MANUAL Page 190

You might also like