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

C PROGRAMMING FOR ENGINEERS LAB MANUAL

The document contains a series of C programming exercises aimed at teaching various programming concepts, including calculating the sum of digits, generating Fibonacci sequences, finding prime numbers, solving quadratic equations, calculating factorials, finding GCDs, and solving the Towers of Hanoi problem. Each exercise includes an aim, description, algorithm, program code, input, and output examples. The exercises are designed for students at the Kodada Institute of Technology & Science for Women in the CSE department.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C PROGRAMMING FOR ENGINEERS LAB MANUAL

The document contains a series of C programming exercises aimed at teaching various programming concepts, including calculating the sum of digits, generating Fibonacci sequences, finding prime numbers, solving quadratic equations, calculating factorials, finding GCDs, and solving the Towers of Hanoi problem. Each exercise includes an aim, description, algorithm, program code, input, and output examples. The exercises are designed for students at the Kodada Institute of Technology & Science for Women in the CSE department.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

1) Write a C program to find the sum of individual digits of positive integer


AIM:

To find the sum of individual digits of positive integer.

DESCRIPTION:

Summation of digits of a number

Ex: 1234

Summation =1+2+3+4=10

ALGORITHM:

Step 1: Start

Step 2: Read n

Step 3: Initialize sum ← 0

Step 4: while(n!=0)

Begin

Step 5: r←n%10

Step 6: sum←sum+r

Step 7: n←n/10

End

Step 8: Print “sum”

Step 9: Stop

PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int n,r,sum=0;

clrscr();

1
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("ENTER A POSITIVE INTEGER \n");

scanf("%d",&n);

while(n!=0)

r=n%10;

sum=sum+r;

n=n/10;

printf("THE SUMOF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..%d",sum);

getch();

INPUT:

ENTER A POSITIVE INTEGER

5321

OUTPUT:

THE SUM OF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..11

2
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

2) 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.
AIM: To generate the first n terms of the Fibonacci sequence..

DESCRIPTION: Initial Fibonacci numbers are 0 and 1. Next number can be generated by
adding two numbers. So 0+1=1. Therefore next number can be generated by adding two
previous . so Fibonacci series is 0 1 1 2 3 5 ……

ALGORITHM:

Step 1 : Start

Step 2 : Read n

Step 3 : Initialize f0 ← 0, f1 ← 1, f ← 0

Step 4 :i=0

Step 5 : while(i<=n) do as follows

printf("%d\t",f0);

f=f0+f1;

f0=f1;

f1=f;

i=i+1;

If not goto step 7

Step 6 : Stop

PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int f0,f1,f,n,i;

clrscr();

3
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("ENTER THE VALUE FOR n \n");

scanf("%d",&n);

f0=0;

f1=1;

printf("FIBONACCI SEQUENCE FOR THE FIRST %d TERMS:\n",n);

i=0;

while(i<n)

printf("%d\t",f0);

f=f0+f1;

f0=f1;

f1=f;

i=i+1;

INPUT:

ENTER THE VALUE FOR n

10

OUTPUT:

FIBONACCI SEQUENCE FOR THE FIRST 10 TERMS:

0 1 1 2 3 5 8 13 21 34

4
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

3) Write a C Program to Generate the First N Terms of the Sequence

AIM:TO generate the first N Terms of the sequence]

ALGORITHM:

Step 1: Start

Step 2: Read n

Step 3: Initialize f0 ← 0, f1 ← 1, f ← 0

Step 4:i=0

Step 5:

while(i<=n) do as follows

printf("%d\t",f0);

f=f0+f1;

f0=f1;

f1=f; i=i+1;

If not goto step 7

Step 6: Stop

PROGRAM:

include <stdio.h>

#include <conio.h>

void main()

int f0, f1, f, n, i;

clrscr();

printf("ENTER THE VALUE FOR n \n");

scanf("%d", &n);

f0 = 0;

5
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

f1 = 1;

printf("FIBONACCI SEQUENCE FOR THE FIRST %d TERMS:\n", n);

i = 0;

while (i < n)

printf("%d\t", f0);

f = f0 + f1;

f0 = f1;

f1 = f;

i = i + 1;

INPUT:

ENTER THE VALUE FOR n

10

OUTPUT:

FIBONACCI SEQUENCE FOR THE FIRST 10 T

6
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

4) Write a C program to generate all prime numbers between 1 and n. Where


n is the value supplied by the user.

AIM: To print a prime numbers up to 1 to n

DESCRIPTION:

Prime number is a number which is exactly divisible by one and itself only

Ex: 2, 3,5,7,………;

ALGORITHM:

Step 1: start

Step 2: read n

Step 3: initialize i=1,c=0

Step 4:if i<=n goto step 5

If not goto step 10

Step 5: initialize j=1

Step 6: if j<=i do the following. If no goto step 7

i)if i%j==0 increment c

ii) increment j

iii) goto Step 6

Step 7: if c== 2 print i

Step 8: increment i

Step 9: goto step 4

Step 10: stop


PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int n,i,fact,j;

7
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

clrscr();

printf("enter the number:");

scanf("%d",&n);

for(i=1;i<=n;i++)

{ fact=0;

//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.

for(j=1;j<=i;j++)

if(i%j==0)

fact++;

if(fact==2)

printf("\n %d",i);

getch( );

OUTPUT:

Enter the number : 5

235

8
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

5) Write a C Program to Find the Roots of a Quadratic Equation

AIM: To find the roots of a quadratic equation.

DESCRIPTION: roots of quadratic equation are -b±√ b2-4ac/2a


ALGORITHM:

Step 1: Start

Step 2: Read a,b,c

Step 3: calculate disc = b*b-4*a*c

Step 4: if(disc>0) Begin

Step 5: root1=(-b+sqrt(disc))/(2*a)

Step 6: root2=(-b-sqrt(disc))/(2*a)

Step 7: Print “Root1” , “Root2”

End

Step 8: else if(disc=0) Begin

