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

CP Lab Manual

This document provides code and algorithms to find the greatest common divisor (GCD) of two integers using both recursive and non-recursive functions in C. It includes pseudocode for the recursive Euclidean algorithm to find the GCD by repeatedly dividing the larger number by the smaller number and setting the dividend and divisor equal to the previous divisor and remainder. It also provides non-recursive code that finds the GCD by repeatedly subtracting the smaller of the two numbers from the larger number until they are equal. The document contains example code implementing both approaches to find the GCD.

Uploaded by

Vikas Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
228 views

CP Lab Manual

This document provides code and algorithms to find the greatest common divisor (GCD) of two integers using both recursive and non-recursive functions in C. It includes pseudocode for the recursive Euclidean algorithm to find the GCD by repeatedly dividing the larger number by the smaller number and setting the dividend and divisor equal to the previous divisor and remainder. It also provides non-recursive code that finds the GCD by repeatedly subtracting the smaller of the two numbers from the larger number until they are equal. The document contains example code implementing both approaches to find the GCD.

Uploaded by

Vikas Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 81

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept.

of IT */
Week1a

Page:1 */

Problem Definition: Write a C program to find sum of individual digits of a positive


integer.
ALGORITHM
1.
2.
3.
4.

START
READ NUM
SUMDIGIT=0
DO WHILE NUM > 0
4.1 SUMDIGIT=SUMDIGIT + NUM MOD 10
4.2 NUM=NUM/10
5. END WHILE
6. PRINT NUM
7. END.
CODE:
/*Week1a.c */
#include <stdio.h>
#include <conio.h>
int main()
{
long num;
int sumdigit=0;
clrscr();
printf("Enter a positive integer : ");
scanf("%ld",&num);
while(num>0)
{
sumdigit = sumdigit + num % 10;
num = num / 10;
}
printf("Sum of individual digits = %d\n",sumdigit);
getch();
return (0);
}
Output:
Enter a positive integer : 23456
Sum of individual digits = 20

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week1b

Page:2 */

Problem Definition:
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..
Understanding Problem:
Fibonacci series is:
0
1
1
2
3
5
8
Where current number is sum last two numbers

13

21

34

55

ALGORITHM:
1
2
3
4
5
6

7
8

START
FIRST=0
SECOND=0
PRINT FIRST, SECOND
INPUT N
FOR X = 2 TO N
6.1 CURRENT = FIRST + SECOND
6.2 PRINT CURRENT
6.3 FIRST=SECOND
6.4 SECOND=CURRENT
NEXT X
END.

CODE:

/*week1b.c*/
#include <stdio.h>
main()
{
long first,second,current;
int n,x;
clrscr();
printf("How many numbers of Fibonacci series? : ");
scanf("%d",&n);
first=0; second=1;
printf("%10ld%10ld",first,second);
for(x=2;x<=n;x++)
{
current=first+second;
printf("%10ld",current);
first=second;
second=current;
}
return (0);
}
Output:
How many numbers of Fibonacci series? : 20
0
1
1
2
3
5
8
377
610
987
1597
2584 4181

13
6765

21

34

55

89

144

233

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week1c

Page:3 */

Problem Definition:
Write a C program to generate all prime numbers between 1 and n, where n is a value supplied
by the user
Understanding the problem and process logic:
A number is prime if it exactly divisible only by 1 and number itself. We can check the divisibility
from 1 to number to find total number of factors whether it is 2 or more.
Mathematicians suggest, if a number is not exactly divisible from 2 to integer value of square
root of number then it can be declared as prime. So to reduce the number of comparisons we
will check the divisibility from 2 to square root of the number.
We will set the prime as true first before checking divisibility. If any divider is found we can set
the prime false and terminate the loop. Checking the status of variable prime we can declare
whether it is prime or not.
One outer loop is required to feed the number within the range each time to be checked by inner
loop.
ALGORITHM
1
2
3
4

START
ACCEPT N
(RANGE)
PRINT PRIME NUMBERS FROM 1 TO N, N
FOR NUM = 2 TO N
4.1 PRIME=TRUE
4.2 FOR D = 2 TO SQRT(N)
4.2.1 IF N MOD D = 0 THEN
4.2.1.1 PRIME=FALSE
4.2.1.2 BREAK
4.2.2 ENDIF
4.3 NEXT D
4.4 IF PRIME=TRUE THEN
4.4.1 PRINT NUM
4.5 ENDIF
5 NEXT NUM
6 END

(TERMINATE INNER LOOP)

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


CODE:
/* Week1c.c */
#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
long int n,num,d;
char prime;
printf("Enter range for prime numbers from 1 to ..: ");
scanf("%ld",&n);
for(num = 2; num <= n; num++)
{
prime = 't';

Page:4 */

for(d = 2; d <= sqrt(num); d++)


if(num % d == 0)
{ prime = 'f'; break ; }
if(prime=='t')
printf("%10ld",num);
}
return (0);
}
Output:
Enter range for prime numbers from 1 to ..: 1000
2
3
5
7
11
19
23
29
31
37
41
53
59
61
67
71
73
89
97
101
103
107
109
131
137
139
149
151
157
173
179
181
191
193
197
223
227
229
233
239
241
263
269
271
277
281
283
311
313
317
331
337
347
359
367
373
379
383
389
409
419
421
431
433
439
457
461
463
467
479
487
503
509
521
523
541
547
569
571
577
587
593
599
613
617
619
631
641
643
659
661
673
677
683
691
719
727
733
739
743
751
769
773
787
797
809
811
827
829
839
853
857
859
881
883
887
907
911
919
941
947
953
967
971
977
997

13
43
79
113
163
199
251
293
349
397
443
491
557
601
647
701
757
821
863
929
983

17
47
83
127
167
211
257
307
353
401
449
499
563
607
653
709
761
823
877
937
991

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week2a

Page:5 */

Problem Definition:
Write a C program to calculate the following sum:
sum= 1 x2/2! + x4/4! x6/6! + x8/8! x10/10!
Understanding Problem and Process Logic:
First the sum is to initialized 1 then loop will run from 2 to 10 in step 2. First, third and fifth time
the term is to subtracted and second and fourth time it is to be added. So if a variable c should
be initialized to 1 and will be incremented by 1 in each iteration. Checking the status of c MOD 2
(0 or 1), the term will added or subtracted. Within the loop power and factorial are to be
computed. For power we can use pow ( ) function and for factorial we can use an inner loop.
ALGORITHM:
1
2
3
4
5

START
SUM=1
INPUT X
C=1
FOR A = 2 TO 10 STEP 2
5.1 B=A
5.2 F=1
5.3 DO WHILE B >= 1
5.3.1 F=F*B
5.3.2 B=B-1
5.4 END WHILE
5.5 IF C MOD 2 = 0 THEN
5.5.1 SUM=SUM+POWER(X,A)/F
5.6 ELSE
5.6.1 SUM=SUM-POWER(X,A)/F
5.7 ENDIF
5.8 C=C+1
6 NEXT A
7 PRINT SUM
8 END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */

Page:6 */

CODE:
/*Week2a.c*/
#include <stdio.h>
#include <math.h>
#include <conio.h>
main()
{
int a,b;
long int f;
int c;
float x,sum=1.00;
clrscr();
printf("Enter value of x : ");
scanf("%f",&x);
c=1;
for(a=2;a<=10;a+=2)
{
b=a;/* to find factorials of 2,4,6,8 and 10 */
f=1;
while(b>=1)
{
f*=b;
b--;
}
/* factorial of b is calculated in f */
if(c%2==0)
sum=sum+pow(x,a)/f; /* when factorial of 4 & 8 */
else
sum=sum-pow(x,a)/f; /* when factorial of 2, 6 & 10 */
c++;
}
printf("Sum = %.3f\n",sum);
return (0);
}
Output:
Enter value of x : 4
Sum = -0.686

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week2b
Problem Definition:
Write a C program to find roots of a quadratic equation
ALGORITHM
1
2
3
4

START
INPUT A, B, C
DESCR=B*B - 4*A*C
IF DESCR < 0 THEN
4.1 PRINT ROOTS ARE IMAGINARY
5 ELSE
5.1 R1=(-B+SQRT(DESCR))/(2*A)
5.2 R2=(-B-SQRT(DESCR))/(2*A)
5.3 PRINT R1, R2
6 ENDIF
7 END.
CODE:
/*Week2b.c */
#include <stdio.h>
#include <math.h>
#include <conio.h>
main()
{
float a,b,c,descr,r1,r2;
clrscr();
printf("Enter values of a,b & c : ");
scanf("%f%f%f",&a,&b,&c);
descr=b*b-4*a*c;
if(descr<0)
printf("Roots are imaginary\n");
else
{
r1=(-b+sqrt(descr))/(2*a);
r2=(-b-sqrt(descr))/(2*a);
printf("Root1 = %.3f Root2 = %.3f\n",r1,r2);
}
return (0);
}
Output:
Enter values of a,b & c : 4 12 5
Root1 = -0.500 Root2 = -2.500

Page:7 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week3i

Page:8 */

Problem Definition:
Write a C program that use both recursive and non recursive functions:
i. to find factorial of a given number
Understanding the problem and process logic:
Recursion is a process where a function calls itself. C language supports recursion.
If n! = n*(n-1)*(n-2)*..1
It can be written as
n! = n*(n-1)!
Means
Factorial(n) = n*factorial(n-1)
To find factorial by non-recursive function we will use loop to find
n! = n*(n-1)*(n-2)*..1
ALGORITHM ( USING RECURSION)
1. FACTORIAL1(N)
2. IF N= 0 OR N = 1 THEN
3.1. RETURN 1
3. ELSE
4.1 RETURN (N*FACTOIAL1(N-1))
4. ENDIF
ALGORITHM (USING NON-RECURSIVE FUNCTION )
1. FACTORIAL2(N)
2. F=1
3. FOR X = N TO 1 STEP 1
1.1 F=F*X
4. NEXT X
5. RETURN F
ALGORITHM OF MAIN FUNCTION
1.
2
3
4
5

START
INPUT N
PRINT FACTORIAL OF , N , BY RECURSIVE FUNCTION= , FACTORIAL1(N)
PRINT FACTORIAL OF , N , BY NON-RECURSIVE FUNCTION= , FACTORIAL1(N)
END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


CODE:

Page:9 */

/*Week3i.c */
#include <stdio.h>
#include <conio.h>
/* recursive function*/
long int factorial(int n)
{
if(n<=1)
return (1);
else
return (n*factorial(n-1));
}
/* non-recursive function */
void FACTORIAL(int n)
{
long int f=1;
int k;
for(k=n;k>=1;k--)
f*=k;
printf("Factorial of %d (by non-recursive function)= %ld\n",n,f);
}
main()
{
int n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Factorial of %d (by recursive function) = %ld\n",
n,factorial(n));
FACTORIAL(n); /* calling non-recursive function */
getch();
return (0);
}
Output:
Enter a number : 7
Factorial of 7 (by recursive function) = 5040
Factorial of 7 (by non-recursive function)= 5040

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


