Lab Program : Week 1

Computer Programming and Data Structures Laboratory Manual
SREYAS
Introduction
Subject
Year
Branches
: Computer Programming and Data Structures Laboratory
: I Year B. Tech
: Common to all Branches
Lab Objectives



To make the student learn a programming language.
To teach the student to write programs in C to solve the problems.
To introduce the student to simple linear data structures such as lists, stacks, queues.
Recommended Systems/Software Requirements:


Intel based desktop PC
ANSI C Compiler with Supporting Editors
Reference Books:
1. C programming and Data Structures, P. Padmanabham, Third Edition,
BS Publications
2. Mastering C, K.R. Venugopal and S.R. Prasad, TMH Publications.
3. The Spirit of C, an introduction to modern programming, M.Cooper,
Jaico Publishing House.
4. Practical C Programming, Steve Oualline, O’Reilly, SPD. TMH publications.
5. Computer Basics and C Programming, V. Raja Raman, PHI Publications.
6. Data structures and Program Design in C, R.Kruse, C.L.Tondo, B.P.Leung,
M.Shashi, Pearson Education.
Department of Computer Science and Engineering, SREYAS
Page 1
Computer Programming and Data Structures Laboratory Manual
SREYAS
SYLLABUS
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’.
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.
Department of Computer Science and Engineering, SREYAS
Page 2
Computer Programming and Data Structures Laboratory Manual
SREYAS
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 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
Department of Computer Science and Engineering, SREYAS
Page 3
Computer Programming and Data Structures Laboratory Manual
SREYAS
a) Write a C program that implements the Selection sort method to sort a given array of
integers in ascending order.
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.
Department of Computer Science and Engineering, SREYAS
Page 4
Computer Programming and Data Structures Laboratory Manual
SREYAS
Lab Program : Week 1
a) Write a C program to find the sum of individual digits of a positive integer.
Objective 1.1:
To find the sum of individual digits of a given positive number.
Description :
Sum of the individual digits means adding all the digits of a number.
e.g. If a given number is 123 then sum of digits is 1+2+3=6
Pseudo Code:
declare variables called sum, LSD, number
set sum to 0
read a number from user
if the number is not a positive number then exit
loop (number != 0)
LSD = number % 10
sum = sum + LSD
number = number / 10
end loop
print sum
Source Code:
/* To find the sum of individual digits of a given positive number.*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
int num,sum=0,new_num,temp;
clrscr();
printf("Enter the positive number........ \n");
scanf("%d",&temp);
if ( temp>0 )
num=temp;
else
exit (1);
while(temp!=0)
{
new_num=temp%10;
sum=sum+new_num;
temp=temp/10;
}
printf(" \n sum of individual digits of %d is...%d ",num,sum);
getch();
Department of Computer Science and Engineering, SREYAS
Page 5
Computer Programming and Data Structures Laboratory Manual
SREYAS
}
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.
Objective 1.2:
To print the Fibonacci series for 1 to n value
Description:
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each
subsequent number is the sum of the previous two.
e.g. 0, 1, 1, 2, 3, 5, 8, 13, 21, …
Pseudo Code :
declare variables called seed0,seed1,number,count
set seed0 to 0
set seed1 to 1
read a number from user
if the number is less than 1 then
print the Fibonacci series is not possible
else
if the number is equal to 1 then print seed0
else
if the number is equal to 2 then print seed0,seed1
else
print seed0
print seed1
set count to 1
loop (count <= number-2)
fib = seed0 + seed1
print fib
seed0 = seed1
seed1 = fib
end loop
Source Code:
/*To print the Fibonacci series for 1 to n value*/
#include <stdio.h>
#include <conio.h>
void main()
{
int num1=0, num2=1,n,counter,fab;
clrscr();
printf("\n\n\n\t\tENTER LENGTH OF SERIES FOR 1 TO N : ");
scanf("%d",&n);
if(n<1)
printf(“\n\n\n\t\ THE FIBONACCI SERIES IS NOT POSSIBLE”);
Department of Computer Science and Engineering, SREYAS
Page 6
Computer Programming and Data Structures Laboratory Manual
SREYAS
else
if(n==1)
{
printf("\n\n\t\t\t<------------------FIBONACCI SERIES------------");
printf(“\n %d”,num1);
}
else
if(n==2)
{
printf("\n\n\t<-----------FIBONACCI SERIES--------->");
printf(“\n\n\t\t%d %d”, num1,num2);
}
else
{
printf("\n\n\t\t\t<----------FIBONACCI SERIES------->");
printf("\n\n\t\t%d %d",num1,num2);
for(counter = 1; counter <= n-2; counter++)
{
fab=num1 + num2;
printf("%3d",fab);
num1=num2;
num2=fab;
}
}
getch();
}
c) Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
Objective 1.3:
To print a prime numbers up to 1 to n
Description:
Prime number is a number which is exactly divisible by one and itself only. e.g. 2, 3,5,7,
11…
Pseudo Code :
declare variables called number,start,count1 ,count
read a number from user
set start to1
loop from start to number
set count to 0
loop count1 from 1 to start
if start mod count1 = 0 then count++
end loop
if count equal to 2
print start
endif
Department of Computer Science and Engineering, SREYAS
Page 7
Computer Programming and Data Structures Laboratory Manual
SREYAS
end loop
Source Code:
/* To print a prime numbers up to 1 to n*/
#include<stdio.h>
#include<conio.h>
void main ()
{
int i, n, j, count;
clrscr();
printf(" Enter the number till which PRIME NUMBERS to be printed.....");
scanf("%d",&n);
printf(“\n\n The prime numbers 1 to %d are \n”,n);
for(i=1;i<=n;i++)
{
count=0;
for ( j=1; j<=i;j++)
{
if (i%j==0)
count++;
}
if ( count==2)
{
printf("%d ",i);
}
}
getch();
}
Department of Computer Science and Engineering, SREYAS
Page 8
Computer Programming and Data Structures Laboratory Manual
SREYAS
Lab Program : Week 2
a) Write a C program to calculate the following Sum:
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!
Objective 2.1:
To calculate the following sum:
sum=1 - x2 / 2! + x4 / 4! - x6 / 6! + x8 / 8! - x10 / 10!
Description:
Calculate the given expression for different values of x.
Pseudo Code:
start
declare variables i, j, x, y, v,f,sum
set sum to 1
set f to 1
read x
set i to 1
loop( i <= 5)
y = pow (-1, i) * pow (x, 2 * i)
f=1
set j to 1
loop( j <= 2 )
f = f * j;
v = y / f;
end loop
sum=sum+v;
end loop
print sum
stop
Source Code:
/* Write a C program to calculate the following sum
sum=1 - x2 / 2! + x4 / 4! - x6 / 6! + x8 / 8! - x10 / 10! */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
float x,y,v,f=1,sum=1;
clrscr();
printf("Enter X value\n");
scanf("%f",&x);
Department of Computer Science and Engineering, SREYAS
Page 9
Computer Programming and Data Structures Laboratory Manual
SREYAS
for(i=1;i<=5;i++)
{
y=pow(-1,i)*pow(x,2*i);
for(j=1;j<=2*i;j++)
{
f=f*j;
v=y/f;
}
sum=sum+v;
}
printf(" The sum of series is %f",sum);
getch();
}
b) Write a C program to find the roots of a quadratic equation.
Objective 2.2:
To find the roots of a quadratic equation
Description:
In Mathematics, a quadratic equation is a polynomial equation of the second degree.
The general form is
where x represents a variable or an unknown, and a, b, and c are constants
with a ≠ 0.
A quadratic equation with real or complex coefficients has two solutions, called roots.
These two solutions may or may not be distinct, and they may or may not be real.
The roots are given by the quadratic formula
where b2-4ac is called discriminant.
There are 3 cases:
1. b2 - 4ac =0 then roots are real and equal
2. b2 - 4ac >0 then roots are real and unequal
3. b2 - 4ac <0 then roots are imaginary
Pseudo Code:
read values a, b and c
if b2- 4ac >0
two distinct real roots
root1 = -b + sqrt (b * b – 4 * a * c) / 2 * a;
root2 = -b – sqrt (b * b – 4 * a * c) / 2 * a;
2
else if b - 4ac =0
two equal real roots
root1= root2 = -b/2a
else
Department of Computer Science and Engineering, SREYAS
Page 10
Computer Programming and Data Structures Laboratory Manual
SREYAS
roots are imaginary
Source Code:
/* Write a C program to find the roots of a quadratic equation */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,root1,root2,dis;
clrscr();
printf("\n Enter values of a,b,c for finding roots of a quadratic eq:\n");
scanf("%f%f%f",&a,&b,&c);
dis=b*b-4*a*c;
if(dis>0)
{
root1=-b+sqrt(dis)/2*a;
root2=-b-sqrt(dis)/2*a;
printf("\n*****ROOTS ARE REAL & UNEQUAL*****\n");
printf("\n root1=%f\n root2=%f",root1,root2);
}
else if (dis==0)
{
root1=root2=-b/2*a;
printf("\n*****ROOTS ARE REAL & EQUAL*****\n");
printf("\n root1=%f\n root2=%f",root1,root2);
}
else
printf("\n Imaginary Roots.");
getch();
}
Lab Program : Week 3
Objective 3.1:
To find the total distance travelled at regular intervals of time given the values of ‘u’ and
‘a’. The total distance travelled by vehicle in ‘t’ sec is given by distances=ut+1/2 (at2)
where ‘u’ and ‘a’ are initial velocity and acceleration.
Description:
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).
Department of Computer Science and Engineering, SREYAS
Page 11
Computer Programming and Data Structures Laboratory Manual
SREYAS
Consider two limits that is, time lower bound and time upper bound. Calculate the
distance traveled at regular time intervals decided by the user.
e.g.:
a=3.5 , u=6
time_lowerbound=2, time_upperbound=12, time_Interval=4.
Then result is:
The distance travelled in 2 seconds is 19.0
The distance travelled in 6 seconds is 99.0
The distance travelled in 10 seconds is 235.0
Pseudo Code:
start
read velocity u
read acceleration a
read lower time limit tl
read upper time limit th
read time interval ti
loop (tl < th)
distance = u * tl + 0.5 * a * tl * tl ;
print distance
th = tl + ti;
end loop
stop
Source Code:
/* To find the total distance travelled at regular intervals of time given the values of ‘u’
and ‘a’. The total distance travelled by vehicle in ‘t’ sec is given by distance
s=ut+1/2 at2 where ‘u’ and ‘a’ are initial velocity and acceleration.
*/
#include<stdio.h>
#include<conio.h>
void main ()
{
int acc,vel, timSt, timEnd, tInter, i ;
float dist;
clrscr();
printf("Enter acceleration: ");
scanf("%d",&acc);
printf("Enter the initial velocity; ");
scanf("%d",&vel);
printf("Enter the start time: ");
scanf("%d",&timSt);
printf("Enter the end time: ");
scanf("%d",&timEnd);
printf("Enter the interval: ");
scanf("%d",&tInter);
i=timSt;
while ( i <= timEnd )
{
dist = (vel* i) + (0.5 * acc * i * i);
Department of Computer Science and Engineering, SREYAS
Page 12
Computer Programming and Data Structures Laboratory Manual
SREYAS
printf("Distance travelled in %d seconds is %f\n ",i, dist);
i = i + tInter;
}
getch();
}
Objective 3 .2:
To print the result by taking two integer operands and one operator from the user,
performs the operation .( Consider the operators +,-,*,/,% and use Switch statements).
Description:
By taking any two integers and any arithmetic operator (i.e. +,-,*,/,%) from the user,
Perform operation and print the result.
Ex:
x=8,y=4
Select +: 8+4 =12
x=8,y=3
Select %: 8%4=2
Pseudo Code:
start
read two operands
display the operators for selection
using case perform the desired operation
stop
Source Code:
/* 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 statements)
*/
#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,x;
char ch;
clrscr();
printf("Enter the values of a and b...... ");
scanf("%d%d",&a,&b);
printf(" 1.'+' for Addition \n “);
printf(“ 2.'-' for Subtraction \n);
printf(“ 3.'*' for Multiplication \n”);
printf(“ 4.'/' for Divison \n”);
printf(“ 5.'%' for Modulus Divison \n");
printf("\n Enter the operator..... ");
scanf(" %c",&ch);
switch (ch)
Department of Computer Science and Engineering, SREYAS
Page 13
Computer Programming and Data Structures Laboratory Manual
SREYAS
{
case '+' :
case '-' :
case '/' :
case '%' :
case '*' :
default :
x=a+b;
printf("\n Sum of two values is..... %d",x);
break;
x=a-b;
printf("\n Subtraction of two values is..... %d",x);
break;
x=a/b;
printf("\n Divison of two values is..... %d",x);
break;
x=a%b;
printf("\n Modulus Divison of two values is..... %d",x);
break;
x=a*b;
printf("\n Product of two values is..... %d",x);
break;
printf(" Invalid option....... ");
}
getch();
}
Lab Program : Week 4
Objective4 .1:
To find factorial of a number using non recursive function.
Description:
Factorial of a given number ‘n’ is: n X (n-1) X (n – 2) X (n – 3) X (n -4) ….X 1.
e.g. factorial of 5 is: 5 X 4 X 3 X 2 X 1 = 120
Pseudo Code - main program:
start
declare n and d
read n
d = factorial (n)
print d
stop
Pseudo Code for Factorial Function using iteration:
start
declare n = 1, i
for i = 1, i <= n, i++
n=n*i
return n
stop
Source Code:
/* To find factorial of a number using non recursive function.*/
Department of Computer Science and Engineering, SREYAS
Page 14
Computer Programming and Data Structures Laboratory Manual
SREYAS
#include<stdio.h>
#include<conio.h>
int factorial( int x)
{
int n=1,i;
for ( i=1; i<=x; i++)
{
n=n*i;
}
return n;
}
void main ()
{
int num, fact;
clrscr ();
printf("Enter the number ....... ");
scanf("%d",&num);
fact=factorial(num);
printf("\nThe factorial of the number %d is ..... %d",num,fact);
getch();
}
Pseudo Code for Factorial Function using recursion:
factRecurse(n)
start
if(n == 0)||(n==1)
return 1
else
return (n * factRecurse(n - 1))
stop
Source Code:
/* To find factorial of a number using recursive function.*/
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f;
if (n==0)
return(1);
else
f=n*fact(n-1);
return(f);
}
void main()
{
int n;
Department of Computer Science and Engineering, SREYAS
Page 15
Computer Programming and Data Structures Laboratory Manual
SREYAS
clrscr();
printf(" Enter the number :\n");
scanf("%d",&n);
printf("\n Factorial of Number : %d",fact(n));
getch();
}
Objective4.2:
To find GCD of a number using non-recursive functions.
Description:
Greatest Common Divisor (GCD) of two numbers m, n will be the common greatest
factor of m and n.
Ex: Let m=15 and n=30. Factors of 15 are 1,3,5,15. Factors of 30 are 1,2,3,5,6,15,30.
Here the common factors are 1,3,5,15. So, GCD is 15.
main program:
start
declare a, b, f
read a and b
f = gcd (a, b)
print f
//prints function return value
stop
Pseudo Code for gcd:
start
declare m, n value
while m!= n
if m>n
m=m-n
else
n=n-m
end while
return m
stop
Source Code:
/* To find GCD of a number using non-recursive functions*/
#include<stdio.h>
#include<conio.h>
int gcd_nonrec ( int m, int n )
{
while ( m!=n)
{
if (m>n)
(m-=n);
Department of Computer Science and Engineering, SREYAS
Page 16
Computer Programming and Data Structures Laboratory Manual
SREYAS
else
(n-=m);
}
return m;
}
void main ()
{
int n1,n2,GCD;
clrscr ();
printf("Enter the numbers ....... ");
scanf("%d%d",&n1,&n2);
GCD=gcd_nonrec(n1,n2);
printf("\nThe GCD of the numbers %d & %d is ..... %d",n1,n2,GCD);
getch();
}
Euclid's Algorithm:
for m >= n, gcd (m, n) = n if n divides m with no remainder
else gcd (n, remainder of m/n)
start
gcd (n, m)
declare m, n value
if ((m % n) == 0)
return n;
else
return gcd(n, m % n);
stop
Source Code:
/* Euclid's Algorithm */
#include<stdio.h>
#include<conio.h>
int gcd_euclid ( int m, int n )
{
if ( (m%n)==0 )
return n;
else
return gcd_euclid(n,m%n);
}
void main ()
{
int n1,n2,GCD;
clrscr ();
printf("Enter the numbers ....... ");
scanf("%d%d",&n1,&n2);
GCD=gcd_euclid(n1,n2);
printf("\nThe GCD of the numbers %d & %d is ..... %d",n1,n2,GCD);
Department of Computer Science and Engineering, SREYAS
Page 17
Computer Programming and Data Structures Laboratory Manual
SREYAS
getch();
}
Dijkstra's Algorithm:
for m, n >0 , gcd (m, n) = m if m ==n
gcd (m-n, n) if m > n
gcd (m, n-m) if m < n
start
gcd (m, n)
declare m, n value
if(m == n)
return m;
else if (m > n)
return gcd(m-n, n);
else
return gcd(m, n-m);
stop
Objective 4.3:
To solve Tower of Hanoi problem by using recursive function.
Description:
The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in
1883. The problem has an elegant solution through recursion. In the problem, three pegs,
A, B and C exist.
‘n’ disks of differing diameters are placed on peg A so that the larger disk is always
below a smaller disk. The objective is to move all the disks to peg C using peg B as
auxiliary. Only the top disk on any peg may be moved to any other peg, and the larger
disk may never rest on a smaller one.
The recursive solution involves the following steps :
1. if n==1, move the single disk from A to C and stop.
2. Move the top n-1 disks from A to B, using C as auxiliary.
3. Move the remaining disk from A to C.
4. Move the n-1 disks from B to C, using A as auxiliary.
For a value of n = 3 the following diagram represents the end solution.
Department of Computer Science and Engineering, SREYAS
Page 18
Computer Programming and Data Structures Laboratory Manual
SREYAS
Pseudo Code for Tower of Hanoi :
towers (disk, source, spare, dest)
start
if disk == 1
move disk from source to dest
else
moveTower(disk - 1, source, spare, dest)
move disk from source to dest
moveTower(disk - 1, spare, dest, source)
stop
Source Code:
/* To solve Tower of Hanoi problem using recursive function */
#include<stdio.h>
#include<conio.h>
void towers (int n, char A, char B, char C);
void main()
{
int n;
clrscr();
printf("\n\t\t\tEnter no of disks:");
scanf("%d",&n);
if(n<1)
{
Department of Computer Science and Engineering, SREYAS
Page 19
Computer Programming and Data Structures Laboratory Manual
SREYAS
printf("\n >>>>>>NO DISKS<<<<<<\n");
getch();
exit(0);
}
towers(n,'A','C','B');
getch();
}
void towers (int n, char A, char B, char C)
{
/* If only 1 disk, make the move and return */
if(n==1)
{
printf ("\n\tMove disk 1 from peg %c to peg %c", A, B);
return;
}
else
{
/* Move top n-1 disks from A to C, using B as auxiliary */
towers (n-1, A, C, B);
/* Move remaining disks from A to C */
printf ("\n \t Move disk %d from peg %c to peg %c", n, A, B);
/* Move n-1 disks from C to B using A as auxiliary */
towers (n-1, C, B, A);
}
}
Department of Computer Science and Engineering, SREYAS
Page 20
Computer Programming and Data Structures Laboratory Manual
SREYAS
Lab Program : Week 5
Objective 5.1:
To find both the largest and smallest number in a list of integers.
Description:
It is required to find the largest and smallest numbers in a one dimensional array and
display them.
e.g.: Enter size of array: 5
Enter the elements of array: 34, 45, 23, 8, 78
Smallest no is: 8
Largest no is: 78
Pseudo Code:
start
declare an array ar.
read the size of the array
loop i=0 to i=size-1
read the elements from the user
end loop
Min = ar[0], Max = ar[0]
loop i=0 to i=size – 1
if ar[i] < Min
Min = ar[i]
if ar[i] > Max
Max = ar[i]
end loop
print Max and Min
stop
Source Code:
/* To find both the largest and smallest number in a list of integers.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,n,min,max;
clrscr();
printf("Enter Size of Array\n");
scanf("%d",&n);
printf("Enter Elements into Array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
max=0;
Department of Computer Science and Engineering, SREYAS
Page 21
Computer Programming and Data Structures Laboratory Manual
SREYAS
for(i=0;i<n;i++)
{
if(a[i]<min)
min=a[i];
if(a[i]>max)
max=a[i];
}
printf(" min is %d \n max is %d",min,max);
getch();
}
Objective 5.1a :
To find both the largest and smallest number in a list of integers using functions.
Pseudo Code:
start main
use functions for
1.
2.
3.
4.
5.
initialize the array from User.
print the array.
find Minimum
find Maximum
print Minimum and maximum
stop main
Source Code:
/* To find both the largest and smallest number in a list of integers usinfunctions.*/
#include<conio.h>
#include<stdio.h>
void input (int a[10])
{
for(int i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
}
void display (int a[10])
{
for(int i=0; i<5; i++)
{
printf("\t%d",a[i]);
}
}
int max (int a[10], int big)
{
for(int i=1; i<5; i++)
{
if ( big<a[i] )
big=a[i];
}
Department of Computer Science and Engineering, SREYAS
Page 22
Computer Programming and Data Structures Laboratory Manual
SREYAS
return big;
}
int min (int a[10], int small )
{
for(int i=1;i<5;i++)
{
if ( small>a[i] )
small=a[i];
}
return small;
}
void display_max_min ( int large, int small )
{
printf("\n\nLargest number is :
%d\n",large);
printf("\nSmallest number is :
%d",small);
}
void main ()
{
int i,nums[5],large,small;
clrscr();
printf("\nENTER THE NUMBERS..................");
input ( nums );
printf(" Numbers are..... : \n\n\t ");
display ( nums );
small=large=nums[0];
large=max ( nums, large );
small=min ( nums, small );
display_max_min ( large, small );
getch();
}
Objective 5.1(b) :
To perform addition and multiplication of two matrices by using functions.
Description:
In Mathematics, a matrix is a rectangular array of numbers, symbols, or expressions.
The individual items in a matrix are called its elements or entries.
Matrices of the same size can be added or subtracted element by element.
A (m x n)
B (m x n)
A + B (m x n)
C (m x n)
1 3 1
0 0 5
1+0 3+0 1+5
1 3 6
1 0 0
7 5 0
1+7 0+5 0+0
8 5 0
Two matrices can be multiplied only when the number of columns in the first equals the
number of rows in the second.
Multiply elements of each row by elements of each column.
A (m x n)
B (n x p)
AXB
C (m x p)
Department of Computer Science and Engineering, SREYAS
Page 23
Computer Programming and Data Structures Laboratory Manual
SREYAS
2
4
6
-3
5
0
1 0
-2 1
(2)(1) + (-3)(-2) (2)(0) + (-3)(1)
(4)(1) + (5)(-2) (4)(0) + (5)(1)
(6)(1) + (0)(-2) (6)(0) + (0)(1)
8 -3
-6 5
6 0
Pseudo Code for Addition of the matrix:
start
declare matrices A, B and C
declare variables for loop
read the size of matrixA
loop i=0 to rowmax-1
loop j=0 to colmax-1
read matrixA
read the size of matrix
loop i=0 to rowmax-1
loop j=0 to colmax-1
read matrix
loop i=0 to rowmax-1
loop j=0 to colmax-1
SumMatrixAB and store in C
C[i][j] = A[i][j] + B[i][j];
verify matrixC
stop
Pseudo Code for multiplication of the matrix:
start
declare matrices A, B and C
declare variables for loop
read the size of matrixA
loop i=0 to rowmax-1
loop j=0 to colmax-1
read matrixA
read the size of matrix
loop i=0 to rowmax-1
loop j=0 to colmax-1
read matrix
loop i=0 to rowmax-1
loop j=0 to colmax-1
Department of Computer Science and Engineering, SREYAS
Page 24
Computer Programming and Data Structures Laboratory Manual
SREYAS
Multiply MatrixAB and store in C
loop i=0 to rowmaxA -1
loop j=0 to colmaxB -1
C[i][j] = 0;
loop k=0 to rowmaxB - 1
C [i][j] = C[i][j] + A[i][k] * B[k][j];
verify matrixC
stop
Source Code:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n,p,q;
printf(“ENTER ROW AND COLUMN OF A MATRIX \n”);
scanf(“%d%d”,&n,&m);
printf(“ENETR ROW AND COLUMN OF B MATRIX \n”);
scanf(“%d%d”,&p,&q);
if((n==p)&&(m==q))
{
printf(“MATRIX CAN BE ADDED \n”);
printf(“enter a matrix \n”);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf(“%d”,&a[i][j]);
printf(“ENTER B MATRIX \n”);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf(“%d”,&b[i][j]);
printf(“SUM OF A AND B MATRICES \n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
c[i][j]=a[i][j]+b[i][j];
}
Department of Computer Science and Engineering, SREYAS
Page 25
Computer Programming and Data Structures Laboratory Manual
SREYAS
printf("\nThe Addition of two matrix is\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<m;j++)
printf("%d\t",c[i][j]);
}
}
else
printf(“MATRICES CAN NOT BE ADDED \N”);
}
OUTPUT:
ENTER ROW AND COLUMN OF A MATRIX
33
ENETR ROW AND COLUMN OF B MATRIX
33
MATRIX CAN BE ADDED.
ENETR A MATRIX.
123
456
789
ENETR B MATRIX
123
456
789
SUM OF A AND B MATRICES:
2 4 6
8 10 12
14 16 18
Source Code: multipication of matrix
#include<stdio.h>
#include<conio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int m,n, i, j, k, l,g;
printf("Enter the number of rows and column of first matrix\n");
scanf("%d%d",&m,&n);
printf("\nEnter the elements of first %dx%d matrix\n",m,n);
for (i=0; i< m; i++)
{
for(j=0; j<n; j++)
{
Department of Computer Science and Engineering, SREYAS
Page 26
Computer Programming and Data Structures Laboratory Manual
SREYAS
scanf("%d",&a[i][j]);
}
}
s1 : printf("\nEnter the number of rows and column of second matrix\n");
scanf("%d%d",&g,&l);
if(n!=g)
{
printf("\nIn matrix multiplication first column and second row
number should be the same \n");
getch();
goto s1;
}
printf("\nEnter the elements of second %dx%d matrix",n,l);
for(i = 0; i <n; i++)
{
for (j = 0; j < l; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("\nThe first matrix is :-\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("\t%d", a[i][j]);
}
printf("\n");
}
printf("\nThe second matrix is :-\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < l; j++)
{
printf("\t%d", b[i][j]);
}
printf("\n");
}
printf("\nMultiplication of the two matrices=\n");
for (i = 0;i < m; i++)
{
printf("\n");
for (j = 0; j < l; j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j] = c[i][j]+a[i][k] * b[k][j];
printf("\t%d", c[i][j]);
Department of Computer Science and Engineering, SREYAS
Page 27
Computer Programming and Data Structures Laboratory Manual
SREYAS
}
}
getch();
}
OUTPUT:
ENTER ROW AND COLUMN OF A MATRIX
33
ENETR ROW AND COLUMN OF B MATRIX
33
MATRIX CAN BE ADDED.
ENETR A MATRIX.
123
456
789
ENETR B MATRIX
123
456
789
MULTIPICATION OF A AND B MATRICES:
30 36 42
66 81 96
102 126 150
Department of Computer Science and Engineering, SREYAS
Page 28
Computer Programming and Data Structures Laboratory Manual
SREYAS
Lab Program: Week 6
Objective 6.1:
To insert a sub string into given main string from a given position.
Description:
In this program we insert any sub string into given string from a given position.
e.g.: First string cplab
Second string ds
Enter position: 2
Result is cpdslab
Pseudo Code:
start
declare string variables for first string, second string and output string
get first string
get second string
get position
split first string using strncpy
use strcpy and strcat to generate output string
stop
Source Code:
/* Functions to insert a sub string into given main string from a given position*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20],str1[20],str2[20]="";
int n;
clrscr();
printf("enter string\n");
gets(str);
printf("enter second string\n");
gets(str1);
Department of Computer Science and Engineering, SREYAS
Page 29
Computer Programming and Data Structures Laboratory Manual
SREYAS
printf(" enter the position where the substring is to be inserted \n");
scanf("%d",&n);
strncpy(str2,str,n);
strcat(str2,str1);
strcat(str2,str+n);
puts(str2);
getch();
}
Objective 6.2:
To delete n characters from a given position in a given string.
Description:
In this program we need to delete n chars form a given position in a string.
e.g.: Enter string is cpdslab
Enter position is: 2
The number of characters to be deleted: 2
Result is: cplab
Pseudo Code:
start
declare string variables for first string.
declare position and number of characters to be deleted.
get first string
get position and number
use strcpy to generate output string.
stop
Source Code:
/* To delete n characters from a given position in a given string.*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20],str2[20]="";
int n,pos;
clrscr();
printf("enter string\n");
gets(str);
printf("enter position\n");
scanf("%d",&pos);
printf(" enter number of characters to be delete");
scanf("%d",&n);
strncpy(str2,str,pos);
strcat(str2,str+pos+n);
puts(str2);
getch();
}
Department of Computer Science and Engineering, SREYAS
Page 30
Computer Programming and Data Structures Laboratory Manual
SREYAS
Objective 6.3:
To determine if the given string is a palindrome or not.
Description:
A palindrome is a string or a number that can be read the same way in either direction.
e.g.: “madam”
Pseudo Code:
start
declare string variables for string
get string
use strrev and strcmp to determine string is palindrome
stop
Source Code:
/* To write a program to determine if the given string is a palindrome or not.*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int temp;
char str[20],str1[20];
clrscr();
printf(" Enter a string : ");
gets(str);
strcpy(str1,str);
strrev(str1);
temp=strcmp(str1,str);
if ( temp==0 )
printf("\n\n Entered string is a palindrome");
else
printf("\n\n Entered string is not a palindrome");
getch();
}
Lab Program: Week 7
Objective 7.1:
To display the position or index of the string S where the string T begins, or -1 if S
doesn’t contain T.
Department of Computer Science and Engineering, SREYAS
Page 31
Computer Programming and Data Structures Laboratory Manual
SREYAS
Description:
In this program we display the position of string S where the string T begins, if S doesn’t
contain T display -1.
e.g.: S string is cpdslab
T string is ds
The position of T begins in S string is 2
Pseudo Code:
start
declare S [30], T [30], found
read string S
read string T
found = strstr(S,T)
if (found)
print position
else
print -1
stop
Source Code:
/* To display the position or index of the string S where the string T begins, or -1
if S doesn’t contain T.
*/
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
puts("Enter the first string: ");
gets(s);
puts("Enter the string to be searched: ");
gets(t);
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();
}
Objective 7.2:
To count the lines, words and characters in a given text.
Department of Computer Science and Engineering, SREYAS
Page 32
Computer Programming and Data Structures Laboratory Manual
SREYAS
Description:
In this program we will read text and we will find and display no. of lines, words and
characters in that given text.
e.g.: Text:
sreyas institute of engineering & technology
besides indu aranya
No. of lines = 2
No of words = 9
No of characters =62
Pseudo Code:
start
read the text until an empty line.
compare each character with newline char ‘\n’ to count number of lines.
compare each character with tab char ‘\t’ or space char ‘ ‘ to count number
of words.
compare first character with NULL char ‘\0’ to find the end of text.
number of characters = length of each line of text.
print number of lines, number of words, number of chars.
stop
Source Code:
/* Write a C program to count the lines, words and characters in a given text.*/
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
char ch;
int line=0,chars=0, words=0;
clrscr();
printf(" Enter text\n");
while((ch=getchar())!=EOF)
{
chars++;
if(ch=='\n')
line++;
if(ch=='\t' || ch=='\n'|| ch==' ')
words++;
}
printf(" no of lines are %d\n no of words are %d \n no of characters are
%d",line,words, chars);
getch();
}
Department of Computer Science and Engineering, SREYAS
Page 33
Computer Programming and Data Structures Laboratory Manual
SREYAS
Lab Program: Week 8
Objective 8.1:
To generate and display Pascal triangle.
Description :
In this program we generate and display the Pascal triangle. Pascal triangle is a triangle of
numbers in which a row represents the coefficients of the binomial series. The triangle is
bordered by ones on the right and left sides, and each interior entry is the sum of the two
entries above.
e.g.: Pascal triangle with 5 rows
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Pseudo Code :
start
declare a[30],t[30], i,j,n,spec=25,k;
read n
set i to 0
loop i=0; until i<n
loop k=spec-(2*i); until k>0
print space
end loop
loop j=0;until j<=i
if (j==0||i==j)
a[i][j]=1;
else
a[i][j]=a[i-1][j-1]+a[i-1][j]
print a[i][j]
end loop
print new line
end loop
stop
Source Code:
/* To generate and display Pascal triangle */
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[30][30],i,j,k,n,spec=25;
clrscr();
printf("Enter the value of n : ");
scanf("%d",&n);
for ( i=0; i<n; i++ )
{
for ( k=(spec-(2*i)); k>0; k-=2 )
{
Department of Computer Science and Engineering, SREYAS
Page 34
Computer Programming and Data Structures Laboratory Manual
SREYAS
printf(" ");
}
for ( j=0; j<=i; j++ )
{
if ( j==0 || j==i )
a[i][j]=1;
else
a[i][j]=a[i-1][j-1]+a[i-1][j];
printf("%d ",a[i][j]);
}
printf("\n");
}
getch();
}
Objective 8.2:
To generate and display a pyramid of numbers.
Description :
In this program we will generate and display a pyramid of numbers
e.g. pyramid of numbers having 3 rows
0
101
21012
Pseudo Code :
start
declare pyramid ( int ),n
read n
call pyramid(n)
in pyramid(n) definition, declare i ,j
set i to 0
loop i<n
set j to n-1
loop j>i
print spaces
decrement j by1
end loop
set j to i
loop j>=0
print j value
decrement j by 1
end loop
set j to 1
loop j<i
print j value
increment j by 1
print new line
increment i by 1
end loop
stop
Source Code:
Department of Computer Science and Engineering, SREYAS
Page 35
Computer Programming and Data Structures Laboratory Manual
SREYAS
/* To generate and display a pyramid of numbers*/
#include<stdio.h>
#include<conio.h>
void pyramid ( int );
void main ()
{
int n;
clrscr();
printf(" Enter the value of n : ");
scanf("%d",&n);
pyramid(n);
getch();
}
void pyramid ( int n )
{
int i,j;
for ( i=0; i<n; i++ )
{
for ( j=n-1; j>i; j-- )
printf(" ");
for ( j=i; j>=0; j-- )
printf(" %d",j);
for ( j=1; j<=i; j++ )
printf(" %d",j)
printf("\n");
}
}
Lab Program: Week 9
Objective:
To read in two numbers, x and n, and then compute the sum of this geometric progression:
1 + x + x2 + x3 +………….+ xn
Description:
1 + x + x2 + x3 +………….+ xn
For example: if n is 3 and x is 5, then the program computes
1+5+25+125.
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.
Pseudo Code:
start
declare variables sum, x, n, i
loop
read values of x, n
if x < 0 or n < 0 continue
Department of Computer Science and Engineering, SREYAS
Page 36
Computer Programming and Data Structures Laboratory Manual
SREYAS
end loop
sum = 1
loop from i=1 to n
accumulate sum using power function
end loop
print sum
stop
Source Code:
/* 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
*/
#include<conio.h>
#include<math.h>
#include<stdio.h>
void main ()
{
float sum=1,x;
int i,n;
clrscr();
do
{
printf(“Enter +ve values\n”);
printf(" Enter the value of 'x' : ");
scanf("%f",&x);
printf(" Enter the value of 'n' : ");
scanf("%d",&n);
}
while ( x<0 || n<0 );
for ( i=1; i<=n; i++ )
{
sum+=pow(x, i);
}
printf(" Geometric Progression is : %.2f",sum);
getch();
}
Department of Computer Science and Engineering, SREYAS
Page 37