Step 9: root1=-b/(2*a)

Step 10: root2=root1;

Step 11: Print “Root1” , “Root2”

End

Step 12: else

Step 13: Print Roots are imaginary

Step 14: Stop

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>

int main()

9
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int a,b,c;

float disc,root1,root2;

float img,real;

printf("ENTER VALUES FOR a,b,c:\n");

scanf("%d%d%d",&a,&b,&c);

disc=(float)b*b-4*a*c;

if(disc>0)

{ printf("THE ROOTS ARE REAL & UNEQUAL:\n");

root1=(-b+sqrt(disc))/(2*a);

root2=(-b-sqrt(disc))/(2*a);

printf("Root1=%f\n",root1);

printf("Root2=%f\n",root2);

else if(disc==0)

printf("THE ROOTS ARE REAL AND EQUAL:\n");

root1=-b/(2*a);

root2=root1;

printf("Root1=%f\n",root1);

printf("Root2=%f\n",root2);

else

{ printf("THE ROOTS ARE IMAGINARY:\n");

disc=-disc;

img=(float)disc/2*a;

real=(float)-b/2*a;

if (img>0)

10
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

{ printf("Root1=%f + i%f\n",real,img);

printf("Root2=%f - i%f\n",real,img);

else

{ img=-img;

printf("Root1=%f + i%f\n",real,img);

printf("Root2=%f - i%f\n",real,img);

return 0;

INPUT:

ENTER VALUES FOR a,b,c

144

OUTPUT:

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

11
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

6a) Write a C program to find the factorial of a given integer using non-
recursive function.
AIM:

To find the factorial of a given number using non-recursive function.

ALGORITHM:

Step 1: Start

Step 2: Read n

Step 3: Call fact(n) goto step 6

Step 4: Store result in “f”

Step 5: Print “f” goto step 10

Step 6: Begin //sub program

Initialize f ← 1

Step 7: for i is 1 to n by step 2

Step 8: Calculate f = f*i

Step 9: return “f”

End

Step 10: Stop

PROGRAM:

#include<stdio.h>

#include<conio.h>

int fact(int);

void main()

int n,i,f;

clrscr();

printf("ENTER A VALUE FOR n:\n");

scanf("%d",&n);

12
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

f=fact(n);

printf("THE FACTORIAL OF A GIVEN NO IS..%d",f);

getch();

int fact(int n)

int i,f=1;

for(i=1;i<=n;i++)

f=f*i;

return(f);

INPUT:

ENTER A VALUE FOR n

OUTPUT:

THE FACTORIAL OF A GIVEN NUMBER IS..120

13
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

6b) Write a C program to find the factorial of a given integer using recursive
function.
AIM:

To find the factorial of a given number using recursive function.

ALGORITHM:

main program:

Step 1: start

Step 2: read n

Step 3: call sub program as f=fact(n)

Step 4: print f value

Step 5: stop

Sub program:

Step 1: initialize the f

Step 2: if n= = 0 or n == 1 return 1 to main program if not goto step 3

Step 3: return n*fact(n-1) to main program

PROGRAM:

#include<stdio.h>

#include<conio.h>

int fact(int);

void main()

int n,res;

clrscr();

printf("ENETR A NUMBER:\n");

scanf("%d",&n);

14
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

res=fact(n);

printf("THE FACTORIAL OF A GIVEN NUMBER IS..%d",res);

getch();

int fact(int n)

int r;

if(n==0)

return(1);

else

r=n*fact(n-1);

return(r);

}
INPUT:

ENTER A VALUE FOR n

5
OUTPUT:

THE FACTORIAL OF A GIVEN NUMBER IS..120

15
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

7a) Write a C program to find the GCD of two given integers by using the
recursive function
AIM: To find the Gcd of two given integers by using the recursive function

ALGORITHM:

Main program:

Step 1: start

Step 2: read a,b

Step 3: call the sub program GCD(a,b) for print the value

Step 4: stop

Sub program: GCD(n,m)

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

Step 2: if n==0 return m else goto step 3

Step 3: return GCD (n,m%n)

Step 4: return to main program

PROGRAM:

#include<stdio.h>

#include<conio.h>

int gcdrecursive(int m,int n)

if(n>m)

return gcdrecursive(n,m);

if(n==0)

return m;

else

return gcdrecursive(n,m%n); // return to the main program

void main()

16
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int a,b,igcd; clrscr();

printf("enter the two numbers whose gcd is to be found:");

scanf("%d%d",&a,&b);

printf("GCD of a,b is %d",gcdrecursive(a,b)); // return to the sub program getch();

INPUT:

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

OUTPUT:

GCD of a,b is : 5

17
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

7b) Write a C program to find the GCD of two given integers using non-
recursive function.
AIM:To find the GCD of two given integers by using the non recursive function

DESCRIPTION:

GCD means Greatest Common Divisor. i.e the highest number which divides the given
number

Ex: GCD(12,24) is 12

Formula: GCD= product of numbers/ LCM of numbers

ALGORITHM:

Step 1: start

Step 2: read a,b

Step 3: call sub program g=GCD(a,b)

Step 4: print the g value

Step 5: stop

Sub program:

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

Step 2: remainder=p-(p/q*q)

Step 3: remainder=0 return q else goto step 4

Step 4: GCD(q,remainder) return to main program

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>

int gcdnonrecursive(int m,int n)

int remainder;

remainder=m-(m/n*n);

if(remainder==0)
18
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

return n;

else

gcdnonrecursive(n,remainder);

void main()

int a,b,igcd;

clrscr();

printf("enter the two numbers whose gcd is to be found:");

scanf("%d%d",&a,&b);

printf("GCD of %d",gcdnonrecursive(a,b));

getch();

OUTPUT:

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

GCD of a,b is : 5

19
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

8) Write a C program to solve Towers of Hanoi problem.


AIM: To solve towers of honoi problem

PROGRAM:

#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)

if (n == 1)

printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);