WEEK3II

Page:10 */

TO FIND GCD OF TWO GIVEN INTEGERS


GENERAL EUCLIDS ALGORITHM TO FIND GCD OF 2 INTEGERS
STEP 1: CALL THE LARGER VALUE I AND THE SMALLER VALUE J.
STEP 2: DIVIDE I BY J AND CALL THE REMAINDER R.
STEP 3: IF R IS NOT 0, THEN
RESET I TO THE VALUE OF J
RESET J TO THE VALUE OF R
GO BACK TO STEP 2
STEP 4: PRINT OUT THE ANSWER, WHICH IS THE VALUE OF J
Process logic: We can call I and J dividend and divider also. In recursion divider will be
received as dividend and remainder will be received as divider.
We can use following logic also for the same concept:
1. START
2. INPUT N1, N2
3. DO WHILE (N1 != N2)
3.1 IF N1 > N2 THEN
3.1.1 N1=N1-N2
3.2 ELSE
3.2.1 N2=N2-N1
3.3 ENDIF
4. ENDWHILE
5. PRINT N1
(OR N2)
6. END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Code:

Page:11 */

/*Week3ii.c */
#include <stdio.h>
#include <conio.h>
/* recursive function*/
int GCD(int dividend,int divider)
{
int rem=dividend%divider;
if(rem==0)
return (divider);
else
return GCD(divider, rem);
}
/* non-recursive function */
int gcd(int n1,int n2)
{
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
return (n1);
}
main()
{
int n1,n2;
clrscr();
printf("Enter two numbers : ");
scanf("%d%d",&n1,&n2);
printf("GCD (using recursive function) = %d\n",GCD(n1,n2));
printf("gcd (using non-recursive function = %d\n",gcd(n1,n2));
getch();
return (0);
}
Output:
Enter two numbers : 230 45
GCD (using recursive function) = 5
GCD (using non-recursive function = 5

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */

Page:12 */

Week3III
Write a C program to solve Tower of hanoi problem.
Tower of Hanoi
The Tower of Hanoi (sometimes referred to as the Tower of Brahma or the End of the World
Puzzle) was invented by the French mathematician, Edouard Lucas, in 1883. He was inspired
by a legend that tells of a Hindu temple where the pyramid puzzle might have been used for the
mental discipline of young priests. Legend says that at the beginning of time the priests in the
temple were given a stack of 64 gold disks, each one a little smaller than the one beneath it.
Their assignment was to transfer the 64 disks from one of the three poles to another, with
important conditions that disk could never be placed on top of a smaller one and it will be moved
one by one. The priests started working very efficiently, day and night.
This is one of the worst case complexity example of data structure algorithms. Total number of
movements will be 264 1. if one movement can be done in one second then also it will take
nearly 600 billion years to finish the task (End of the world as myth)

Earlier it was discussed that it can be solved by recursive function and it is very tough to
solve by non-recursive function without using goto statement of C/C++. Students of data
structure can take as opportunity to get it solved by non-recursive functions with the
help of the teacher.
Algorithm ( Recursive)
1. FUNCTION HANOI(DISKS, LEFT, RIGHT, MIDDLE)
2. IF DISKS > 0 THEN
2.1 HANOI(DISKS-1, LEFT, MIDDLE, RIGHT)
2.2 PRINT MOVE DISK , DISKS, FROM , LEFT, TO , RIGHT
2.3 HANOI(DISKS-1, MIDDLE, RIGHT, LEFT)
3 ENDIF
Process Logic:
In each recursive step disk number is changed and string values for LEFT, RIGHT
and MIDDLE are changed. Internally this function will use stack to keep the statements
in it in LIFO manner.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:13 */
Code:
/*Week3iii.c*/
#include <stdio.h>
#include <conio.h>
long int moves=0;
void hanoi(int d, char l[], char r[], char m[])
{
if(d>0)
{ hanoi(d-1,l,m,r);
moves++;
printf("%10ld. Move disk %d from %s to %s\n",moves,d,l,r);
if(moves%20==0)
{ printf("--------More---------\n");
getch();
}
hanoi(d-1,m,r,l);
}
}
main()
{
int disks;
clrscr();
printf("Number of disks ? ");
scanf("%d",&disks);
printf("
Movements of the disks:\n");
hanoi(disks,"left","right","middle");
printf("Total movements = %ld\n",moves);
getch();
return (0);
}
Output:
Number of disks ? 4
Movements of the disks:
1. Move disk 1 from left to middle
2. Move disk 2 from left to right
3. Move disk 1 from middle to right
4. Move disk 3 from left to middle
5. Move disk 1 from right to left
6. Move disk 2 from right to middle
7. Move disk 1 from left to middle
8. Move disk 4 from left to right
9. Move disk 1 from middle to right
10. Move disk 2 from middle to left
11. Move disk 1 from right to left
12. Move disk 3 from middle to right
13. Move disk 1 from left to middle
14. Move disk 2 from left to right
15. Move disk 1 from middle to right
Total movements = 15

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week4a

Page:14 */

The total distance traveled by vehicle in 't' seconds is given by distance=ut+1/2at 2 where
'u' and 'a' are the initial velocity (m/sec) and acclelaration (m/sec 2). Write C program to
find the distance traveled 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'.
Algorithm:
1
2
3
4
5
6
7
8
9
10

START
T=3
(DEFAULT TIME INTERVAL IS 3 SECOND)
INPUT U,A
PRINT DO U WISH TO ENTER TIME ENTERVAL :
READ CH
IF CH = Y THEN
6.1 READ T
ENDIF
FOR INTERVALS = T TO 50 STEP T
8.1 DISTANCE=U*INTERVALS+0.5*A*INTERVALS*INTERVALS;
8.2 PRINT "DISTANCE TRAVELED , DISTANCE, METER IN , T SECONDS
NEXT INTERVAL
END.

CODE:
/*week4a.c*/
#include <stdio.h>
main()
{
float a,u,distance;
int intervals,t=3,x; /* default time interval is 3 seconds */
char ch;
printf("Enter velocity (m/sec) : ");
scanf("%f",&u);
printf("Enter acceleration (m/sec^2) : ");
scanf("%f",&a);
fflush(stdin);
printf("Do you want to give time intervals? : ");
ch=getchar();

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


if(ch=='y'||ch=='Y')
{
printf("Enter time intervals in seconds : ");
scanf("%d",&t);
}
for(intervals=t;intervals<=50;intervals+=t)
{
distance=u*intervals+0.5*a*intervals*intervals;
printf("Distance traveled = %.3f meter in %d seconds.\n",
distance,intervals);
}
return (0);
}
Output:
Enter velocity (m/sec) : 23
Enter acceleration (m/sec^2) : 5
Do you want to give time intervals? : y
Enter time intervals in seconds : 3
Distance traveled = 91.500 meter in 3 seconds.
Distance traveled = 228.000 meter in 6 seconds.
Distance traveled = 409.500 meter in 9 seconds.
Distance traveled = 636.000 meter in 12 seconds.
Distance traveled = 907.500 meter in 15 seconds.
Distance traveled = 1224.000 meter in 18 seconds.
Distance traveled = 1585.500 meter in 21 seconds.
Distance traveled = 1992.000 meter in 24 seconds.
Distance traveled = 2443.500 meter in 27 seconds.
Distance traveled = 2940.000 meter in 30 seconds.
Distance traveled = 3481.500 meter in 33 seconds.
Distance traveled = 4068.000 meter in 36 seconds.
Distance traveled = 4699.500 meter in 39 seconds.
Distance traveled = 5376.000 meter in 42 seconds.
Distance traveled = 6097.500 meter in 45 seconds.
Distance traveled = 6864.000 meter in 48 seconds.

Page:15 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:16 */
Week4b
Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result. (Consider operators +, -, /,*,% and use
switch statement
Algorithm:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

START
INPUT OPERAND1, OPERAND2
INPUT OPERATOR
DO CASE
CASE OPERATOR = +
5.1 RESULT = OPERAND1+OPERAND2
CASE OPERATOR = -
6.1 RESULT = OPERAND1-OPERAND2
CASE OPERATOR = *
7.1 RESULT = OPERAND1*OPERAND2
CASE OPERATOR = /
8.1 RESULT = OPERAND1/OPERAND2
CASE OPERATOR = %
9.1 RESULT = OPERAND1%OPERAND2
OTHERWISE
10.1
RESULT=NULL
ENDCASE
IF RESULT <> NULL THEN
12.1
PRINT RESULT IS, RESULT
ELSE
13.1
PRINT WRONG OPERATOR
ENDIF
END.

(MOD)

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Code:

Page:17 */

/*Week4b.c */
#include <stdio.h>
main()
{
int operand1, operand2,result;
char operator;
clrscr();
printf("Enter two operands (numbers) : ");
scanf("%d%d",&operand1, &operand2);
fflush(stdin);
printf("Enter operator (+, -, /, * or % ) : ");
scanf("%c",&operator);
switch (operator)
{
case '+' : result
break;
case '-' : result
break;
case '/' : result
break;
case '*' : result
break;
case '%' : result
break;
default : result
}

= operand1 + operand2;
= operand1 - operand2;
= operand1 / operand2;
= operand1 * operand2;
= operand1 % operand2;
= NULL;

if(result!=NULL) /* we can write if(answer) or if(!answer) also */


printf("Result = %d\n",result);
else
printf("Wrong operator\n");
getch();
return (0);
}
Output:
Enter two operands (numbers) : 45 23
Enter operator (+, -, /, * or % ) : %
Result = 22

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:18 */
Week5a
Write a C program to find both the largest and smallest number in a list of integers
Algorithm:
1 START
2 FOR X = 1 TO 10
2.1 READ LIST[X]
2.2 IF X=1 THEN
2.2.1 LARGEST=LIST[1]
2.2.2 SMALLEST=LIST[1]
2.3 ENDIF
2.4 IF LIST[X] > LARGEST THEN
2.4.1 LARGEST=LIST[X]
2.5 ENDIF
2.6 IF LIST[X] < SMALLEST THEN
2.6.1 SMALLEST=LIST[X]
2.7 ENDIF
3 NEXT X
4 PRINT LARGEST, SMALLEST
5 END
/*Week5a.c */
#include <stdio.h>
main()
{
int list[10],largest,smallest,x;
for(x=0;x<10;x++)
{
printf("Enter number %d : ",x+1);
scanf("%d",&list[x]);
if(x==0) { largest=smallest=list[x]; }
/* first time initialization */
if(list[x] > largest) largest = list[x];
if(list[x] < smallest) smallest = list[x];
}
printf("Largest = %d Smallest = %d\n",largest,smallest);
return (0);
}
Output:
Enter number 1 : 22
Enter number 2 : 323
Enter number 3 : 45
Enter number 4 : 567
Enter number 5 : 67
Enter number 6 : 877
Enter number 7 : 44
Enter number 8 : 3
Enter number 9 : 45
Enter number 10 : 112
Largest = 877 Smallest = 3

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week5b
Write a C program that uses functions to perform the following:
i. Addition of two matrices
ii. Multiplication of two matrices

Page:19 */

Algorithm(FOR ADDITION AND MULTIPLICATION):


1. FUNCTION ADDMAT(A[3][3], B[3][3])
2. START
3. FOR ROW = 1 TO 3
a. FOR COL = 1 TO 3
i. C[ROW][COL]=A[ROW][COL]+B[ROW][COL]
b. NEXT COL
4. NEXT ROW
5. PRINT AFTER ADDITION
6. FOR ROW = 1 TO 3
a. FOR COL = 1 TO 3
i. PRINT C[ROW][COL]
b. NEXT COL
c. PRINT NEXTLINE
7. NEXT ROW
8. END.
1. FUNCTION MULMAT(A[3][3], B[3][3])
2. START
3. FOR X = 1 TO 3
a. FOR Y = 1 TO 3
i. C[X][Y]=0
ii. FOR Z = 1 TO 3
1. C[X][Y]=C[X][Z]+A[X][Y]*B[Z][Y]
iii. NEXT Z
11.2 NEXT Y
4. NEXT X
5. PRINT AFTER MULTIPLICATION:
6. FOR ROW = 1 TO 3
a. FOR COL = 1 TO 3
i. PRINT C[ROW][COL]
b. NEXT COL
c. PRINT NEXTLINE
7. NEXT ROW
8. END.
Process Logic:
Both the functions can be called from main( ) function after accepting the matrices a and
b.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Code:
/*Week5b.c */
#include <stdio.h>

Page:20 */

void addmat(a,b)
int a[3][3], b[3][3];
{
int c[3][3],row,col;
for(row=0;row<3;row++)
for(col=0;col<3;col++)
c[row][col] = a[row][col] + b[row][col];
puts("i. After addition:");
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
printf("%5d",c[row][col]);
printf("\n");
}
}
void mulmat(a,b)
int a[3][3], b[3][3];
{
int c[3][3],x,y,z;
for(x=0;x<3;x++)
for(y=0;y<3;y++)
{
c[x][y]=0;
for(z=0;z<3;z++)
c[x][y]=c[x][y]+a[x][z]*b[z][y];
}
puts("ii. After Multiplication:");
for(x=0;x<3;x++)
{
for(y=0;y<3;y++)
printf("%5d",c[x][y]);
printf("\n");
}
}
main()
{
int a[3][3], b[3][3], x,y;
printf("Enter data for matrix a:\n");
for(x=0;x<3;x++)
for(y=0;y<3;y++)
{
printf("Row %d Col %d : ", x+1, y+1); scanf("%d",&a[x][y]);
}
printf("Enter data for matrix b:\n");

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:21 */
for(x=0;x<3;x++)
for(y=0;y<3;y++)
{
printf("Row %d Col %d : ",x+1,y+1); scanf("%d",&b[x][y]);
}
printf("
Matrix a
Matrix b\n");
for(x=0;x<3;x++)
{
for(y=0;y<3;y++)
printf("%5d",a[x][y]);
for(y=0;y<3;y++)
printf("%5d",b[x][y]);
printf("\n");
}
addmat(a,b);
mulmat(a,b);
return (0);
}
Output:
Enter data for matrix a:
Row 1 Col 1 : 2
Row 1 Col 2 : 3
Row 1 Col 3 : 4
Row 2 Col 1 : 5
Row 2 Col 2 : 6
Row 2 Col 3 : 7
Row 3 Col 1 : 8
Row 3 Col 2 : 7
Row 3 Col 3 : 6
Enter data for matrix b:
Row 1 Col 1 : 5
Row 1 Col 2 : 4
Row 1 Col 3 : 3
Row 2 Col 1 : 2
Row 2 Col 2 : 3
Row 2 Col 3 : 4
Row 3 Col 1 : 5
Row 3 Col 2 : 4
Row 3 Col 3 : 3
Matrix a
Matrix b
2
3
4
5
4
3
5
6
7
2
3
4
8
7
6
5
4
3
i. After addition:
7
7
7
7
9
11
13
11
9
ii. After Multiplication:
36
33
30
72
66
60
84
77
70

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week6a

Page:22 */

Write a C program that uses functions to perform following operations:


i. To insert a sub-string into a given string from a given position
ii. To delete n characters from given position in a given string
PROCESS LOGIC:
I. To insert a sub-string into a given string from a given position
1. INPUT STR, SUBSTR, POS
2. EXTRACT CHARACTERS FROM STARTING POSITION TO END TO TEMP
3. INSERT SUBSTRING TO STRING AT STARTING POSITION
4. APEEND TEMP IN STR
II. To delete n characters from given position in a given string
Deleting number of characters from a string should cause shifting of characters to
deleted space/overwriting characters by shifting.
Algorithm:
1.
2.
3.
4.

START
INPUT STR, POS, NCHARS
LAST=POS+NCHARS-1
DO WHILE STR[POS] != NULL
4.1. STR[POS]=STR[LAST]
4.2
POS=POS+1
4.3
LAST=LAST+1
5 ENDWHILE
6 PRINT STR
7 END.

(Overwriting characters by shifting)

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


/*Week6a.c */
#include <stdio.h>
#include <conio.h>

Page:23 */

void insertstr(char *str,char *substr,int pos)


{
char temp[20];
int j,k=0,l;
pos--;
/* to read from 0th character */
l=pos;
while(str[l]!=NULL) /* Extracting characters from position to temp */
{
temp[k]=str[l];
k++;
l++;
}
temp[k]='\0';
k=0;
while(substr[k]!=NULL) /* inserting characters at position */
{
str[pos]=substr[k];
k++;
pos++;
}
str[pos]='\0';
k=0;
while(temp[k]!=NULL) /* adding extracted characters from temp */
{
str[pos]=temp[k];
k++;
pos++;
}
str[pos]='\0';
}
void deletestr(char *str, int pos, int nc)
{
int last=pos+nc-1;
/* to shift characters after deletion */
pos--;
while(str[pos]!=NULL)
{
str[pos]=str[last];
/* shifting upto last*/
pos++;
last++;
}
str[pos]='\0';
puts(str);
}

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:24 */
main()
{
char *str,*substr= "Engg.";
int pos,nchars;
clrscr();
printf("Enter string : ");
gets(str);
printf("Enter sub-string : ");
gets(substr);
printf("Enter position to insert : ");
scanf("%d",&pos);
insertstr(str,substr,pos);
printf("The string after insertion of substring:\n");
puts(str);
printf("Enter position from where to delete characters : ");
scanf("%d",&pos);
printf("Enter number of characters to be deleted : ");
scanf("%d",&nchars);
printf("After deletion:\n");
deletestr(str,pos,nchars);
getch();
return (0);
}
Output:
Enter string : GMRIT College
Enter sub-string : Engg.
Enter position to insert : 7
The string after insertion of substring:
GMRIT Engg. College
Enter position from where to delete characters : 7
Enter number of characters to be deleted : 5
After deletion:
GMRIT College

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:25 */
Week6b
Write a C program to determine if the given string is palindrome or not.
Definition : A palindrome is a string which reverse is also same like MADAM, DAD,
MALAYALAM, ABLE WAS I ERE I SAW ELBA etc.
Algorithm:
1. INPUT STRING
2. LEN=LEGTH(STRING)
3. Q=LEN
4. PALIN=TRUE
5. FOR P = 1 TO LEN/2
5.1 IF STRING[P] <> STRING[Q] THEN
5.1.1 PALIN=FALSE
5.1.2 BREAK
(TERMINATE THE LOOP)
5.2 ENDIF
6 Q=Q-1
7 NEXT P
8 IF PALINE = TRUE THEN
8.1 PRINT YES, PALINDROM
9 ELSE
9.1 PRINT NOT PALINDROM
10 ENDIF
11 END.
/*week6b.c*/
#include <stdio.h>
void checkpalin(char word[])
{
int len,p,q,palin=1;
len=0;
while(word[len]!='\0') len++;
q=len-1;
for(p=0;p<len/2;p++)
{
if(word[p] != word[q]) { palin=0;
q--;
}
if(palin)
puts("Yes, palindrome");
else
puts("Not a palindrom");
}
main()
{
char word[50];
printf("Enter string : ");
gets(word);
checkpalin(word);
return (0);
}
Output:
Enter string : able was i ere i saw elba
Yes, palindrome

break;

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


WEEK7A

Page:26 */

Write a C program that displays the position or index in the string S where the string t
begins, or -1 if S does not contain T.
Definition: Searching a sub-string t in string s
Process Logic:
Start comparing character by character of sub-string t with s from beginning to length of s-length
of t.
Comparison will terminate if any mismatch is there.
Comparison will end up to length of t
If number of compared characters (without mismatch) is equal to length of t then t is found at
position.
This algorithm is also known as Brute-Force Algorithm
Algorithm:
1
2
3
4
5

START
INPUT S, T
L1=LENGTH(S)
L2=LENGTH(T)
FOR I = 1 TO L1-L2
5.1 J=1
5.2 K=I
5.3 DO WHILE S[K] = T[J] AND J < L2
5.3.1 K=K+1
5.3.2 J=J+1
5.4 ENDWHILE
5.5 IF J = L2 THEN
5.5.1 FOUND=TRUE
5.6 ELSE
5.6.1 FOUND=FALSE
5.7 ENDIF
6 NEXT I
7 END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


/*week7a.c */
#include <stdio.h>
int find(S,T)
char S[],T[];
{
int l1,l2,i,j,k;
l1=l2=0;
while( S[l1] != '\0') l1++;
while( T[l2] != '\0') l2++;
for ( i = 0 ; i <= l1 - l2 ; i++ )
{
j = 0 ; k = i ;
while ( ( S[k] == T[j] ) && ( j < l2 ) )
{
k++ ;
j++ ;
}
if ( j == l2 )
return (i) ;
}
return -1 ;
}
main()
{
char S[80],T[20];
int pos;
clrscr();
printf("Enter string (S) : ");
gets(S);
printf("Enter sub-string(T) to search in S : ");
gets(T);
pos=find(S,T);
printf("Position of sub-string : %d\n",pos);
getch();
return (0);
}
Output:
Enter string (S) : Paras Nath Singh
Enter sub-string(T) to search in S : Nath
Position of sub-string : 6

Page:27 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week 7b

Page:28 */

Write a C program to count lines, words and characters in a given text


Process Logic:
Input text
Count all characters from beginning to end (for number of characters)
For number words count number of blanks+1 ( Take care of contiguous blanks)
Count number of new line characters for total lines
/*week7b.c

*/

#include <stdio.h>
main()
{
char text[300];
int lines,words,nchars;
clrscr();
printf("\t\tEnter Text (^z to end):\n");
lines=words=nchars=0;
while((text[nchars]=getchar())!=EOF)
{
if(text[nchars]==' ' && text[nchars-1] != ' ')
if(text[nchars]=='\n') { lines++; words++; }
nchars++;
}
printf("\nNumber of lines = %d\n",lines+1);
printf("Number of words = %d\n",words+1);
printf("Number of characters = %d\n",nchars-1);

words++;

getch();
return (0);
}
Output:
Enter Text (^z to end):
There is a question in our lab exercise of CP lab i.e. to solve
Tower of Hanoi problem by non-recursive program.
Generally this problem is solved by recursive function only.
I am not getting the complete solution anywhere to solve it
non-recursively.
Can you solve Tower of Hanoi problem by looping statements
only (non-recursively)^Z
Number of lines = 7
Number of words = 55
Number of characters = 331

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week8a

Page:29 */

Write a C program to print Pascal's Triangle


Definition: Printing Binomial Coefficient incrementing the power produces Pascals
Triangle:
BINOMIAL CO-EFFICIENTS
(a+b)0 =
(a+b)1 =
(a+b)2=
(a+b)3=
AND SO ON

1
A+B
A2+2AB+B2
A3+3A2B+3AB 2+B3

1
1
1
1

1
2
3

1
3

General logic of this triangle:


Each lines starts and ends with 1. In between add digits of the previous line
For next line 1, (1+3=4), (3+3=6), (3+1=4) and 1
So next line will be:
1
4
Algorithm:
1 START
2 FOR I = 0 TO 9
2.1 FOR J = 0 TO I
2.1.1 IF J=0 OR I=0 THEN
2.1.1.1 K=1
2.1.2 ELSE
2.1.2.1 K=K*(I-J)/J
2.1.3 ENDIF
2.1.4 PRINT ,K
2.2 NEXT J
3 NEXT I
4 END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Code:
/*week8a.c */
#include <stdio.h>
#include <conio.h>
main()
{
int i,j,k;
clrscr();
puts("The pascal's Triangle:");
for(i=0;i<10;i++)
{
for(j=0;j<20-i;j++)
printf(" ");
/* to print space */
for(j=0;j<i;j++)
{
if(j==0|| i==0)
k=1;
else
k=k*(i-j)/j;
printf("%4d",k);
}
printf("\n");
}
return (0);
}
Output:
The pascal's Triangle:
1
1
1
1
1

1
2

1
3

4
6
4
1
5 10 10
5
1
1
6 15 20 15
6
1
1
7 21 35 35 21
7
1
1
8 28 56 70 56 28
8
1
1

Page:30 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week8b
Write a C program to construct pyramid of numbers
ALGORITHM:
1 START
2 FOR I = 1 TO 9
2.1 FOR J = 1 TO 39-I
2.1.1 PRINT BLANK
2.2 NEXT J
2.3 FOR J = 1 TO I
2.3.1 PRINT J
2.4 NEXT J
2.5 FOR J=I-1 TO 1 STEP 1
2.5.1 PRINT J
2.6 NEXT J
3 NEXT I
4 END.
/*week8b.c */
#include <stdio.h>
main()
{
int i,j,k;
puts("The Pyramid of numbers:\n");
for(i=1;i<=9;i++)
{
for(j=1;j<=39-i;j++)
printf(" ");
for(j=1;j<=i;j++)
printf("%d",j);
for(j=i-1;j>=1;j--)
printf("%d",j);
printf("\n");
}
return (0);
}
Output:
The Pyramid of numbers:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

Page:31 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week9

Page:32 */

Write a C program to read two numbers, x & n, and then compute the sum of geometric
progression:
1+x+x^2+x^3+......+x^n
For example: if n is 3 and x is 5, then program computes 1+5+25+125
Print x, n and the sum.
Perform error checking. For example, the formula does not make the 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 value
of x also illegal? if so, test for them too.
ALGORITHM:
1
2
3
4
5

START
REPEAT:
SUM=1
INPUT X,N
IF N < 0 THEN
5.1 PRINT NEGATIVE EXPONENT!!!
5.2 GOTO REPEAT
6 ELSE
6.1 IF X = 0 THEN
6.1.1 PRINT ILLEGAL VALUE OF X
6.1.2 GOTO REPEAT
6.2 ELSE
6.2.1 FOR I = 1 TO N
6.2.2 SUM=SUM+POWER(X,I)
6.2.3 NEXT I
6.3 ENDIF
7 ENDIF
8 END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


/*week9.c*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
int x,n,i;
long int sum=1;
clrscr();
repeat:
printf("Enter value of x and n : ");
scanf("%d%d",&x,&n);
if(n<0)
{
printf("Negative exponent!!!\n");
goto repeat;
}
else
if(x==0)
{
printf("Illegal value of x!!!\n");
goto repeat;
}
else
for(i=1;i<=n;i++)
sum+=pow(x,i);
printf("x = %d n = %d sum = %ld\n",x,n,sum);
getch();
return (0);
}
Output:
Enter value of x and n : 5 4
x = 5 n = 4 sum = 781
Output with negative value of n
Enter value of x and n : 5 -3
Negative exponent!!!
Output with 0 for x
Enter value of x and n : 0 4
Illegal value of x!!!

Page:33 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


WEEK10a

Page:34 */

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.
Algorithm:
1
2
3
4

5
6

7
8
9

START
INPUT NUMBIN (AS STRING)
LEN=LENGTH(NUMBIN)
DO WHILE NUMBIN[X] <> 1
(SCANNING FROM RIGHT AND SEARCHING 1)
4.1 IF NUMBIN[X] <> 0 AND NUMBIN[X] <> 1 THEN
4.1.1 PRINT NOT A BINARY NUMBER
4.1.2 EXIT
4.2 ENDIF
4.3 X=X-1
ENDWHILE
DO WHILE X >=1
6.1 IF NUMBIN[X] = 0 THEN
6.1.1 NUMBIN[X]=1
6.2 ELSE
6.2.1 NUMBIN[X]=0
6.3 ENDIF
6.4 X=X-1
ENDWHILE
PRINT 2S COMPLIMENT IS , NUMBIN
END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


CODE:
/*week10a.c*/

Page:35 */

#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char numbin[50];
int len,x,y;
clrscr();
printf("Enter Binary digits : ");
scanf("%s",numbin);
len=strlen(numbin);
x=len-1;
while(numbin[x]!='1') /* scanning from right and reaching to 1 */
{
if(numbin[x] !='0' && numbin[x]!='1')
{
puts("Sorry, not binary number");
return (1);
}
x--;
}
x=x-1;

/* to compliment after that digit*/

while(x>=0) /* complementing from the digit to beginning */


{
if(numbin[x]=='0')
numbin[x]='1';
else
numbin[x]='0';
x--;
}
printf("2's complement of number is %s\n",numbin);
getch();
return (0);
}
Output wrong Binary number:
Enter Binary digits : 102032
Sorry, not binary number
Output with binary digits:
Enter Binary digits : 10011101100
2's complement of number is 01100010100

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Week10b

Page:36 */

Write a C program to convert a Roman numeral to its decimal equivalent


Algorithm (To check whether its ROMAN numeral):
1
2
3
4

START
INPUT ROMAN
(AS STRING)
SIZE=LENGTH(ROMAN);
FOR I = 1 TO SIZE
4.1 C=ROMAN[I]
4.2 F=ROMAN[I+1]
4.3 IF C AND NOT F THEN
4.3.1 RETURN TRUE
4.4 ENDIF
4.5 IF C='I' AND F='I' AND ROMAN[I-1]='I' AND ROMAN[I-2]='I' THEN
4.5.1 RETURN FALSE
4.6 ENDIF
4.7 IF C='X' AND F='X' AND ROMAN[I-1]='X' AND ROMAN[I-2]='X'
4.7.1 RETURN FALSE
4.8 ENDIF
4.9 IF(C='C' AND F='C' AND ROMAN[I-1]='C' AND ROMAN[I-2]='C'
4.9.1 RETURN FALSE
4.10 ENDIF
4.11 IF C='V' AND F='V' THEN
4.11.1 RETURN FALSE
4.12 ENDIF
4.13 IF C='L' AND F='L' THEN
4.13.1 RETURN FALSE
4.14 ENDIF
4.15 IF C='D' AND F='D' THEN
4.15.1 RETURN FALSE
4.16 ENDIF
4.17 IF C='I' AND (F <>'I' AND F<>'V' AND F<>'X' )THEN
4.17.1 RETURN FALSE
4.18 ENDIF
4.19 IF C='X' AND (F<>'I' AND F<>'V' AND F<>'X' AND F<>'L' AND F<>'C') THEN
4.19.1 RETURN FASLE
4.20 ENDIF
4.21 IF C='C' AND (F<>'I' AND F<>'V' AND F<>'X' AND F<>'L' AND F<>'C'
AND F<>'D' AND F<>'M') THEN
4.21.1 RETURN FA
4.22 ENDIF
5 NEXT I
6 RETURN TRUE
7 END.

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Algorithm (Roman to decimal):
1
2
3
4
5

START
INPUT ROMAN (AS STRING)
VALUE = 0
SIZE=LENGTH(ROMAN);
FOR I=1 TO SIZE
5.1 T=ROMAN[I];
5.2 F=ROMAN[I+1];
5.3 DO CASE (T)
5.3.1 CASE 'M':VALUE=VALUE+1000
5.3.2 CASE 'D':VALUE=VALUE+500
5.3.3 CASE 'C':
5.3.3.1 IF F='M' OR F='D' THEN
5.3.3.1.1 VALUE=VALUE-100
5.3.3.2 ELSE
5.3.3.2.1 VALUE=VALUE+100
5.3.3.3 ENDIF
5.3.4 CASE 'L':VALUE=VALUE+50
5.3.5 CASE 'X':
5.3.5.1 IF F='C' OR F='L' THEN
5.3.5.1.1 VALUE=VALUE-10;
5.3.5.2 ELSE
5.3.5.2.1 VALUE=VALUE+10;
5.3.5.3 ENDIF
5.3.6 CASE 'V':VALUE=VALUE+5
5.3.7 CASE 'I':
5.3.7.1 IF F='X' OR F='V' THEN
5.3.7.1.1 VALUE=VALUE-1;
5.3.7.2 ELSE
5.3.7.2.1 VALUE=VALUE-1;
5.3.7.3 ENDIF
5.4 ENDCASE
6 NEXT I
7 RETURN VALUE
8 END.

Page:37 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Code:

Page:38 */

/* Week10b.c */
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
int checkroman(char roman[])
{
int i,size=strlen(roman);
char c,f;
for(i=0;i<size;i++)
{
c=roman[i];
f=roman[i+1];
if(c && !f) return (1);
if(c=='I' && f=='I' && roman[i-1]=='I' && roman[i-2]=='I')
return NULL;
if(c=='X' && f=='X' && roman[i-1]=='X' && roman[i-2]=='X')
return NULL;
if(c=='C' && f=='C' && roman[i-1]=='C' && roman[i-2]=='C')
return NULL;
if(c=='V' && f=='V') return NULL;
if(c=='L' && f=='L') return NULL;
if(c=='D' && f=='D') return NULL;
if(c=='I' && (f!='I' && f!='V' && f!='X')) return NULL;
if(c=='X' && (f!='I' && f!='V' && f!='X' && f!='L' && f!='C'))
return NULL;
if(c=='C' && (f!='I' && f!='V' && f!='X' && f!='L' && f!='C'
&& f!='D' && f!='M')) return NULL;
}
return (1);
}
int romantodecimal(char roman[])
{
int i,value = 0,size=strlen(roman);
char t,f;
for( i=0; i < size ; i++)
{
t=roman[i];
f=roman[i+1];
switch(t)
{
case 'M':value+=1000; break;
case 'D':value+=500; break;
case 'C':
if(f=='M'|| f=='D')
value-=100;
else
value+=100;
break;

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


case 'L':value+=50; break;
case 'X':
if(f=='C'||f=='L')
value-=10;
else
value+=10;
break;
case 'V':value+=5; break;
case 'I': if(f=='X'|| f=='V')
value-=1;
else
value+=1;
break;
}
}
return value;
}
main()
{
char roman[15];
int dec,i;
clrscr();
printf("Enter roman numeral (IVXLCDM): ");
scanf("%s",roman);
for(i=0;i<strlen(roman);i++)
roman[i]=toupper(roman[i]);
if(!checkroman(roman))
puts("Invalid roman numeral!!!");
else
{
dec=romantodecimal(roman);
printf("Equivalent decimal value = %d\n",dec);
}
getch();
return (0);
}
output:
Enter roman numeral (IVXLCDM): XCV
Equivalent decimal value = 95

Page:39 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:40 */
/* week11.c
Write a C program that uses functions to perform the following
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.)
*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
struct comp
{
float r,i;
};
struct comp c1,c2,c3;
struct comp readdata(struct comp c)
{
printf("Enter real and imaginary part : ");
scanf("%f%f",&c.r,&c.i);
return c;
}
void writedata(struct comp c)
{
printf("Real = %.3f\n",c.r);
printf("Imaginary = %.3f\n",c.i);
}
struct comp add_complex(struct comp c1, struct comp c2)
{
struct comp c3;
c3.r = c1.r + c2.r;
c3.i = c1.i + c2.i;
return c3;
}
struct comp mul_complex(struct comp c1, struct comp c2)
{
struct comp c3;
c3.r = c1.r * c2.r;
c3.i = c1.i * c2.i;
return c3;
}

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


main()
{
clrscr();
c1=readdata(c1);
writedata(c1);
c2=readdata(c2);
writedata(c2);
c3=add_complex(c1,c2);
puts(After addition:);
writedata(c3);
c3=mul_complex(c1,c2);
puts(After multiplication:);
writedata(c3);
getch();
return (0);
}
Output:
Enter real and imaginary part : 5 3
Real = 5.000
Imaginary = 3.000
Enter real and imaginary part : 6 4
Real = 6.000
Imaginary = 4.000
After addition:
Real = 11.000
Imaginary = 7.000
After Multiplication:
Real = 30.000
Imaginary = 12.000

Page:41 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */

Page:42 */

/* Week12a.c
Write a C program which copies one file to another */
#include <stdio.h>
#include <conio.h>
main()
{
FILE *fp1, *fp2;
char sfname[67], tfname[67],c;
clrscr();
printf("Enter source file : ");
scanf("%s",sfname);
printf("Enter target file : ");
scanf("%s",tfname);
fp1=fopen(sfname,"r");
if(!fp1)
{ printf("%s file does not exist.\n",sfname);
return (1);
}
fp2=fopen(tfname,"w");
while(!feof(fp1))
{
c=getc(fp1);
putc(c,fp2);
}
printf(File %s successfully copied to %s\n,sfname,tfname);
fclose(fp1);
fclose(fp2);
getch();
return (0);
}
Output:
Enter source file : week1a.c
Enter target file : itlab1.c
File week1a.c successfully copied to itlab1.c

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:43 */
/* Week12b.c
Write a C program to reverse the first n characters in a file.
(Note: the file and n are specified on the command line) */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
main(int argc, char **argv)
{
FILE *fp;
char c,str[20];
int p=0,n=atoi(argv[2]);
clrscr();
fp=fopen(argv[1],"r+");
if(!fp)
{
printf("File %s not found\n",argv[1]);
return (1);
}
if(argc<3)
{
printf("Required parameter missing!!!\n");
return (1);
}
printf(contents of file %s\n\n,argv[1]);
while(!feof(fp))
{
c=getc(fp);
putchar(c);
}
rewind(fp);

/* displaying contents */

/* coming at beginning of file */

while(p<n)
/* reading first n characters */
{
str[p]=getc(fp);
p++;
}
str[p]='\0';
rewind(fp);

/* coming back at beginning */

strrev(str); /* reversing string i.e. first n characters */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */

Page:44 */

p=0;
while(p<n)
/* writing in file */
{
c=str[p];
putc(c,fp);
p++;
}
rewind(fp);

/* displaying contents again */

printf(\nAfter reversing first n characters:\n\n);


while(!feof(fp))
{
c=getc(fp);
putchar(c);
}
fclose(fp);
return (0);
}
Output:
Running program week12b.exe with arguments gmrit.txt and 15 (number of
characters to be reversed in file)
C:\TURBOC2>week12b gmrit.txt 15
contents of file vitam.txt
GMRIT COLLEGE OF ENGG.
GMR Nagar, Rajam
Dist: Srikakulam
ANDHRA PRADESH - 532127
After reversing first n characters:
O EGELLOC TIRMG F ENGG.
GMR Nagar, Rajam
Dist: Srikakulam
ANDHRA PRADESH - 532127

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:45 */
Week20-1
Write C programs that implement the following sorting methods to sort a given list of
integers in ascending order: i) Bubble sort
Process Logic:
Logic begins with comparing 1st element with 2nd. If 1st one is greater then it will be
swapped with 2nd. Again 2nd element will be compared with 3rd for same operation. This 3rd
with 4th, 4th with 5th and so on (n-1)th with nth.
In first pass the largest (heaviest) element will sink down at the bottom most place. In
each pass smaller (lighter) elements will bubble up and larger will sink down for 2 nd
largest, 3rd largest
Comparison will always start from 1st element to Total elements-no. of sorted elements.
Complexity/Number of comparison is similar to Selection Sort. Bubble Sort differs with
selection sort in way of comparison only.
In selection sort 1st compared with 2nd , 1st with 3rd, 1st with 4th . 1st with nth. So in first
pass smallest element will come at the top most position. In next pass comparision will
start from 2nd ( 2nd with 3rd, 2nd with 4th, 2nd with 5th .) for second smallest.
Algorithm: (Bubble sort)
1.
2.
3.
4.

5.
6.
7.
8.

START
INPUT ARRAY LIST
(WITH N ELEMENTS)
FOR I = 1 TO N-1
FOR J = 1 TO N-I
I. IF LIST[J] > LIST[J+1] THEN
1. SWAP(LIST[J],LIST[J+1])
II. ENDIF
NEXT J
NEXT I
PRINT SORTED ARRAY LIST
END

/* Week20-i.c */
#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


// Function for Bubble Sort
void bub_sort(int list[], int n)
{
int i,j;
for(i=0;i<(n-1);i++)
for(j=0;j<(n-(i+1));j++)
if(list[j] > list[j+1])
swapList(&list[j],&list[j+1]);
}

Page:46 */

void readlist(int list[],int n)


{
int j;
printf("\nEnter the elements: \n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}
// Showing the contents of the list
void printlist(int list[],int n)
{
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}
void main()
{
int list[MAX], num;
clrscr();
printf("\n*** Enter the number of elements [Maximum 10] *****\n");
scanf("%d",&num);
readlist(list,num);
printf("\n\nElements in the list before sorting are:\n");
printlist(list,num);
bub_sort(list,num);
printf("\n\nElements in the list after sorting are:\n");
printlist(list,num);
getch();
}
Output:

***** Enter the number of elements [Maximum 10] *****


10
Enter the elements:
44 5 66 7 444 1234 65 766 4 34

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Elements in the list before sorting are:
44
5
66
7
444
1234
Elements in the list after sorting are:
4
5
7
34
44
65

65

66

/*week20ii.c
Quick sort */
#include<stdio.h>
#include<conio.h>
int n;
void main()
{
long int a[100];
int i;
void qsort(long int [], int, int);
clrscr();
printf("\nEnter number of elements : ");
scanf("%d",&n);
printf("\nEnter elements :\n");
for(i=0;i<n;i++)
{
printf("Element %d ",i+1);
scanf("%ld",&a[i]);
}
qsort(a,0,n-1);
printf("\nNow quick sorted vector:\n");
for(i=0;i<n;i++)
printf(" %ld",a[i]);
printf("\n");
getch();
}
void qsort(long int a1[], int left, int right)
{
long int p,temp;
int i,j,k;
char ok;
if(right > left)
{
i=left;
j=right;
p=a1[left];

766

444

Page:47 */

34

766

1234

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


ok = 'n';
while(ok != 't')
{
do
{ ++i; } while ( (a1[i] <= p) && (i <= right) );
while( (a1[j] >= p) && (j > left))

Page:48 */

{ --j; }

if (j < i)
ok = 't';
else
{
temp=a1[i];
a1[i] = a1[j];
a1[j] = temp;
}
} /*while*/
temp = a1[left];
a1[left] = a1[j];
a1[j] = temp;
qsort(a1,left,j-1);
qsort(a1,i,right);
}
}
Output:
Enter number of elements : 10
Enter elements :
Element 1 44
Element 2 65
Element 3 7
Element 4 457
Element 5 56
Element 6 8
Element 7 54
Element 8 24
Element 9 65
Element 10 33
Now quick sorted vector:
7 8 24 33 44 54 56 65 65 457
/Week21-I.c
Write C programs that implement the following sorting methods to sort
a given list of integers in ascending order:

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


I -Insertion Sort */
#include <stdio.h>
#include <conio.h>
void insertion_sort(int a[], int size)
{
int x,y,picked;
for(x=1;x<size;x++)
{
picked=a[x];
y=x;
while (picked < a[y-1] && y> 0)
{
a[y]=a[y-1];
y--;
}
a[y]=picked;
}
}
main()
{
int *a,tot,x;
clrscr();
printf("How many numbers : ");
scanf("%d",&tot);
for(x=0;x<tot;x++)
{
printf("Enter number %d : ", x+1);
scanf("%d",&a[x]);
}
insertion_sort(a,tot);
printf("After sorting:\n");
for(x=0;x<tot;x++)
printf("%5d",a[x]);
getch();
return (0);
}
Output:
How many numbers
Enter number 1 :
Enter number 2 :
Enter number 3 :
Enter number 4 :
Enter number 5 :
Enter number 6 :
Enter number 7 :
Enter number 8 :
Enter number 9 :

: 10
444
55
66
77
82
34
5677
674
85

Page:49 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Enter number 10 : 123
After sorting:
34
55
66
77
82
85 123 444 674 5677
/*Week21-II - Merge Sort (Merging 2 sorted arrays in 3rd) */
#include <stdio.h>
#include <conio.h>
main()
{
int a[7]={22,33,44,55,666,777,888,};
int b[5]={100,200,300,890,900}, c[12], ax,bx,cx;
clrscr();
printf("Array a:\n ");
for(ax=0;ax<7;ax++)
printf("%5d",a[ax]);
printf("\nArray b:\n ");
for(bx=0;bx<5;bx++)
printf("%5d",b[bx]);
ax=bx=cx=0;
while(ax<7 && bx<5)
{
if (a[ax] < b[bx]) { c[cx]=a[ax]; ax++; }
else { c[cx] = b[bx]; bx++; }
cx++;
}
/* for rest of the elements */
while (ax < 7) { c[cx]=a[ax]; ax++; cx++; }
while (bx < 5) { c[cx]=b[bx]; bx++; cx++; }
printf ("\nNow merged and sorted array c:\n");
for(cx=0;cx<12;cx++)
printf("%5d",c[cx]);
getch();
return (0);
}
Output:
Array a:
22
33
44
55 666 777 888
Array b:
100 200 300 890 900
Now merged and sorted array c:
22
33
44
55 100 200 300 666

777

888

890

900

Page:50 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


/*Week19-I.c - Linear Search */
#include <stdio.h>
#include <conio.h>
int linser(int *a, int size, int skey)
{
int x,found=0;
for(x=0;x<size;x++)
if(a[x]==skey)
{
found=1;
break;
}
if(found) return (x+1);
else return (NULL);
}
main()
{
int a[100],*p,x,k,tot;
p=a;
clrscr();
printf("How many elements? : ");
scanf("%d",&tot);
for(x=0;x<tot;x++)
{
printf("Enter element %d : ",x+1);
scanf("%d",&p[x]);
}
printf("Enter element to search : ");
scanf("%d",&k);
x=linser(p,tot,k);
if(x)
printf("Found at %dth position.\n",x);
else
puts("Not found");
getch();
return (0);
}
Output:
How many elements? : 10
Enter element 1 : 44
Enter element 2 : 5
Enter element 3 : 66

Page:51 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Enter element 4 : 7
Enter element 5 : 88
Enter element 6 : 9
Enter element 7 : 111
Enter element 8 : 24
Enter element 9 : 65
Enter element 10 : 77
Enter element to search : 88
Found at 5th position.

Page:52 */

/* Week21-i.c
Write C programs that implement the following sorting methods to sort
a given list of integers in ascending order: i) Bubble sort */

/*Week19II.c - Binary search */


#include <stdio.h>
#include <conio.h>
int binser(int *a, int size, int skey)
{
int first,last,mid,found=0;
first=0; last=size-1;
while(first<=last && !found)
{
mid=(first+last)/2;
if(a[mid] > skey) last=mid-1;
else if(a[mid] < skey) first = mid+1;
else found=1;
}
if(found) return (mid+1);
else return (NULL);
}
main()
{
int a[10]={ 33,44,55,66,77,88,99,111,222,333},x,k;
clrscr();
printf("The sorted array:\n");
for(x=0;x<10;x++)
printf("%5d",a[x]);

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


printf("\nEnter element to search : ");
scanf("%d",&k);
x=binser(a,10,k);
if(x)
printf("Found at %dth position.\n",x);
else
puts("Not found");
getch();
return (0);
}
Output:
The sorted array:
33
44
55
66
77
88
Enter element to search : 222
Found at 9th position.

99

111

/*Week13.c
linked list*/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct LIST {
int data;
struct LIST *next;
};
typedef struct LIST node;
node *p;
void create(int num)
{ node *q, *t;
if(p==NULL)
{ p=(node *) malloc(sizeof(node));
p->data=num; p->next = NULL;
}
else
q=p;
while(q->next!=NULL) q=q->next;
t=(node *) malloc(sizeof(node));
t->data=num;
t->next = NULL;
q->next = t;

222

333

Page:53 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


}
void insert(int c,int num)
{ node *q, *t;
int i;
for(i=0,q=p;i<c;i++)
{
q=q->next;
if(q==NULL)
{ printf("\nThere are less than %d elements.\n",c);
return;
}
}
t=(node *) malloc(sizeof(node));
t->data=num;
t->next=q->next;
q->next = t;
}
void del(int num)
{ node *q,*r;
q=p;
if(q->data==num)
{ p=q->next; free(q); return; }
while(q!=NULL)
{
if (q->data==num)
{ r->next=q->next;
free(q);
return;
}
r=q;
q=q->next;
}
printf("\nElement %d not found",num);
}
void display()
{
node *q;
for(q=p;q!=NULL;q=q->next)
printf("%d-->",q->data);
}

Page:54 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:55 */
main()
{
int n,pos;
char ch;
p=NULL;
while (1)
{
printf("\nEnter choice : c/i/d/x to create/insert/delete/exit : ");
fflush(stdin);
ch=getchar();
switch (ch)
{ case 'c':
case 'C':
printf("Enter number : ");
scanf("%d",&n);
create(n);
display();
break;
case 'i':
case 'I':
printf("\nEnter number to insert (-999 to end) : ");
scanf("%d",&n);
printf("Insert after (position - 0,1,2,3,...n-1) : ");
scanf("%d",&pos);
insert(pos,n);
display();
break;
case 'd':
case 'D':
printf("\nEnter number to delete : ");
scanf("%d",&n);
del(n);
display();
break;
case 'x':
case 'X':
puts("Bye-Bye");
return 0;
}
}
}
Output:
Enter choice : c/i/d/x
Enter number : 12
12-->
Enter choice : c/i/d/x
Enter number : 44
12-->44-->
Enter choice : c/i/d/x
Enter number : 55
12-->44-->55-->
Enter choice : c/i/d/x

to create/insert/delete/exit : c
to create/insert/delete/exit : c
to create/insert/delete/exit : c
to create/insert/delete/exit : c

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Enter number : 77
12-->44-->55-->77-->
Enter choice : c/i/d/x to create/insert/delete/exit : i
Enter number to insert (-999 to end) : 66
Insert after (position - 0,1,2,3,...n-1) : 2
12-->44-->55-->66-->77-->
Enter choice : c/i/d/x to create/insert/delete/exit : d
Enter number to delete : 44
12-->55-->66-->77-->
Enter choice : c/i/d/x to create/insert/delete/exit : x
Bye-Bye
/*WEEK14.c Program to maintain a doubly linked list */
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
/* structure representing a node of the doubly linked list */
struct dnode
{
struct dnode *prev ;
int data ;
struct dnode * next ;
} ;
void d_append ( struct dnode **, int ) ;
void d_addatbeg ( struct dnode **, int ) ;
void d_addafter ( struct dnode *, int , int ) ;
void d_display ( struct dnode * ) ;
int d_count ( struct dnode * ) ;
void d_delete ( struct dnode **, int ) ;
void main( )
{
struct dnode *p ;
p = NULL ;
d_append
d_append
d_append
d_append
d_append

(
(
(
(
(

/* empty doubly linked list */


&p
&p
&p
&p
&p

,
,
,
,
,

11 ) ;
2 ) ;
14 ) ;
17 ) ;
99 ) ;

clrscr( ) ;
d_display ( p ) ;

Page:56 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:57 */
printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ;
d_addatbeg ( &p, 33 ) ;
d_addatbeg ( &p, 55 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ;
d_addafter ( p, 4, 66 ) ;
d_addafter ( p, 2, 96 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ;
d_delete ( &p, 55 ) ;
d_delete ( &p, 2 ) ;
d_delete ( &p, 99 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ;
}
/* adds a new node at the end of the doubly linked list */
void d_append ( struct dnode **s, int num )
{
struct dnode *r, *q = *s ;
/* if the linked list is empty */
if ( *s == NULL )
{
/*create a new node */
*s = malloc ( sizeof ( struct dnode ) ) ;
( *s ) -> prev = NULL ;
( *s ) -> data = num ;
( *s ) -> next = NULL ;
}
else
{
/* traverse the linked list till the last node is reached */
while ( q -> next != NULL )
q = q -> next ;
/* add a new node at the end */
r = malloc ( sizeof ( struct dnode ) ) ;
r -> data = num ;
r -> next = NULL ;
r -> prev = q ;
q -> next = r ;
}
}

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */

Page:58 */

/* adds a new node at the begining of the linked list */


void d_addatbeg ( struct dnode **s, int num )
{
struct dnode *q ;
/* create a new node */
q = malloc ( sizeof ( struct dnode ) ) ;
/* assign
q -> prev
q -> data
q -> next

data and pointer to the new node */


= NULL ;
= num ;
= *s ;

/* make new node the head node */


( *s ) -> prev = q ;
*s = q ;
}
/* adds a new node after the specified number of nodes */
void d_addafter ( struct dnode *q, int loc, int num )
{
struct dnode *temp ;
int i ;
/* skip to desired portion */
for ( i = 0 ; i < loc ; i++ )
{
q = q -> next ;
/* if end of linked list is encountered */
if ( q == NULL )
{
printf ( "\nThere are less than %d elements", loc );
return ;
}
}
/* insert new node */
q = q -> prev ;
temp = malloc ( sizeof ( struct dnode ) ) ;
temp -> data = num ;
temp -> prev = q ;
temp -> next = q -> next ;
temp -> next -> prev = temp ;
q -> next = temp ;
}
/* displays the contents of the linked list */
void d_display ( struct dnode *q )
{

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


printf ( "\n" ) ;

Page:59 */

/* traverse the entire linked list */


while ( q != NULL )
{
printf ( "%2d\t", q -> data ) ;
q = q -> next ;
}
}
/* counts the number of nodes present in the linked list */
int d_count ( struct dnode * q )
{
int c = 0 ;
/* traverse the entire linked list */
while ( q != NULL )
{
q = q -> next ;
c++ ;
}
return c ;
}
/* deletes the specified node from the doubly linked list */
void d_delete ( struct dnode **s, int num )
{
struct dnode *q = *s ;
/* traverse the entire linked list */
while ( q != NULL )
{
/* if node to be deleted is found */
if ( q -> data == num )
{
/* if node to be deleted is the first node */
if ( q == *s )
{
*s = ( *s ) -> next ;
( *s ) -> prev = NULL ;
}
else
{
/* if node to be deleted is the last node */
if ( q -> next == NULL )
q -> prev -> next = NULL ;
else
/* if node to be deleted is any intermediate node */
{

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


q -> prev -> next = q -> next ;
q -> next -> prev = q -> prev ;
}
free ( q ) ;
}
return ; /* return back after deletion */
}
q = q -> next ; /* go to next node */
}
printf ( "\n%d not found.", num ) ;
}
Output:

/*week15-i.c - stack implementation using arrays */


#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 5
int top, status;
/*function to push elements on to the stack */
void push(int stack[], int item)
{
if (top == (MAX - 1))
status = 0;
else

Page:60 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


{
status = 1;
++top;
stack[top] = item;
}
}
/* function to pop the elements off the stack */
int pop(int stack[])
{
int ret;
if(top == -1)
{
ret = 0;
status = 0;
}
else
{
status = 1;
ret = stack[top];
--top;
}
return ret;
}
/* function to display the elements of the stack */
void display(int stack[])
{
int i;
printf("The stack is ");
if(top == -1)
printf("empty.\n");
else
{
printf("\n");
for(i=top;i>=0;--i)
printf("\n--------\n|%5d |\n--------",stack[i]);
}
printf("\n");
}
/* main program */
void main()
{
int stack[MAX],quit,item;
char c;
clrscr();
quit = 0;

Page:61 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


top = -1;
do
{
printf("\nPush/Pop/Quit (P/O/Q)");
printf("\tEnter choice : ");
do
c = getchar();
while (strchr("pPoOqQ",c) == NULL);
switch (c)
{
case 'p':
case 'P':
printf("\nEnter elements to be pushed : ");
scanf("%d",&item);
push(stack,item);
if(status)
{
printf("\nAfter pushing : ");
display(stack);
if(top == (MAX-1))
printf("\nThe stack is full.\n");
}
else
printf("\nStack overflow on push.\n");
break;

Page:62 */

case 'o':
case 'O':
item = pop(stack);
if(status)
{
printf("\nThe popped item is %d \nAfter popping :",item);
display(stack);
}
else
printf("\nStack underflow on pop.\n");
break;
case 'q':
case 'Q':
quit = 1;
}
}while (!quit);
printf("\n Thank You \n");
getch();
}
Output:
Push/Pop/Quit (P/O/Q)

Enter choice : p

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Enter elements to be pushed : 44
After pushing : The stack is
-------|
44 |
-------Push/Pop/Quit (P/O/Q)

Enter choice : p

Enter elements to be pushed : 55


After pushing : The stack is
-------|
55 |
--------------|
44 |
-------Push/Pop/Quit (P/O/Q)

Enter choice : p

Enter elements to be pushed : 66


After pushing : The stack is
-------|
66 |
--------------|
55 |
--------------|
44 |
-------Push/Pop/Quit (P/O/Q)

Enter choice : o

The popped item is 66


After popping :The stack is
-------|
55 |
--------------|
44 |
--------

Page:63 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Push/Pop/Quit (P/O/Q)
Enter choice : q

Page:64 */

/*week16-ii.c: Program that implements queue using pointers */


#include <stdio.h>
#include <conio.h>
#define MAX 10
void addq ( int *, int, int *, int * ) ;
int delq ( int *, int *, int * ) ;
void main( )
{
int arr[MAX] ;
int front = -1, rear = -1, i ;
clrscr( ) ;
addq
addq
addq
addq
addq
addq
addq
addq
addq
addq
addq

(
(
(
(
(
(
(
(
(
(
(

arr,
arr,
arr,
arr,
arr,
arr,
arr,
arr,
arr,
arr,
arr,

23, &front, &rear ) ;


9, &front, &rear ) ;
11, &front, &rear ) ;
-10, &front, &rear ) ;
25, &front, &rear ) ;
16, &front, &rear ) ;
17, &front, &rear ) ;
22, &front, &rear ) ;
19, &front, &rear ) ;
30, &front, &rear ) ;
32, &front, &rear ) ;

i = delq ( arr, &front, &rear ) ;


printf ( "\nItem deleted: %d", i ) ;
i = delq ( arr, &front, &rear ) ;
printf ( "\nItem deleted: %d", i ) ;
i = delq ( arr, &front, &rear ) ;
printf ( "\nItem deleted: %d", i ) ;
getch( ) ;
}
/* adds an element to the queue */
void addq ( int *arr, int item, int *pfront, int *prear
{
if ( *prear == MAX - 1 )
{
printf ( "\nQueue is full." ) ;
return ;

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


}
( *prear )++ ;
arr[*prear] = item ;
printf(Inserted item
if ( *pfront == -1 )
*pfront = 0 ;

Page:65 */

= %d\n,item);

}
/* removes an element from the queue */
int delq ( int *arr, int *pfront, int *prear )
{
int data ;
if ( *pfront == -1 )
{
printf ( "\nQueue is Empty." ) ;
return NULL ;
}
data = arr[*pfront] ;
arr[*pfront] = 0 ;
if ( *pfront == *prear )
*pfront = *prear = -1 ;
else
( *pfront )++ ;
return

data ;

}
Output:
Inserted
Inserted
Inserted
Inserted
Inserted
Inserted
Inserted
Inserted
Inserted
Inserted

item
item
item
item
item
item
item
item
item
item

=
=
=
=
=
=
=
=
=
=

23
9
11
-10
25
16
17
22
19
30

Queue is full.
Item deleted: 23
Item deleted: 9
Item deleted: 11
/* week17-i.c: Program to convert an Infix form to Postfix form */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX 50
struct infix
{
char target[MAX] ;
char stack[MAX] ;
char *s, *t ;
int top ;
} ;
void initinfix ( struct infix * ) ;
void setexpr ( struct infix *, char * ) ;
void push ( struct infix *, char ) ;
char pop ( struct infix * ) ;
void convert ( struct infix * ) ;
int priority ( char ) ;
void show ( struct infix ) ;
void main( )
{
struct infix p ;
char expr[MAX] ;
initinfix ( &p ) ;
clrscr( ) ;
printf ( "\nEnter an expression in infix form: " ) ;
gets ( expr ) ;
setexpr ( &p, expr ) ;
convert ( &p ) ;
printf ( "\nThe postfix expression is: " ) ;
show ( p ) ;
getch( ) ;
}
/* initializes structure elements */
void initinfix ( struct infix *p )
{
p -> top = -1 ;
strcpy ( p -> target, "" ) ;
strcpy ( p -> stack, "" ) ;

Page:66 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


p -> t = p -> target ;
p -> s = "" ;
}
/* sets s to point to given expr. */
void setexpr ( struct infix *p, char *str )
{
p -> s = str ;
}
/* adds an operator to the stack */
void push ( struct infix *p, char c )
{
if ( p -> top == MAX )
printf ( "\nStack is full.\n" ) ;
else
{
p -> top++ ;
p -> stack[p -> top] = c ;
}
}
/* pops an operator from the stack */
char pop ( struct infix *p )
{
if ( p -> top == -1 )
{
printf ( "\nStack is empty.\n" ) ;
return -1 ;
}
else
{
char item = p -> stack[p -> top] ;
p -> top-- ;
return item ;
}
}
/* converts the given expr. from infix to postfix form */
void convert ( struct infix *p )
{
char opr ;
while ( *( p -> s ) )
{
if ( *( p -> s ) == ' ' || *( p -> s ) == '\t' )
{
p -> s++ ;
continue ;
}

Page:67 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:68 */
if ( isdigit ( *( p -> s ) ) || isalpha ( *( p -> s ) ) )
{
while ( isdigit ( *( p -> s ) ) || isalpha ( *( p -> s ) ) )
{
*( p -> t ) = *( p -> s ) ;
p -> s++ ;
p -> t++ ;
}
}
if ( *( p -> s ) == '(' )
{
push ( p, *( p -> s ) ) ;
p -> s++ ;
}
if ( *( p -> s ) == '*' || *( p -> s ) == '+' || *( p -> s ) == '/' ||
*( p -> s ) == '%' || *( p -> s ) == '-' || *( p -> s ) == '$' )
{
if ( p -> top != -1 )
{
opr = pop ( p ) ;
while ( priority ( opr ) >= priority ( *( p -> s ) ) )
{
*( p -> t ) = opr ;
p -> t++ ;
opr = pop ( p ) ;
}
push ( p, opr ) ;
push ( p, *( p -> s ) ) ;
}
else
push ( p, *( p -> s ) ) ;
p -> s++ ;
}
if ( *( p -> s ) == ')' )
{
opr = pop ( p ) ;
while ( ( opr ) != '(' )
{
*( p -> t ) = opr ;
p -> t++ ;
opr = pop ( p ) ;
}
p -> s++ ;
}
}
while ( p -> top != -1 )
{
char opr = pop ( p ) ;

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


*( p -> t ) = opr ;
p -> t++ ;
}

Page:69 */

*( p -> t ) = '\0' ;
}
/* returns the priority
int priority ( char c )
{
if ( c == '$' )
return 3 ;
if ( c == '*' || c
return 2 ;
else
{
if ( c == '+'
return 1
else
return 0
}
}

of an operator */

== '/' || c == '%' )

|| c == '-' )
;
;

/* displays the postfix form of given expr. */


void show ( struct infix p )
{
printf ( " %s", p.target ) ;
}
Output:
Enter an expression in infix form: a+b*c/d-e
Stack is empty.
The postfix expression is:

abc*d/+e-

/* week17ii.c: Program to evaluate an expression entered in postfix


form */
#include
#include
#include
#include
#include

<stdio.h>
<conio.h>
<stdlib.h>
<math.h>
<ctype.h>

#define MAX 50
struct postfix
{

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


int stack[MAX] ;
int top, nn ;
char *s ;
} ;

Page:70 */

void initpostfix ( struct postfix * ) ;


void setexpr ( struct postfix *, char * ) ;
void push ( struct postfix *, int ) ;
int pop ( struct postfix * ) ;
void calculate ( struct postfix * ) ;
void show ( struct postfix ) ;
void main( )
{
struct postfix q ;
char expr[MAX] ;
clrscr( ) ;
initpostfix ( &q ) ;
printf ( "\nEnter postfix expression to be evaluated: " ) ;
gets ( expr ) ;
setexpr ( &q, expr ) ;
calculate ( &q ) ;
show ( q ) ;
getch( ) ;
}
/* initializes data members */
void initpostfix ( struct postfix *p )
{
p -> top = -1 ;
}
/* sets s to point to the given expr. */
void setexpr ( struct postfix *p, char *str )
{
p -> s = str ;
}
/* adds digit to the stack */
void push ( struct postfix *p, int item )
{
if ( p -> top == MAX - 1 )
printf ( "\nStack is full." ) ;
else

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


{
p -> top++ ;
p -> stack[p -> top] = item ;
}
}
/* pops digit from the stack */
int pop ( struct postfix *p )
{
int data ;
if ( p -> top == -1 )
{
printf ( "\nStack is empty." ) ;
return NULL ;
}
data = p -> stack[p -> top] ;
p -> top-- ;
return data ;
}
/* evaluates the postfix expression */
void calculate( struct postfix *p )
{
int n1, n2, n3 ;
while ( *( p -> s ) )
{
/* skip whitespace, if any */
if ( *( p -> s ) == ' ' || *( p -> s ) == '\t' )
{
p -> s++ ;
continue ;
}
/* if digit is encountered */
if ( isdigit ( *( p -> s ) ) )
{
p -> nn = *( p -> s ) - '0' ;
push ( p, p -> nn ) ;
}
else
{
/* if operator is encountered */
n1 = pop ( p ) ;
n2 = pop ( p ) ;
switch ( *( p -> s ) )
{
case '+' :

Page:71 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


n3 = n2 + n1 ;
break ;
`

case '-' :
n3 = n2 - n1 ;
break ;
case '/' :
n3 = n2 / n1 ;
break ;
case '*' :
n3 = n2 * n1 ;
break ;
case '%' :
n3 = n2 % n1 ;
break ;
case '^' :
n3 = pow ( n2 , n1 ) ;
break ;
default :
printf ( "Unknown operator" ) ;
exit ( 1 ) ;
}
push ( p, n3 ) ;
}
p -> s++ ;
}

}
/* displays
void show (
{
p.nn =
printf
}

the result */
struct postfix p )
pop ( &p ) ;
( "Result is: %d", p.nn ) ;

Output:
Enter postfix expression to be evaluated: 5 5 5 5 * + +
Result is: 35

/*week18.c Program to implement BST & to perform


insertion, deletion & traversals - Prof. P. N. Singh */

Page:72 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


#include<stdio.h>
#include<conio.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
typedef struct TREE
{int data;
struct TREE *left;
struct TREE *right;
}TREE;

Page:73 */

/*Insert data into tree */


TREE *insert(int data, TREE *p)
{
/*is tree NULL */
if(!p)
{ p=(TREE *) malloc(sizeof(TREE));
p->data = data;
p->left = NULL;
p->right = NULL;
return (p);
}
/*is data less than the parent element */
if(data < p->data)
p->left = insert(data,p->left);
else
/* is data greater than the parent element */
if(data > p->data)
p->right = insert(data,p->right);
return (p);
}
/*display tree */
void display(TREE *tree, int level)
{
int i;
if(tree)
{
display(tree->right,level+1);
printf("\n");
for(i=0;i<level;i++)
printf("
");
printf("%d",tree->data);
display(tree->left,level+1);
}
}
/* replace the node at which key is found with last right key

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


of a left child */
TREE *del(TREE *r, TREE *q)
{
TREE *dnode;
if(r->right != NULL)
r->right = del(r->right,q);
else
{
dnode = r;
q->data = r->data;
r = r->left;
free(dnode);
}
return (r);
}
/*delete the key from the tree */
TREE *delelement(TREE *p, int data)
{
TREE *q;
if(!p)
{
printf("\nNonexistant data\n");
return (p);
}
else
{
if(data < p->data)
p->left = delelement(p->left,data);
else
if(data > p->data)
p->right = delelement(p->right,data);
else
{
q = p;
if(q->right == NULL)
{
p = q->left;
free(q);
}
else
if(q->left==NULL)
{ p=q->right;
free(q);
}
else
q->left = del(q->left,q);
}
}

Page:74 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


return (p);
}
/*preorder traversal */
void preorder(TREE *tree)
{
if(tree)
{
printf(" %d",tree->data); /*process node*/
preorder(tree->left);
preorder(tree->right);
}
}
/*Inorder traversal */
void inorder(TREE *tree)
{
if(tree)
{
inorder(tree->left);
printf(" %d",tree->data); /*process node */
inorder(tree->right);
}
}
/*post order traversal */
void postorder(TREE *tree)
{
if(tree)
{
postorder(tree->left);
postorder(tree->right);
printf(" %d",tree->data); /*process node*/
}
}
void traverse(TREE *tree)
{
printf("\nPre-order traversal:\n"); preorder(tree);
printf("\nIn-order traversal:\n");
inorder(tree);
printf("\nPost-order traversal:\n"); postorder(tree);
printf("\n");
}
void main()
{
int data,choice;
TREE *tree = NULL;
clrscr();
while(1)
{

Page:75 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Page:76 */
printf("\nSelect choice : 1-insert 2-delete 3-traverse 4-exit:");
scanf("%d",&choice);
if(choice==1)
{ printf("\nNumber to insert :");
scanf("%d",&data);
tree = insert(data,tree);
printf("\nTree display(left most is root):\n");
display(tree,1);
}
else
if(choice==2)
{
printf("\nNumber to delete:");
scanf("%d",&data);
tree=delelement(tree,data);
printf("\nTree display(left most is root):\n");
display(tree,1);
}
else
if(choice==3)
traverse(tree);
else
if(choice==4)
break;
else
puts("Wrong choice");
}
printf("\nOkay - Bye\n");
getch();
}
Output:
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :55
Tree display(left most is root):
55
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :66
Tree display(left most is root):
66
55
Select choice : 1-insert 2-delete 3-traverse 4-exit:1

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


Number to insert :44
Tree display(left most is root):
66
55
44
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :33
Tree display(left most is root):
66
55
44
33
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :50
Tree display(left most is root):
66
55
50
44
33
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :60
Tree display(left most is root):
66
60
55
50
44
33
Select choice : 1-insert 2-delete 3-traverse 4-exit:1
Number to insert :70
Tree display(left most is root):
70
66
60

Page:77 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


55
50
44
33
Select choice : 1-insert 2-delete 3-traverse 4-exit:3

Page:78 */

Pre-order traversal:
55 44 33 50 66 60 70
In-order traversal:
33 44 50 55 60 66 70
Post-order traversal:
33 50 44 60 70 66 55
Select choice : 1-insert 2-delete 3-traverse 4-exit:4
Okay - Bye
/* week22.c Computer program to implement the Lagrange interpolation */
#include <stdio.h>
#include <conio.h>
#define MAXPOINTS 21
double lagrpol(double x[], double y[], int n, double xbar);
main()
{
double x[MAXPOINTS], y[MAXPOINTS] ;
int n,i;
double xbar,ybar;
clrscr();
puts("LAGRANGE INTERPOLATION POLYNOMIAL");
printf("Enter degree of the polynomial: "); scanf("%d",&n);
printf("\nEnter data points:\n");
for (i=0; i<=n; i++)
{
printf("x[%d]=",i); scanf("%lf",&x[i]);
printf("y[%d]=",i); scanf("%lf",&y[i]);
}
printf("\nEnter xbar: ");
scanf("%lf",&xbar);
ybar=lagrpol(x,y,n,xbar);
printf("\nThe value of the polynomial at x = %lf is %lf\n"
,xbar,ybar);
getch();
return (0);
}
double lagrpol(double x[], double f[], int n, double xbar)
{
int i,j;

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


double fx=0.0;
double l=1.0;
for (i=0; i<=n; i++)
{
l=1.0;
for (j=0; j<=n; j++)
if (j != i) l *= (xbar-x[j])/(x[i]-x[j]);
fx += l*f[i];
}
return (fx);
}
Output:
LAGRANGE INTERPOLATION POLYNOMIAL
Enter degree of the polynomial: 3
Enter data points:
x[0]=5
y[0]=6
x[1]=4
y[1]=3
x[2]=7
y[2]=4
x[3]=2
y[3]=3
Enter xbar: 6
The value of the polynomial at x = 6.000000 is 7.266667

/*

Week23.c linear regression */

#include <stdio.h>
#include <conio.h>
#define N 9
main()
{

Page:79 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


float sumx,sumxsq,sumy,sumxy,denom,a0,a1,x[N],y[N];
int i;
sumx=sumxsq=sumy=sumxy=0;
clrscr();
for(i=0;i<N;i++)
{
printf("enter value for x[%d] and y[%d] : ",i,i);
scanf("%f%f",&x[i],&y[i]);
sumx+=x[i];
sumxsq+=x[i]*x[i];
sumy+=y[i];
sumxy+=x[i]*y[i];
}
denom=N*sumxsq-(sumx*sumx);
a0=(sumy*sumxsq - sumx*sumxy)/denom;
a1=(N*sumxy-sumx*sumy)/denom;
printf("a1 = %f a0 = %f\n",a1,a0);
getch();
}
Output:
enter value for x[0] and y[0]
enter value for x[1] and y[1]
enter value for x[2] and y[2]
enter value for x[3] and y[3]
enter value for x[4] and y[4]
enter value for x[5] and y[5]
enter value for x[6] and y[6]
enter value for x[7] and y[7]
enter value for x[8] and y[8]
a1 = 1.940001 a0 = 3.433330

/*

:
:
:
:
:
:
:
:
:

1
2
3
4
5
6
7
8
9

5.5
7.0
9.6
11.5
12.6
14.4
17.6
19.5
20.5

Week24.c Trazoidal & Simpson method */

#include <stdio.h>
#include <conio.h>
float f(float x)
{

Page:80 */

/* B.Tech 1st Year(R07) CP Lab Manual P. N. Singh, M.Tech(CSE), Dept. of IT */


return 1/2*x+3;
}
main()
{
float a,b,n,h,sum=0.00,trap,x1,x2,simp;
int i,x;
clrscr();
printf("Enter value of a,b & n : ");
scanf("%f%f%f",&a,&b,&n);
h=(b-a)/n;
/* for trapezoidal method */
for(i=1;i<n;i++)
{
x=a+i*h;
sum+=f(x);
}
trap=h*(f(a)+2*sum+f(b))/2;
printf("Result by Trapezoidal : %f\n",trap);
/* for simpson method */
x=a+h;
sum=f(a)+f(b)+4*f(x);
for(i=3;i<n;i+=2)
{
x1=a+i*h;
x2=a+(i-1)*h;
sum+=4*f(x1)+2*f(x2);
}
simp=h/3*sum;
printf("Result by Simpson : %f\n",simp);
getch();
}
Output:
Enter value of a,b & n : 3 4 5
Result by Trapezoidal : 3.000000
Result by Simpson : 2.400000

Page:81 */

You might also like