return;

towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);

towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

int main()

int n = 4; // Number of disks

towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods

return 0;

}
OUTPUT:

Move disk 1 from rod A to rod B

20
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 3 from rod A to rod B

Move disk 1 from rod C to rod A

Move disk 2 from rod C to rod B

Move disk 1 from rod A to rod B

Move disk 4 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 2 from rod B to rod A

Move disk 1 from rod C to rod A

Move disk 3 from rod B to rod C

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

21
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

9) 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)
AIM: To takes two integer operands and one operator from the user,

PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int a,b,c,ch; clrscr();

printf("ENTER TWO VALUES FOR a & b\n"); scanf("%d %d",&a,&b);

while(1) {

printf("MENU OPTIONS \n");

printf("************\n");

printf("1.Addition\n");

printf("2.Subtraction\n");

printf("3.Multiplication\n");

printf("4.Division\n");

printf("5.Modulus\n");

printf(“6.Exit\n”);

printf("\n");

printf("ENTER UR CHOICE\n");

scanf("%d",&ch);

switch(ch) {

case 1: c=a+b;

printf("The addition of %d and %d is..%d\n",a,b,c); break;

case 2: c=a-b;

22
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("The subtraction of %d and %d is..%d\n",a,b,c); break;

case 3: c=a*b;

printf("The multiplication of %d and %d is..%d\n",a,b,c); break;

case 4: c=a/b;

printf("The division of %d and %d is..%d\n",a,b,c); break;

case 5: c=a%b;

printf("The modulus of %d and %d is..%d\n",a,b,c); break;

case 6:exit(0); default:printf("INVALID CHOICE\n"); }

getch();

INPUT:

ENTER TWO VALUES FOR a & b: 20 16

OUTPUT:

MENU OPTIONS

1.Addition 2.Subtraction 3.Multiplication 4.Division 5.Modulus

6.Exit

ENTER UR CHOICE 1

The addition of 20 and 16 is..36

23
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

10) Write a C program to find both the largest and smallest number in a list of
integers.
AIM:To find the largest and smallest number in a list of integers.

ALGORITHM:

Step 1: start

Step 2: read n

Step 3: initialize i=0

Step 4: if i<n do as follows. If not goto step 5

Read a[i]

Increment i

Goto step 4

Step 5: small=a[0], large=a[0]

Step 6: initialize i=0

Step 7: if i<n do as follows. If

not goto step 8

If a[i]<small

Assign small=a[i]

If a[i]>large

Assign large=a[i]

Increment i goto Step 7

Step 8: print small, large

Step 9: stop

PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

24
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int a[10],i,n,small,large;

clrscr();

printf("Enter The Array Size:");

scanf("%d",&n);

printf("ENTER ELEMENTS OF ARRAY");

for(i=0;i<n;i++) // read the elements of an array

scanf("%d",&a[i]);

small=a[0];

large=a[0];

for(i=0;i<n;i++)// read the elements of an array

{ if(a[i]<small)// check the condition for minimum value

small=a[i];

if(a[i]>large)//check the condition for maximum value

large=a[i];

printf("largest value is:%d\n",large);

printf("smallest value is:%d\n",small);

getch();

INPUT:

Enter The Array Size:10

ENTER THE ELEMENTS OF ARRAY

7 10 9 8 6 5 2 3 4 1

OUTPUT:

largest value is : 10

smallest value is : 1

25
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

11a) Write a C program to perform addition of two matrices.


AIM: To perform addition of two matrices.

ALGORITHM:

Step 1: Start

Step21: for i is 0 to 2 by step 1

for j is 0 to 2 by step 1

Step 3: Read a[i][j],b[i][j]

Step 4: goto step 2

Step 5: calculate c[i][j]=a[i][j]+b[i][j]

Step 6: goto step 2

Step 7: Print c[i][j]

Step 8: Stop

#include<stdio.h>

#include<conio.h>

void main()

int a[3][3],b[3][3],c[3][3];

int i,j;

clrscr();

printf("ENTER A MATRIX\n");

for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

printf("ENTER B MATRIX\n");

for(i=0;i<3;i++)

26
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

for(j=0;j<3;j++)

scanf("%d",&b[i][j]);

for(i=0;i<3;i++)

for(j=0;j<3;j++)

c[i][j]=a[i][j]+b[i][j];

printf(" After addition of two matrices :\n");

for(i=0;i<3;i++)

for(j=0;j<3;j++)

printf("%d\t",c[i][j]);

printf("\n");

getch();

27
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

INPUT:

ENTER a MATRIX

123

456

789

ENTER b MATRIX

111

111

111

OUTPUT:

After addition of two matrices is..

234

567

8 9 10

28
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

11b) Write a C program that uses functions to perform Multiplication of

Two Matrices.
AIM: To perform multiplication of two matrices.

ALGORITHM:

Step 1: Start

Step21: for i is 0 to 2 by step 1

for j is 0 to 2 by step 1

Step 3: Read a[i][j],b[i][j]

Step 4: goto step 2

Step 5: calculate c[i][j]=c[i][j]+a[i][k]*b[k][j]

Step 6: goto step 2

Step 7: Print c[i][j]

Step 8: Stop

Program:

#include<stdio.h >

#include<conio.h>

int i,j,k;

void main()

int a[10][10],b[10][10],c[10][10],m,n,p,q;

void mul(int x[10][10],int y[10][10],int z[10][10],int m,int n,int p,int q);

void read(int x[10][10],int m,int n);

void display(int x[10][10], int m,int n);

clrscr();

printf("Enter the size of A Mtrix (Row and Col): \n");

scanf("%d%d",&m,&n);

printf("Enter the size of B Mtrix (Row and Col): \n");

29
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

scanf("%d%d",&p,&q);

if(n!=p)

printf("Multiplication Not Possible\n Please re-enter\n");

printf("correct size and try again .....\n");

else

read(a,m,n);

read(b,m,n);

mul(a,b,c,m,n,p,q);

printf("A Matrix is :\n");

display(a,m,n);

printf("B Matrix is :\n");

display(b,m,n);

printf("C Matrix is :\n");

display(c,m,n);

getch();

void mul(int x[10][10],int y[10][10],int z[10][10],int m,int n,int p,int q)

for (i=0;i<m;i++)

for(j=0;j<q;j++)

z[i][j]=0;

for(k=0;k<n;k++)

30
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

z[i][j]+= x[i][k]*y[k][j];

void read(int x[10][10], int m,int n)

printf("Enter Matrix Value Row by Row\n");

for (i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&x[i][j]);

void display(int x[10][10], int m,int n)

for (i=0;i<m;i++)

for(j=0;j<n;j++)

printf("%5d",x[i][j]);

printf("\n");

printf("\n");

INPUT:

Enter the size of A Mtrix (Row and Col): 2 2

Enter the size of B Mtrix (Row and Col): 2 2

Enter Matrix Value Row by Row

10

26

Enter Matrix Value Row by Row

31
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

34

42

OUTPUT:

A matrix is:

10

26

B Matrix is:

34

42

C matrix is:

34

24 20

32
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

12a) Write a C program to use function to insert a sub-string in to given main

string from a given position.


AIM: To insert a string into another string from a specified position.

ALGORITHM:

Step 1: start

Step 2: read main string and sub string

Step 3: find the length of main string(r)

Step 4: find length of sub string(n)

Step 5: copy main string into sub string

Step 6: read the position to insert the sub string( p)

Step 7: copy sub string into main string from position p-1

Step 8: copy temporary string into main string from position p+n-1

Step 9: print the strings

Step 10: stop

PROGRAM:

#include<stdio.h>

#include<string.h>

main()

char a[3qq0],b[30],c[30];

int pos=0,i=0,l,la,lb,lc,j;

puts("Enter a string");

gets(a);

puts("Enter sub string");

gets(b);

puts("enter position for insertion");

scanf("%d",&pos);

33
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

la=strlen(a);

lb=strlen(b);

l=pos+lb;

lc=la+lb;

for(i=0;i<pos;i++)

c[i]=a[i];

j=0;

for(i=pos;i<=l;i++)

c[i]=b[j];

j++;

j=pos;

for(i=l;i<lc;i++)

c[i]=a[j];

j++;

c[i]='\0';

puts("String after Insertion is:");

printf("%s",c);

INPUT:

Enter First String:

Comer

34
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

Enter Second String:

put

OUTPUT:

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

Computer

35
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

12 b) To delete n Characters from a given position in a given string.


AIM: To delete n Characters from a given position in a given string.

ALGORITHM:

Step 1: start

Step 2: read string

Step 3: find the length of the string

Step 4: read the value of number of characters to be deleted and positioned

Step 5: string copy part of string from position to end, and

(position + number of characters to end)

Program:

#include<stdio.h>

#include<string.h>

main()

char a[30],c[30];

int pos=0,i=0,L,La,j,n;

puts("Enter a string");

gets(a);

puts("enter position for deletion");

scanf("%d",&pos);

puts("Enter number of characters to be deleted");

scanf("%d",&n);

La=strlen(a);

L=pos+n;

for(i=0;i<pos;i++)

c[i]=a[i];

36
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

j=pos;

for(i=L;i<=La;i++)

c[j]=a[i];

j++;

puts("String after Deletion is:");

printf("%s",c);

INPUT:

Enter the string

jayapal

Enter the position from where to delete:4

Enter the number of characters to be deleted 2

OUTPUT:

Jayal

37
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

13) Write a C program using user defined functions to determine whether the

given string is palindrome or not.


AIM: To determine if the given string is palindrome or not.

DESCRIPTION :

Palindrome means string on reversal should be same as original

Ex: madam on reversal is also madam

ALGORITHM:

Step 1: start

Step 2: read string A

Step 3: copy string A into B

Step 4: reverse string B

Step 5: compare A &B

If A equals B to got step 6

Else goto step 7

Step 6:print given string A is pallindrom

Step 7:print given string is not pallindroma

Step 8: stop

PROGRAM:

#include <stdio.h>

#include <string.h>

void main()

char string[25], reverse_string[25] = {'\0'};

int i, length = 0, flag = 0;

printf("Enter a string \n");

gets(string);

for (i = 0; string[i] != '\0'; i++)

38
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

length++;

printf("The length of the string '%s' = %d\n", string, length);

for (i = length - 1; i >= 0 ; i--)

reverse_string[length - i - 1] = string[i];

for (flag = 1, i = 0; i < length ; i++)

if (reverse_string[i] != string[i])

flag = 0;

if (flag == 1)

printf ("%s is a palindrome \n", string);

else

printf("%s is not a palindrome \n", string);

INPUT:

Enter a string

madam

OUTPUT:

The length of the string 'madam' = 5

madam is a palindrome

39
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

14) 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.


AIM: To display the position or index in the string S where the string T begins,

or - 1 if S doesn't contain T

ALGORITHM:

Step 1: start

Step 2: read the string and then displayed

Step 3: read the string to be searched and then displayed

Step 4: searching the string T in string S and then perform the following steps

i. found=strstr(S,T)

ii. if found print the second string is found in the first string at the

position. If not goto step 5

Step 5: print the -1

Step 6: stop

PROGRAM:

#include<stdio.h>

#include<string.h>

#include<conio.h>

void main()

char s[30], t[20];

char *found;

clrscr();

/* Entering the main string */

puts("Enter the first string: ");

gets(s);

/* Entering the string whose position or index to be displayed */

40
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

puts("Enter the string to be searched: ");

gets(t);

/*Searching string t in string s */

found=strstr(s,t);

if(found)

printf("Second String is found in the First String at %d position.\n",found-s);

else

printf("-1");

getch();

INPUT:

Enter the first string:

computer

Enter the string to be searched:

mp

OUTPUT:

Second string is found in the first string at 2 position

41
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

15) Write a C program to count the number of lines, words and

characters in a given text.


AIM: To count the number of lines, words and characters in a given list.

ALGORITHM:

Step 1: Start

Step 2: Read the text until an empty line

Step 3: Compare each character with newline char ‘\n’ to count no of lines

Step 4: Compare each character with tab char ‘\t\’ or space char ‘ ‘ to count no

of words

Step 5: Compare first character with NULL char ‘\0’ to find the end of text

Step 6: No of characters = length of each line of text

Step 7: Print no of lines, no of words, no of chars

Step 8: Stop.

PROGRAM:

#include <stdio.h>

void main()

char line[81], ctr;

int i,c,

end = 0,

characters = 0,

words = 0,

lines = 0;

printf("TYPE ANY TEXT.\n");

printf("GIVE ONE SPACE AFTER EACH WORD.\n");

while( end == 0)

42
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

/* Reading a line of text */

c = 0;

while((ctr=getchar()) != '\n')

line[c++] = ctr;

line[c] = '\0';

/* counting the words in a line */

if(line[0] == '\0')

break ;

else

words++;

for(i=0; line[i] != '\0';i++)

if(line[i] == ' ' || line[i] == '\t')

words++;

/* counting lines and characters */

lines = lines +1;

characters = characters + strlen(line);

printf ("\n");

printf("Number of lines = %d\n", lines);

printf("Number of words = %d\n", words);

printf("Number of characters = %d\n", characters);

INPUT:

TYPE ANY TEXT

43
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

GIVE ONE SPACE AFTER EACH WORD.

Ramu is a good boy.

OUTPUT:

THE NUMBER OF CHARACTERS IN A GIVEN TEXT IS..18

THE NUMBER OF WORDS IN A GIVEN TEXT IS..5

THE NUMBER OF LINES IN A GIVEN TEXT IS..1

44
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

16) Write a C program to generate Pascal’s triangle.


AIM: To generate Pascal’s triangle.

PROGRAM:

// C program to print Pascal’s Triangle

// using combinations in O(n^2) time

// and O(1) extra space function

#include <stdio.h>

void printPascal(int n)

for (int line = 1; line <= n; line++) {

for (int space = 1; space <= n - line; space++)

printf(" ");

// used to represent C(line, i)

int coef = 1;

for (int i = 1; i <= line; i++) {

// The first value in a line

// is always 1

printf("%4d", coef);

coef = coef * (line - i) / i;

printf("\n");

// Driver code

int main()

45
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int n = 5;

printPascal(n);

return 0;

OUTPUT:

1 1

1 2 1

1 3 3 1

1 4 6 4 1

46
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

17) Write a C program to construct a pyramid of numbers // C program to print


right half pyramid pattern of star.
AIM: To construct a pyramid of numbers.

PROGRAM:

#include <stdio.h>

int main()

int rows;

printf("Number of rows: ");

scanf("%d", &rows);

// first loop for printing rows

for (int i = 1; i <= rows; i++) {

// second loop for printing similar number in each

// rows

for (int j = 1; j <= i; j++) {

printf("%d ", i);

printf("\n");

return 0; }

OUTPUT :

Number of rows: 5

22

333

4444

55555

47
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

18) 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.
AIM: To read in two numbers ,x and n and then compute the sum of given geometric
progression

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

int s_sum,i,x,n;

clrscr();

printf("Enter the values for x and n:");

scanf("%d %d",&x,&n);

if(n<=0 || x<=0)

printf("Value is not valid\n");

else

s_sum=1;

for(i=1;i<=n;i++)

s_sum=s_sum+pow(x,i);

48
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("Sum of series=%d\n",s_sum);

getch();

OUTPUT:

Enter the values for x and n:2 4

Sum of series=31

49
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

19) 2’s complement of a number is obtained by scanning it from right to left


and complementing all the bits after the first appearance of a 1. Thus 2’s
complement of 11100 is 00100. Write a C program to find the 2’s complement
of a binary number.

AIM: To find the 2’s complement of a binary number.

PROGRAM:

#include<stdio.h>

#include<conio.h>

main()

int a[10],i,n;

clrscr();

printf("Enter no of bits \n");

scanf("%d",&n);

printf("Enter binary numbers \n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

for(i=0;i<n;i++)

if(a[i]==0)

a[i]=1;

else

a[i]=0;

for(i=n-1;i>=0;i--)

if(a[i]==0)

50
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

a[i]=1;

break;

else

a[i]=0;

if(a[i-1]==0)

a[i-1]=1;

break;

} }

printf("The complement form is \n");

for(i=0;i<n;i++)

printf("%d",a[i]);

getch(); }

OUTPUT:

Enter no of bits

Enter binary numbers

The complement form is

00100

51
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

20) Write a C program to convert a Roman numeral to its decimal equivalent.


AIM: To convert a Roman numeral to its decimal equivalent

PROGRAM:

#include <stdio.h>

#include <conio.h>

main(){

char roman[30];

int deci=0;

int length,i,d[30];

printf("The Roman equivalent to decimal

");

printf("Decimal:.........Roman

");

printf("%5d............%3c

",1,'I');

printf("%5d............%3c

",5,'V');

printf("%5d............%3c

",10,'X');

printf("%5d............%3c

",50,'L');

printf("%5d............%3c

",100,'C');

printf("%5d............%3c

",500,'D');

printf("%5d............%3c

",1000,'M');

52
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("Enter a Roman numeral:");

scanf("%s",roman);

length=strlen(roman);

for(i=0;i<length;i++){

switch(roman[i]){

case 'm':

case 'M': d[i]=1000; break;

case 'd':

case 'D': d[i]= 500; break;

case 'c':

case 'C': d[i]= 100; break;

case 'l':

case 'L': d[i]= 50; break;

case 'x':

case 'X': d[i]= 10; break;;

case 'v':

case 'V': d[i]= 5; break;

case 'i':

case 'I': d[i]= 1;

for(i=0;i<length;i++){

if(i==length-1 || d[i]>=d[i+1])

deci += d[i];

else

deci -= d[i];

53
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("The Decimal equivalent of Roman numeral %s is %d", roman, deci);

OUTPUT:

When the above program is executed, it produces the following result −

The Roman equivalent to decimal

Decimal:.........Roman

1............ I

5............ V

10............ X

50............ L

100............ C

500............ D

1000............ M

Enter a Roman numeral: M

The Decimal equivalent of Roman Numeral M is 1000

54
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

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


AIM: To perform arithmetic operations on complex numbers

ALGORITHM:

Step 1:start

Step 2: Read Two complex numbers c1 ,c2

Step 3: c3=c1+c2

Step 4:print c3

Step 5: c3=c1-c2

Step 6: print c3

Step 7: c3=c1*c2

Step 8: print c3

Step 9: c3=c1/c2

Step 10: print c3

Step 11:print c

Step 12:stop

PROGRAM:

#include <stdio.h>

#include <conio.h>

struct complex

float real, imag;

}a, b, c;

55
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

struct complex read(void);

void write(struct complex);

struct complex add(struct complex, struct complex);

struct complex sub(struct complex, struct complex);

struct complex mul(struct complex, struct complex);

struct complex div(struct complex, struct complex);

void main ()

clrscr();

printf("Enter the 1st complex number\n ");

a = read();

write(a);

printf("Enter the 2nd complex number\n");

b = read();

write(b);

printf("Addition\n ");

c = add(a, b);

write(c);

printf("Substraction\n ");

c = sub(a, b);

write(c);

printf("Multiplication\n");

c = mul(a, b);

write(c);

printf("Division\n");

c = div(a, b);

write(c);

56
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

getch();

struct complex read(void)

struct complex t;

printf("Enter the real part\n");

scanf("%f", &t.real);

printf("Enter the imaginary part\n");

scanf("%f", &t.imag);

return t;

void write(struct complex a)

printf("Complex number is\n");

printf(" %.1f + i %.1f", a.real, a.imag);

printf("\n");

struct complex add(struct complex p, struct complex q)

struct complex t;

t.real = (p.real + q.real);

t.imag = (p.imag + q.imag);

return t;

struct complex sub(struct complex p, struct complex q)

struct complex t;

57
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

t.real = (p.real - q.real);

t.imag = (p.imag - q.imag);

return t;

struct complex mul(struct complex p, struct complex q)

struct complex t;

t.real=(p.real * q.real) - (p.imag * q.imag);

t.imag=(p.real * q.imag) + (p.imag * q.real);

return t;

struct complex div(struct complex p, struct complex q)

struct complex t;

t.real = ((p.imag * q.real) - (p.real * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));

t.imag = ((p.real * q.real) + (p.imag * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));

return(t);

INPUT & OUTPUT:

Enter the real part

Enter the imaginary part

Complex number is

2.0 + i4.0

Enter the real part

58
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

Enter the imaginary part

Complex number is

4.0 + i2.0

Addition

Complex number is

6.0 + i6.0

Subtraction

Complex number is

-2.0 + i2.0

Multiplication

Complex number is

0.0 + i20.0

Division

Complex number is

0.6 + i0.8

59
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

22 a) Write a C program which copies one file to another.

(Note: The file name and n are specified on the command line.)

AIM: Program which copies one file to another

ALGORITHM:

Step 1: Start

Step 2: read command line arguments

Step 3: check if no of arguments =3 or not. If not print invalid no of arguments

Step 4: open source file in read mode

Step 5: if NULL pointer, then print source file can not be open

Step 6: open destination file in write mode

Step 7: if NULL pointer, then print destination file can not be open

Step 8 : read a character from source file and write to destination file until EOF

Step 9: Close source file and destination file

Step 10: Stop

PROGRAM:

#include<stdio.h>

#include<process.h>

#include<conio.h>

void main()

FILE *ft,*fs;

int c=0;

clrscr();

fs=fopen("a.txt","r");

ft=fopen("b.txt","w");

if(fs==NULL)

60
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("Source file opening error\n");

exit(1);

else

if(ft==NULL)

printf("Target file opening error\n");

exit(1);

while(!feof(fs))

fputc(fgetc(fs),ft);

c++;

printf("%d bytes copied from 'a.txt' to 'b.txt'",c);

c=fcloseall();

printf("%d files closed",c);

INPUT:

a.txt

An array is a collection of elements of similar datatypes

OUTPUT:

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

2 files closed

61
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

22b) Write a C program to reverse the first n characters in a file.


AIM: To reverse the first n characters in a file

ALGORITHM:

Step 1: Start

Step 2: read the command line arguments

Step 3: check if arguments=3 or not

If not print invalid no of arguments

Step 4: open source file in read mode

Step 5: if NULL pointer, then print file can not be open

Step 6: Store no of chars to reverse in k

K= *argv[2]-48

Step 7: read the item from file stream using fread

Step 8: Store chars from last position to initial position in another string(temp)

Step 9: print the temp string

Step 10: Stop

PROGRAM:

#include <stdio.h>

#include <conio.h>

#include <string.h>

#include <process.h>

void main(int argc, char *argv[])

char a[15];

char s[20];

char n;

int k;

int j=0;

62
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int i;

int len;

FILE *fp;

if(argc!=3)

puts("Improper number of arguments.");

exit(0);

fp = fopen(argv[1],"r");

if(fp == NULL)

puts("File cannot be opened.");

exit(0);

k=*argv[2]-48;

n = fread(a,1,k,fp);

a[n]='\0';

len=strlen(a);

for(i=len-1;i>=0;i--)

s[j]=a[i];

printf("%c",s[j]);

j=j+1;

s[j+1]='\0';

getch();

63
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

INPUT:

source.c

this is source

ouput.c

this is source

OUTPUT:

Command line arguments

source.c ouput.c

source.c

this is source

ecruos si siht

64
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

23 a) Write a C program to display the contents of a file.

AIM: to display the contents of a file

ALGORITHM:

Step 1: Start

Step 2: read command line arguments

Step 3: check if no of arguments =3 or not. If not print invalid no of arguments

Step 4: open source file in read mode

Step 5: if NULL pointer, then print source file can not be open

Step 6: open destination file in write mode

Step 7: if NULL pointer, then print destination file can not be open

Step 8 : read a character from source file and write to destination file until EOF

Step 9: Close source file and destination file

Step 10: Stop

PROGRAM:

#include<stdio.h>

#include<process.h>

#include<conio.h>

void main()

FILE *ft,*fs;

int c=0;

clrscr();

fs=fopen("a.txt","r");

ft=fopen("b.txt","w");

if(fs==NULL)

printf("Source file opening error\n");

65
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

exit(1);

else

if(ft==NULL)

printf("Target file opening error\n");

exit(1);

while(!feof(fs))

fputc(fgetc(fs),ft);

c++;

printf("%d bytes copied from 'a.txt' to 'b.txt'",c);

c=fcloseall();

printf("%d files closed",c);

INPUT:

a.txt

An array is a collection of elements of similar datatypes

OUTPUT:

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

66
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

23b) 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).

AIM: To merge two files into a third file

PROGRAM :

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp1,*fp2,*fp3;

char file1[20],file2[20],file3[20],ch;

puts("Program to merge two files....\n");

puts("Enter first file name:");

gets(file1);

puts("Enter Second file name:");

gets(file2);

puts("Enter Destination file name:");

gets(file3);

fp1=fopen(file1,"r");

fp2=fopen(file2,"r");

fp3=fopen(file3,"w");

if(fp1==NULL&&fp2==NULL)

printf("Error opening file1 and file2.....\n");

else

if(fp3==NULL)

printf("Error in creating destination file....\n");

else

67
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

while((ch=fgetc(fp1))!=EOF)

putc(ch,fp3);

while((ch=fgetc(fp2))!=EOF)

putc(ch,fp3);

printf("File Merging Sucessfull....");

fcloseall();

getch();

INPUT:

source.c

this is source

ouput.c

this is source

OUTPUT:

Command line arguments

source.c ouput.c

source.c

this is source

ecruos si siht

68
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

24) Write a C program that implements the following sorting methods to sort a
given list of integers in ascending order

i) Bubble sort ii) Selection sort iii)Insertion sort


i)Bubble sort
AIM: C program for implementation of Bubble sort

PROGRAM:

#include <stdio.h>

#define MAXSIZE 10

void main()

int array[MAXSIZE];

int i, j, num, temp;

printf("Enter the value of num \n");

scanf("%d", &num);

printf("Enter the elements one by one \n");

for (i = 0; i < num; i++)

scanf("%d", &array[i]);

printf("Input array is \n");

for (i = 0; i < num; i++)

printf("%d\n", array[i]);

/* Bubble sorting begins */

69
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

for (i = 0; i < num; i++)

for (j = 0; j < (num - i - 1); j++)

if (array[j] > array[j + 1])

temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

printf("Sorted array is...\n");

for (i = 0; i < num; i++)

printf("%d\n", array[i]);

OUTPUT:

Enter the value of num

Enter the elements one by one

23

45

67

89

12

70
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

34

Input array is

23

45

67

89

12

34

Sorted array is...

12

23

34

45

67

89

ii)Insertion sort
AIM: C program for implementation of Insertion sort

PROGRAM:

#include <math.h>

#include <stdio.h>

/* Function to sort an array

using insertion sort*/

void insertionSort(int arr[], int n)

71
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

int i, key, j;

for (i = 1; i < n; i++)

key = arr[i];

j = i - 1;

/* Move elements of arr[0..i-1],

that are greater than key,

to one position ahead of

their current position */

while (j >= 0 && arr[j] > key)

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

// A utility function to print

// an array of size n

void printArray(int arr[], int n)

int i;

for (i = 0; i < n; i++)

72
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("%d ", arr[i]);

printf("\n");

// Driver code

int main()

int arr[] = {12, 11, 13, 5, 6};

int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printArray(arr, n);

return 0;

OUTPUT:

5 6 11 12 13

iii) Selection sort


AIM: C program for implementation of selection sort

PROGRAM:

#include <stdio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

73
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

*yp = temp;

void selectionSort(int arr[], int n)

int i, j, min_idx;

// One by one move boundary of unsorted subarray

for (i = 0; i < n-1; i++)

// Find the minimum element in unsorted array

min_idx = i;

for (j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first element

if(min_idx != i)

swap(&arr[min_idx], &arr[i]);

/* Function to print an array */

void printArray(int arr[], int size)

int i;

74
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

for (i=0; i < size; i++)

printf("%d ", arr[i]);

printf("\n");

// Driver program to test above functions

int main()

int arr[] = {64, 25, 12, 22, 11};

int n = sizeof(arr)/sizeof(arr[0]);

selectionSort(arr, n);

printf("Sorted array: \n");

printArray(arr, n);

return 0;

OUTPUT:

Sorted array:

11 12 22 25 64

75
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

25) Write C programs that use both recursive and non recursive functions to
perform the following searching operations for a Key value in a given list of
integers:

i) Linear search ii) Binary search


AIM:

PROGRAM:

#include <stdio.h>

#define MAX_LEN 10

/* Non-Recursive function*/

void b_search_nonrecursive(int l[],int num,int ele)

int l1,i,j, flag = 0;

l1 = 0;

i = num-1;

while(l1 <= i)

j = (l1+i)/2;

if( l[j] == ele)

printf("\nThe element %d is present at position %d in list\n",ele,j);

flag =1;

break;

else

if(l[j] < ele)

l1 = j+1;

76
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

else

i = j-1;

if( flag == 0)

printf("\nThe element %d is not present in the list\n",ele);

/* Recursive function*/

int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a)

int m,pos;

if (arrayStart<=arrayEnd)

m=(arrayStart+arrayEnd)/2;

if (l[m]==a)

return m;

else if (a<l[m])

return b_search_recursive(l,arrayStart,m-1,a);

else

return b_search_recursive(l,m+1,arrayEnd,a);

return -1;

void read_list(int l[],int n)

int i;

printf("\nEnter the elements:\n");

for(i=0;i<n;i++)

77
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

scanf("%d",&l[i]);

void print_list(int l[],int n)

int i;

for(i=0;i<n;i++)

printf("%d\t",l[i]);

/*main function*/

main()

int l[MAX_LEN], num, ele,f,l1,a;

int ch,pos;

//clrscr(); printf("==================================================");

printf("\n\t\t\tMENU"); printf("\
n================================================");

printf("\n[1] Binary Search using Recursion method");

printf("\n[2] Binary Search using Non-Recursion method");

printf("\n\nEnter your Choice:");

scanf("%d",&ch);

if(ch<=2 & ch>0)

printf("\nEnter the number of elements : ");

scanf("%d",&num);

read_list(l,num);

printf("\nElements present in the list are:\n\n");

print_list(l,num);

78
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

printf("\n\nEnter the element you want to search:\n\n");

scanf("%d",&ele);

switch(ch)

case 1:printf("\nRecursive method:\n");

pos=b_search_recursive(l,0,num,ele);

if(pos==-1)

printf("Element is not found");

else

printf("Element is found at %d position",pos);

//getch();

break;

case 2:printf("\nNon-Recursive method:\n");

b_search_nonrecursive(l,num,ele);

//getch();

break;

//getch();

OUTPUT:

[1] Binary Search using Recursion method

[2] Binary Search using Non-Recursion method

79
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

Enter your Choice:1

Enter the number of elements : 5

Enter the elements:

12

22

32

42

52

Elements present in the list are:

12 22 32 42 52

Enter the element you want to search:

42

Recursive method:

Element is found at 3 position

80
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

LAB MANUAL
ON

C PROGRAMMING FOR ENGINEERS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


KODADA INSTITUTE OF TECHNOLOGY & SCIENCE FOR
WOMEN
NEAR RANGANI GUDI, KODADA,SURYAPET(DT),TELANGANA-508206

81
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

Department of Computer Science and Engineering


VISION AND MISSION OF CSE DEPARTMENT

Vision
 To acknowledge quality education and instill high patterns of discipline
making the students technologically superior and ethically strong which involves
the improvement in the quality of life in human race.

Mission
 To achieve and impart holistic technical education using the best of
infrastructure, outstanding technical and teaching expertise to establish the
students in to competent and confident engineers.

 Evolving the center of excellence through creative and innovative teaching


learning practices for promoting academic achievement to produce internationally
accepted competitive and world class professionals.

Program Educational Objectives:(PEO’s)

PEO1: Graduates of program will have complete command over all key principles of
hardware and software areas.

PEO2: Graduates of program will develop skills to identify a real life situation, analyze the
problem,formulate a solution and help industry and individuals overcome issues.

PEO3: Graduates of program will cultivate professional skills, develop soft skills and be ready
with complete skill set demanded by industry or higher learning centers.

Program Specific Outcomes(PSO’s):


PSO-1: Computing Techniques: Apply the knowledge about principle of programming
languages,computer algorithms, databases, system software and computer network for the
interconnection.

82
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

PSO-2: Computer product and Application Development: Interpret and analyze the problem,
formulate an efficient hardware and software solution for the real world. Socio - industry
related problems and needs using computing methodologies and latest technologies.

PSO-3: Successful Career and Entrepreneurship Perspectives: Fulfilling desire by attaining


employment, excel in competitive examinations, higher studies, research and initiate
startup’s.

Program Outcomes (POs):

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate review research literature and analyze complex
engineering problems reaching substantiated conclusions using first principle of
mathematics, natural science and engineering science.

3. Design/development of solutions: Design solutions for complex engineering problems

and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and

synthesis of the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering

activities with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to

assess societal, health, safety, legal and cultural issues and the consequent responsibilities

relevant to the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering

solutions in societal and environmental contexts, and demonstrate the knowledge of, and

need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and

83
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

norms of the engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the

engineering community and with society at large, such as, being able to comprehend and

write effective reports and design documentation, make effective presentations, and give

and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one&#39;s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

INDEX:

84
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

S.NO LIST OF EXPERIMENTS


1 Write a C program to find the sum of individual digits of a positive integer

2 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.
3 Write a C program to generate the first n terms of the sequence
4 Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
5 Write a C program to find the roots of a quadratic equation

6 Write a C program to find the factorial of a given integer.

7 Write a C program to find the GCD (greatest common divisor) of two given integers

8 Write a C program to solve Towers of Hanoi problem.

9 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)
10 Write a C program to find both the largest and smallest number in a list of integers.

11 Write a C program that uses functions to perform the following: i) Addition of Two
Matrices ii) Multiplication of Two Matrices
12 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.
13 Write a C program to determine if the given string is a palindrome or not

14 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.
15 Write a C program to count the lines, words and characters in a given text.

16 Write a C program to generate Pascal’s triangle.

17 . Write a C program to construct a pyramid of numbers

18 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
19 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
20 Write a C program to convert a Roman numeral to its decimal equivalent.

21 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.)

85
KODADA INSTITUTE OF TECNOLOGY &SCIENCE FOR WOMEN CSE

22 i. Write a C program which copies one file to another. ii. 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.)
23 i. Write a C program to display the contents of a file. ii. 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)
24 Write a C program that implements the following sorting methods to sort a given list of
integers in ascending order i) Bubble sort ii) Selection sort iii)Insertion sort
25 Write C programs that use both recursive and non recursive functions to perform the
following searching operations for a Key value in a given list of integers: i) Linear search ii)
Binary search

86

You might also like