Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Final Record Programming in C Lab-converted

The document contains a series of C programming exercises, including swapping two numbers, finding the biggest among two or three numbers, calculating factorials, generating Fibonacci series, and checking for prime numbers. Each exercise includes an aim, algorithm, program code, output examples, and results indicating successful execution. The document serves as a practical guide for learning basic programming concepts in C.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Final Record Programming in C Lab-converted

The document contains a series of C programming exercises, including swapping two numbers, finding the biggest among two or three numbers, calculating factorials, generating Fibonacci series, and checking for prime numbers. Each exercise includes an aim, algorithm, program code, output examples, and results indicating successful execution. The document serves as a practical guide for learning basic programming concepts in C.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 160

Ex.

No:1a
PROGRAMS USING I/O STATEMENTS AND
Date: EXPRESSIONSSWAPPING TWO NUMBERS

AIM:
To write a C program to swap two numbers using temporary variable.
ALGORITHM:
Step 1: Start the program.
Step 2: Read two numbers a, b.
Step 3: Swap the values using a temporary variable.
Step 3.1: t=a
Step 3.2: a=b
Step 3.3: b=t
Step 4: Print two numbers a, b
Step 5: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,t;
clrscr();
printf(“Enter 2 numbers:”);
scanf(“%d%d”,&a,&b);
t=a;
a=b;
b=t;
printf(“Number after swap is %d%d”,a,b);
getch();

1
OUTPUT:
Enter 2 numbers:
89
12
Number after swap is:
12
89

Result
:
The program to swap two numbers using temporary variable was successfully executed
in C.

2
Ex.No:1b
Date: BIGGEST AMONG TWO NUMBERS USING TERNARY OPERATOR

AIM:

To write a C program to find the biggest among two numbers using ternary operator.
ALGORITHM:

Step 1: Start the program.


Step 2: Read two numbers.
Step 3: Use ternary operator to find biggest number(i.e.) (a>b)?a:b;
Step 4: Print biggest number.
Step 5: Stop the program.
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter the value of a and b:”);
scanf(“%d%d”,&a,&b);
c=a>b?a:b;
printf(“Biggest number=%d”,c);
getch();
}

3
OUTPUT:

Enter the value of a and b:


30
70
Biggest number=70

RESULT:

The program to find the biggest among two numbers using ternary operator was
successfully executed in C.

4
Ex.No:1c FINDING FACTORIAL OF A NUMBER
Date:

AIM:
To write a C program to find factorial of a number.

ALGORITHM:

Step 1: Start the program


Step 2: Read number n.
Step 3: Initialize the value of fact and i.
Step 4: Calculate fact=fact*i till i=n.
Step 5: Increment i=i+1.
Step 6: Print fact.
Step 7: Stop the program.
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,fact=1;
clrscr();
printf(“Enter the number”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf(“The factorial of %d is =%d”,n,fact);

5
getch();
}

OUTPUT:

Enter the number : 6


The factorial of 6 is= 720

RESULT:

The program to find the factorial of a number was successfully executed in C.

6
Ex.No:1d GENERATING FIBONACCI SERIES
Date:

AIM:

To write a C program to generate a Fibonacci series.

ALGORITHM:

Step 1: start the program.


Step 2: Read num.
Step 3: Assign first=0, second=1.
Step 4: Set loop for c and for all c<=1 value and calculate next=first+second.
Step 5: Display the value of next.
Step 6: Assign first=second and second=next.
Step 7: Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int n, first = 0, second = 1, next, c;
clrscr();
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
getch();

7
}

OUTPUT :

Enter how many numbers 5


0
1
1
2
3

RESULT:

The program to generate a Fibonacci series was successfully executed in C.

8
Ex.No:1e OBJECT UNDERGOES UNIFORM ACCELERATION
Date:

AIM:

To write a C program to generate a Uniform Acceleration.

ALGORITHM:

Step 1: Start the program.


Step 2: Read initial velocity, amount of acceleration and time.
Step 3: Calculate Velocity, v=u+a*t;
Step 4: Print Velocity.
Step 5: Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
float u,v,a,t;
clrscr();
printf("Enter the initial velocity");
scanf("%f",&u);
printf("Enter the amount of acceleration");
scanf("%f",&a);
printf("Enter the time");
scanf("%f",&t);
v=u+a*t;
printf(“ \n Velocity %f %f”,t,v);
getch();
}

9
OUTPUT:

Enter the initial velocity: 5.00


Enter the amount of acceleration: 4.00
Enter the time: 3.00
Velocity: 33.00000

RESULT:
The program to generate a Uniform Acceleration was successfully executed in C.

10
Ex.No:2a
PROGRAMS USING DECISION-MAKING CONSTRUCTS

Date: FINDING BIGGEST AMONG THREE NUMBERS

AIM:

To write a C program to find the biggest among three numbers.


ALGORITHM:

Step 1: Start the program.


Step 2: Read three numbers a,b,c.
Step 3: Compare a and b. If a is greatest perform step 4 else perform step 5.
Step 4: Compare a and c. If a is greatest print biggest number is A. Else print biggest
number is C.
Step 5: Compare b and c. If b is greatest print biggest number is B. Else print biggest
number is C.
Step 6: Stop the program.
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{

11
printf(“The biggest number is=%d”,a);
}
else
{
printf(“The biggest number is =%d”,c);
}
}
else
{
if(b>c)
{
printf(“The biggest number is =%d”,b);
}
else
{
printf(“The biggest number is =%d”,c);
}
}
}
getch();
}
OUTPUT:

Enter three numbers:


90
45
12
The biggest number is =90

RESULT:
The program to find the biggest among three numbers was successfully executed in C.

12
Ex.No:2b SOLVING QUADRATIC EQUATION
Date:

AIM:
To write a C program to find the roots of a quadratic equation.

ALGORITHM:
Step 1: Start the program.

Step 2: Enter three coefficients a,b,c.

Step 3: Calculate d=b*b - 4*a*c.

Step 4: Check if d=0 then roots are equal, and calculate root1 = root2 = -b/(2.0*a)

Step 5: If d>0 then roots are real and distinct. Calculate root1 = -b(2.0*a)

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

root2=(-b - sqrt(d))/(2*a)

Step 6: If d<0 then roots are imaginary root contains real and imaginary parts.

Calculate realp = -b(2*a)

imgp = sqrt(d)/(2*a) and

root1 = realp + imgp

root2 = realp – imgp

Step 7: Display root1, root2.

Step 8: Stop the program.


PROGRAM:

#include<stdio.h>

#include<conio.h>

int main()

13
float root1,root2,realp,imgp,a,b,c,d;

clrscr();

printf(“Enter three coefficients of quadratic equation”);

scanf(“%f%f%f”,&a,&b,&c);

d=b*b – 4*a*c;

if(d==0)

printf(“roots are equal\n”);

root1 = root2 = -b/(2*a);

printf(“root1 = root2 =%f\n”,root1);

else if(d>0)

printf(“roots are real and distinct\n”);

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

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

printf(“root1=%f\n”,root1);

printf(“root2=%f\n”,root2);

else

printf(“roots are imaginary\n”);

realp=-b/(2*a);

imgp=sqrt((-d))/(2*a); printf(“root1=

%f+i %f\n”,realp,imgp);

14
printf(“root2=%f-i %f\n”,realp,imgp);

getch();

OUTPUT:

Enter the coefficients of quadratic equation


1

roots are equal

roots1 = roots2 = -1.000000

RESULT:

The program to find the roots of a quadratic equation was successfully executed in C.

15
Ex.No:2c CHECKING PRIME NUMBERS
Date:

AIM:
To write a C program to check the prime number.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of n.

Step 3: From i=2 to n/2 divide the number by i.

Step 4: If the number is divisible by any other numbers then that number is not prime.

Step 5: If the number is not divisible by any other numbers then that number is prime.

Step 6: Display the result.

Step 7: Stop the program.

PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

inti ,n,count;

count=0;

printf(“Enter n value”);

scanf(“%d”,&n);

for(i=2;i<=n/2;i++)

16
if(n%i==0)

count++;

if(count==0)

printf(“Prime”);

else

printf(“Not prime”);

getch();

OUTPUT:

Enter n value 163

prime

Enter n value 235

Not prime

RESULT:
The program to check whether the given number is prime number or not was successfully
executed in C.

17
Ex.No:2d PRINTING MULTIPLICATION TABLE
Date:

AIM:
To write a C program to print multiplication table.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of n.

Step 3: Initialize the value of i.

Step 4: Calculate b=a*i and print the values in the format a*i=b.

Step 5: Increment i=i+1.

Step 6: Repeat step 4 till i=10.

Step 7: Stop the program.


PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int i,a,b;

a=0;

clrscr();

printf(“Enter the number”);

scanf(“%d”,&a);

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

18
b=a*i; printf(“%d*%d=%d\

n”,a,i,b);

getch();

OUTPUT:

Enter the number 8

8*1=8

8*2=16

8*3=24

8*4=32

8*5=40

8*6=48

8*7=56

8*8=64

8*9=72

8*10=80

RESULT:

The program to print multiplication table was successfully executed in C.

19
Ex.No:2e CHECKING PALINDROME NUMBERS OR NOT
Date:

AIM:
To write a C program to check whether given number is palindrome number or not.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of n.

Step 3: Assign rev=0 and temp=h.

Step 4: Calculate

r=n%10

rev=rev*10+r

n=n/10.

Step 5: Repeat step 4 till n>0

Step 6: Check whether the values of temp and reverse equal.

Step 7: If both are equal then print number is not palindrome.

Step 8: If both are not equal then print number is not palindrome.

Step 9: Stop the program.


PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

int n,r,rev,temp;

20
rev=0;

clrscr();

printf(“\n Enter the number:”);

scanf(“%d”,&n);

temp=n;

while(n>0)

{ r=n

%10;

rev=rev*10+r;

n=n/10;

printf(“The reversed of number %d is=%d\n”,temp,rev);

if(temp==rev)

printf(“It is palindrome”);

else

printf(“It is not palindrome”);

getch();

21
OUTPUT:

Enter the number: 123

The reversed of number 123 is = 321

It is a palindrome

Enter the number: 151

The reversed of number 151 is = 151

It is palindrome.

RESULT:

The program to check whether the given number is palindrome number or not was
successfully executed in C.

22
Ex.No:3
Date: CHECKING LEAP YEAR OR NOT

AIM:
To write a C program to check whether the given year is leap year or not.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of year.

Step 3: Check whether

year%400==0 || year%4=0 && year%100!=0.

Step 4: If the above condition is true then print given year is a leap year.

Step 5: If the above condition is false then print given year is not a leap year.

Step 6: Stop the program.


PROGRAM:

#include<stdio.h>

#include<conio.h>

void main()

inti ,year;

clrscr();

printf(“Enter the value of N:”);

scanf(“%d”,&year);

if((year%400==0)||(year%4==0 && year%100!=0))

printf(“%d is a leap year.\n”,year);

else

23
printf(“%d is not a leap year.\n”,year);

getch();

OUTPUT:

Enter the value of N: 2000

2000 is a leap year

Enter the value of N: 1700

1700 is not a leap year

RESULT:

The C program to check whether the given year is leap year or not was successfully
executed.

24
Ex.No:4
Date: DESIGNING SIMPLE CALCULATOR

AIM:

To write a C program to design a calculator to perform addition, subtraction,


multiplication, division and square of a number.

ALGORITHM:

Step 1: Start the program.

Step 2: Display the menu.

Step 3: Read the choice.

Step 4: If the choice is 1, then read two numbers, add two numbers, and print the result.

Step 5: If the choice is 2, then read two numbers, subtract a-b and print the result.

Step 6: If the choice is 3, then read two numbers, multiply two numbers and print the
result.

Step 7: If the choice is 4, then read two numbers, divide a/b and print the result.

Step 8: If the choice is 5, then exit.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void main()

float a,b,res;

char choice,ch;

25
clrscr();

do

printf(“1.Addition\n”);

printf(“2.Subtraction\n”);

printf(“3.Multiplication\n”);

printf(“4.Division\n”);

printf(“5.Sqaure\n”);

printf(“6.Exit\n”);

printf(“Enter your choice:”);

scanf(“%c”,&choice);

switch(choice)

case „1‟: printf(“Enter two number:”);

scanf(“%f%f”,&a,&b);

res=a+b; printf(“Result=

%f”,res); break;

case „2‟: printf(“Enter two number:”);

scanf(“%f%f”,&a,&b);

res=a-b; printf(“Result=

%f”,res); break;

case „3‟: printf(“Enter two number:”);

scanf(“%f%f”,&a,&b);

26
res=a*b; printf(“Result=

%f”,res); break;

case „4‟: printf(“Enter two number:”);

scanf(“%f%f”,&a,&b);

res=a/b; printf(“Result=

%f”,res); break;

case „5‟: printf(“Enter two number:”);

scanf(“%f”,&a);

res=a*a; printf(“Result=

%f”,res); break;

case „6‟: exit(0);

break;

default: printf(“Wrong Choice…!!”);

break;

printf(“\n…........................................................................\n”);

}while(choice!=6 && choice!=getchar());

getch();

OUTPUT:

1.Addition

2.Subtraction

27
3.Multiplication

4.Division

5.Square

6.Exit

Enter your choice: 1

Enter two numbers: 11

11

Result=22.000000

Enter your choice: 2

Enter two numbers: 22

11

Result=11.000000

Enter your choice: 3

Enter two numbers: 22

Result=66.000000

Enter your choice: 4

Enter two number: 44

Result=22.000000

Enter your choice: 5

Enter a number: 1

Result=16.000000

RESULT:
The C program to design a simple calculator was successfully designed and executed.

28
Ex.No:5 CHECKING ARMSTRONG NUMBER OR NOT
Date:

AIM:
To write a C program to check whether the given number is Armstrong number or not.

ALGORITHM:
Step 1: Start the program.

Step 2: Read the value of n.

Step 3: Store n into another variable num.

Step 4: If n!=0 then calculate

r=n%10

sum=sum+r*r*r

n=n/10

Step 5: Check whether sum equal to num or not. If both numbers, then print number is
Armstrong number.

Step 6: Otherwise print number is not Armstrong number.

Step 7: Stop the program.


PROGRAM:
#include<stdio.h>

#include<conio.h>

void main()

int n,sum,r,num;

sum=0;

printf(“Enter the number:”);

scanf(“%d”,&n);

29
num=n;

while(n!=0)

{r=n%10;

sum=sum+r*r*r;

n=n/10;

if(sum==num)

printf(”Entered number is Armstrong number”);

else

printf(“Entered number is not Armstrong number”);

}}

OUTPUT:
Enter the number:371

Entered number is Armstrong number

Enter the number:120

Entered number is not Armstrong number

RESULT:
The C program to check whether the given number is Armstrong number or not was
successfully executed.

30
Ex.No: 6
Date: FINDING SUM OF WEIGHTS

AIM:
To write a C program to find the sum of weights and sort the numbers.

ALGORITHM:
Step 1: Start the program.

Step 2: Read the values of n.

Step 3: Read n numbers.

Step 4: Initialize sum=0.

Step 5: Check whether the number is perfect cube or not. If it is perfect cube then add
sum=sum+5.

Step 6: Check whether the number is a multiple of 4 and divisible by 6 or not. If the
conditions are true then add sum=sum+4

Step 7: Check whether the number is prime number or not. If it is a prime number then
add sum=sum+3.

Step 8: Sort and print the array.

Step 9: Stop the program.


PROGRAM:
#include<stdio.h>

#include<conio.h>

#include <math.h>

void main()

int nArray[50],wArray[50],nelem,sq,i,j,t;

clrscr();

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

31
scanf("%d",&nelem);

printf("\nEnter %d elements\n",nelem);

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

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

// Sorting an array

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

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

if(nArray[i] > nArray[j])

t = nArray[i];

nArray[i] = nArray[j];

nArray[j] = t;

//Calculate the weight

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

wArray[i] = 0;

// sq =(int) sqrt(nArray[i]);

if(percube(nArray[i]))

wArray[i] = wArray[i] + 5; if(nArray[i]

%4==0 && nArray[i]%6==0)

wArray[i] = wArray[i] + 4;

if(prime(nArray[i]))

wArray[i] = wArray[i] + 3;

32
for(i=0; i<nelem; i++)

printf("<%d,%d>", nArray[i],wArray[i]);

getch();

int prime(int num)

int flag=1,i;

for(i=2;i<=num/2;i++)

if(num%i==0)

flag=0;

break;

return flag;

int percube(int num)

int i,flag=0;

for(i=2;i<=num/2;i++)

if((i*i*i)==num)

flag=1;

break;

return flag;

33
}

OUTPUT:
Enter n number (1-10): 6

Enter 6 elements: 10

36

54

89

12

27

The sorted array is

<10,0>

<54,0>

<89,3>

<36,4>

<12,4>

<27,5>

RESULT:
The C program to find the sum of weights and sort the numbers was successfully
executed.

34
Ex.No: 7
Date: FINDING NUMBER OF PERSONS ABOVE AVERAGE HEIGHT

AIM:
To write a C program to find number of persons above the average height.

ALGORITHM:

Step 1: start the program

Step 2: Read the value of n

Step 3: Populate height of n persons.

Step 4: Find the average by sum/n.

Step 5: Sort height array.

Step 6: Read every element if it is above the average height then increment count.

Step 7: Print count value.

Step 8: Stop the program.

PROGRAM:
#include <stdio.h>

#include <conio.h>

void main()

int i,n,sum=0,count=0,height[100];

float avg;

clrscr();

//Read Number of persons

printf("Enter the Number of Persons : ");

scanf("%d",&n);

//Read the height of n persons

35
printf("\nEnter the Height of each person in centimeter\n");

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

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

sum = sum + height[i];

avg = (float)sum/n;

//Counting

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

if(height[i]>avg)

count++;

//display

printf("\nAverage Height of %d persons is : %.2f\n",n,avg);

printf("\nThe number of persons above average : %d ",count);

getch();

36
OUTPUT:
Enter how many persons?

Populate height of 5 persons

46

78

39

61

59

Average height is = 56

39 46 59 61 78

3 persons above average height

RESULT:
The C program to find number of persons above the average height was successfully
executed.

37
Ex.No: 8
Date: CALCULATING BODY MASS INDEX

AIM:
To write a C program to compute the body mass index.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of n.

Step 3: Read weight and height of n persons.

Step 4: Calculate the value of, bmi=weight/(height*height).

Step 5: Print bmi.

Step 6: Stop the program.

PROGRAM:
#include<stdio.h>

#include<conio.h>

void main()

int i,j,n;

int x,bmi=0.0;

float hw[10][10];

clrscr();

printf(“Enter how many persons”);

scanf(“%d”,&n);

printf(“\n Populate weight in kg and height in meters(like 1.75m)\n”);

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

38
for(j=0;j<2;j++)

scanf(“%f\n”,&hw[i][j]);

printf(“weight and height \n”);

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

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

printf(“%f\t”,hw[i][j]);

printf(“\n”);

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

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

x=hw[i][0]/hw[i][1];

bmi=x/hw[i][1];

printf(“The body mass index of person %d is=%d\n”,i,bmi);

getch();

39
OUTPUT:
Enter how many persons 3

Populate weight in kg and height in meters (like 1.75m)

70

1.75

80

1.79

60

1.70

60

weight and height

70.000000 1.750000

80.000000 1.790000

60.000000 1.700000

The body mass index of person 1 is = 22

The body mass index of person 2 is = 24

The body mass index of person 3 is = 20

RESULT:
The C program to compute the body mass index was successfully executed.

40
Ex.No: 9
REVERSING THE STRING WITHOUT CHANGING SPECIAL CHARACTERS

Date:

AIM:
To write a C program to reverse the string without changing the position of special characters.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the string.

Step 3: Calculate the string length using strlen.

Step 4: Traverse the string from both ends and check it is special character or not.

Step 5: If it is special character just move to next character.

Step 6: If it is not special character swap both characters.

Step 7: Repeat steps 4 to 6. Until traverse all the characters.

Step 8: Print reversed string.

Step 9: Stop the string.

PROGRAM:
#include<stdio.h>

#include<conio.h>

#include<string.h>

isAlphabet(char x)

return((x>='A' && x<='Z')||(x>='a' && x<='z'));

void reverse(char str[])

41
char tmp;

int r=strlen(str)-1;

int l=0;

//Traverse string from both ends

while(l<r)

//Ignore special characters

if(!isAlphabet(str[l]))

l++;

else if(!isAlphabet(str[r]))

r--;

else //Both str[l] and str[r] are not special

tmp=str[l];

str[l]=str[r];

str[r]=tmp;

l++;

r--;

void main()

char str[20];

clrscr();

42
printf("Input String:\n");

scanf("%s",str);

reverse(str);

printf("Output string :%s",str);

getch();

OUTPUT:
Input string:

a@gh%;j

Output string:
j@hg%;a

RESULT:
The C program to reverse the string without changing the position of special characters
was successfully executed.

43
Ex.No: 10
CONVERTING DECIMAL NUMBER TO BINARY, OCTAL AND
HEXADECIMAL NUMBER
Date:

AIM:
To write a C program to convert decimal number to binary, octal and hexadecimal.

ALGORITHM:

Step 1: Start the program.

Step 2: Read the value of n.

Step 3: To convert n to any other base divide n to the base to be converted.

Step 4: Get the remainder and store it in the array.

Step 5: Use the quotient as new n and repeat steps 3 and 4. Until n becomes 0.

Step 6: Print the remainder array in reverse order.

Step 7: Stop the program.

PROGRAM:
#include<stdio.h>

#include<conio.h>

void decitobinary(int);

void decitooct(int);

void decitohex(int);

void main()

int n;

clrscr();

printf(“Enter the decimal number to convert”);

scanf(“%d”,&n);

44
decitobinary(n);

decitooct(n);

decitohex(n);

getch();

void decitobinary(int n)

int a[10],i;

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

a[i]=n%2;

n=n/2;

printf(“\nBinary of given number is =”);

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

printf(“%d”,a[i]);

return;

void decitooct(int n)

int octalNum[100];

int j,i=0; while(n!

=0)

45
{

octalNum[i]=n%8;

n=n/8;

i++;

printf(“\nOctal of Given Number is =”);

//printing octal number array in reverse order

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

printf(“%d”,octalNum[j]);

return;

void decitohex(int n)

int remainder,quotient;

int i=1,j,temp;

char hex[20];

quotient=n;

while(quotient!=0)

temp=quotient%16;

//To convert integer into character

if(temp<10)

temp=temp+48;

else

temp=temp+55;

46
hex[i++]=temp;

quotient=quotient/16;

printf(“\n Hexadecimal of given Number is =”);

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

printf(“%c”,hex[j]);

return;

OUTPUT:
Enter the decimal number to convert: 79

Binary of Given Number is = 1001111

Octal of Given Number is = 117

Hexadecimal of Given Number is = 4F

RESULT:
The C program to convert decimal number to binary, octal and hexadecimal was
successfully executed.

47
Ex.No: 11
PERFORMANCE STRING FUNCTIONS
Date:

AIM:

To write C program to find total number of words in a paragraph, to capitalize the first
word of each sentence and to replace a given word with another word.

ALGORITHM:

a: To find total number of words in a paragraph.

Step 1: Start the program.

Step 2: Read the paragraph.

Step 3: Read one character at a time if any blank space then increment the word count

variable by 1.

Step 4: Print count.

Step 5: Stop the program.

b: To capitalize the first word of each sentence.

Step 1: Start the program.

Step 2: Read the paragraph.

Step 3: Capitalize the first character of the paragraph using toupper built in function.

Step 4: Read one character at a time, and check if it is a full stop (.) then capitalize the
next character.

Step 5: If any uppercase in between the sentence change it to lowercase letter.

Step 6: Print the paragraph.

Step 7: Stop the program.

c: To replace a given word with another word.

Step 1: Start the program.

Step 2: Read a sentence.

48
Step 3: Read search and replace strings.

Step 4: Write a user defined function to replace the search string with the replace string.

Step 5: Recursively call using the function until there is no occurrence of the search
string.

Step 6: Print the new paragraph.

Step 7: Stop the program.

PROGRAM:
a: Program to find total number of words in a paragraph.

#include<stdio.h>

#include<string.h>

void main()

char s[200];

int count=0,i;

clrscr();

printf(“enter the string\n”);

scanf(“%[^\n]s”,s);

for(i=0;s[i]!=‟\0‟;i++)

if(s[i]==‟‟)

count++;

printf(“number of words in given string are:%d\n”,count+1);

getch();

49
b: Program to capitalized the first word of each sentence.

#include<stdio.h>

#include<conio.h>

#define MAX 100

void main()

char str[MAX]={0};

int i;

clrscr();

printf(“Enter a string:”);

scanf(“%[^\n]s”,str);

for(i=0;str[i]!=‟\0‟;i++)

if(i==0)

if((str[i]>=‟a‟ && str[i]<=‟z‟))

str[i]=toupper(str[i]);

continue;

if(str[i]==‟.‟)

++i;

if(str[i]>=‟a‟ && str[i]<=‟z‟)

str[i]=toupper(str[i]);

continue;

50
}

else

if(str[i]>=‟A‟ && str[i]<=‟Z‟)

str[i]=tolower(str[i]);

printf(“Capitalized string is:%s\n”,str);

getch();

c: Program to replace a given word with another word.

#include<stdio.h>

#include<conio.h>

int stlen(char str[50])

int len = 0;

while(str[len]!='\0') len+

+;

len--;

return len;

void stcat(char str1[50], char str2[50])

int i = 0,len = 0; while(str1[len]!

='\0')

51
len++;

while(str2[i]!='\0')

str1[len] = str2[i];

i++;

len++;

str1[len] = '\0';

void main()

char str1[50], str2[50], str3[50], temp[50];

int len1, len2, len3, i, j, match, k;

clrscr();

printf("\n\n\t ENTER A SENTENCE…: ");

gets(str1);

len1 = stlen(str1);

printf("\n\n\t ENTER A STRING WHICH YOU WANT TO DELETE…: ");

gets(str2);

len2 = stlen(str2);

printf("\n\n\t ENTER A NEW STRING WHICH YOU WANT TO INSERT …: ");

gets(str3);

len3 = stlen(str3);

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

match = 1;

52
for(j=0;j<=len2;j++)

if(str2[j]!=str1[i+j])

match = 0;

break;

if(match)

for(k=0,j=i+len2+1;j<=len1;j++,k++)

temp[k] = str1[j];

temp[k] = '\0';

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

str1[i+j] = str3[j];

str1[i+j] = '\0';

stcat(str1,temp);

len1 = len1-len2 +len3;

i = i + j;

printf("\n\n\t OUTPUT IS…: ");

puts(str1);

getch();

53
OUTPUT:
a. To find total number of words in a paragraph

Enter the string:

hai hello how are you

Number of words in given string are:

b. To capitalize the first word of each sentence

Enter a string: hello


Hello
c. To replace a given word with another word

Enter a Sentence: hello hai are you

Enter a String Which You Want to Delete: hai

Enter a New String Which You Want to Insert: how

Output is: hello how are you

RESULT:
The C program to find total number of words in a paragraph, to capitalize the first word
of each sentence and to replace a given word with another word was successfully executed.

54
Ex.No: 12
SOLVING TOWERS OF HANOI
Date:

AIM:
To write a C program to solve towers of Hanoi using recursion.

ALGORITHM:
Step 1: Start the program.

Step 2: Read the number of disks as num.

Step 3: If num=1, move the disk from frompeg to topeg

Step 4: Else repeatedly move disk (num-1, frompeg, auxpeg, topeg)

Step 5: Print the sequence of moves.

Step 6: Stop the program.

PROGRAM:
#include <stdio.h>

#include<conio.h>

void towers(int, char, char, char);

void main()

int num;

printf("Enter the number of disks : ");

scanf("%d", &num);

printf("The sequence of moves involved in the Tower of Hanoi are :\n");

towers(num, 'A', 'C', 'B');

getch();

55
void towers(int num, char frompeg, char topeg, char auxpeg)

if (num == 1)

printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);

return;

towers(num - 1, frompeg, auxpeg, topeg);

printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);

towers(num - 1, auxpeg, topeg, frompeg);

OUTPUT:
Enter the number of disks: 3

The sequence of moves involved in the Towers of Hanoi are:

Move disk 1 from peg A to peg C

Move disk 2 from peg A to peg B

Move disk 1 from peg C to peg B

Move disk 3 from peg A to peg C

Move disk 1 from peg B to peg A

Move disk 2 from peg B to peg C

Move disk 1 from peg A to peg C


RESULT:
The C program to solve Towers of Hanoi using recursion was successfully executed.

56
Ex.No: 13
SORTING LIST OF NUMBERS USING PASS BY REFERENCE
Date:

AIM:
To write the C program to sort n numbers using pass by reference.

ALGORITHM:
Step 1: Start the program.

Step 2: Read the value of n.

Step 3: Read n numbers.

Step 4: Call the function sort by passing the address of two numbers to swap.

4a: In sort function receive the numbers and using temporary variable swap two
numbers.

Step 5: Repeat step 4 until all number are sorted.

Step 6: Print the sorted array.

Step 7: Stop the program.

PROGRAM:
#include<stdio.h>

#include<conio.h>

int sort(int*,int*);

void main()

int n,i,j;

int a[10];

clrscr();

printf("Enter n");

scanf("%d",&n);

57
printf("Enter n numbers\n");

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

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

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

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

if(a[i]>a[j])

sort(&a[i],&a[j]);

printf("\n After sorting\n");

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

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

getch();

int sort(int*x,int*y)

int temp;

temp=*x;

*x=*y;

58
*y=temp;

return;

OUTPUT:
Enter n:
5
Enter n numbers:
89
234
45
90
12
After sorting;
12
45
89
90
234

RESULT:
The C program to sort n numbers using pass by reference is executed successfully.

59
Ex.No: 14
GENERATING SALARY SLIP OF EMPLOYEES USING STRUCTURES
AND POINTERS
Date:

AIM:
To write a C program to generate salary slip of employees using structures and pointers.

ALGORITHM:
Step 1: Start the program.

Step 2: Read number of employees.

Step 3: Read employee details and their basic salary, HRA, DA, Medical allowance, PF,

Insurance.

Step 4: Read the employee id to get salary slip.

Step 5: Display employee details and their basic salary, HRA, DA, Medical allowance,

PF, Insurance.

Step 6: Calculate Gross salary and Net Salary.

Step 7: Stop the program.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct employee
{
int empId;
char name[32];
int basic, hra, da,
ma,pf,insurance; float gross, net;
};

60
void printSalary(struct employee e1)
{
printf("Salary Slip of %s:\n", e1.name);
printf("Employee ID:%d\n", e1.empId);
printf("Basic Salary :%d\n", e1.basic);
printf("House Rent Allowance :%d\n", e1.hra);
printf("Dearness Allowance :%d\n", e1.da);
printf("Medical Allowance :%d\n", e1.ma);
printf("Gross Salary :%.2f Rupees\n", e1.gross);
printf("\nDeductions: \n");

printf("Provident fund :%d\n", e1.pf);


printf("Insurance :%d\n", e1.insurance);
printf("\nNet Salary :%.2f Rupees\n\n", e1.net);
return;

}
void main()
{
int i, ch, num, flag, empId;
struct employee *e1;
clrscr();
printf("Enter the Number of Employees");
scanf("%d", &num);
e1=(struct employee *)malloc(sizeof(struct employee) * num);
printf("Enter the input for Every Employee:\n");
for(i=0;i<num;i++)
{
printf("Employee ID:");

61
scanf("%d", &(e1[i].empId));
printf("Employee Name:");
//gets(e1[i].name);
scanf("%s", (e1[i].name));
printf("Basic Salary & HRA"); scanf("%d
%d", &(e1[i].basic),&(e1[i].hra));
printf("DA, Medical Allowance:");
scanf("%d%d", &(e1[i].da),&(e1[i].ma));
printf("PF & Insurance");
scanf("%d%d", &(e1[i].pf),&(e1[i].insurance));
//printf("Gross and NET");
//scanf("%f%f",&(e1[i].gross),&(e1[i].net));
}
for(i=0;i<num;i++)
{
e1[i].gross=e1[i].basic+(e1[i].hra*e1[i].basic)/100+(e1[i].da*e1[i].basic)/100+(e1[i].ma*e1[i].ba
sic)/100;
e1[i].net=e1[i].gross-(e1[i].pf+e1[i].insurance);
}
printf("Enter the Employee ID to get Salary Slip:");
scanf("%d",&empId);
flag=0;
for(i=0;i<num;i++)
{
if(empId==e1[i].empId)
{
printSalary(e1[i]);
flag=1;

62
}
if(flag==1)
{
break;
}
}
if(flag==0)
{
printf("No Records Found");
}
getch();
}

OUTPUT:
Enter the number of employees: 2

Enter the input for Every Employee

Employee ID: 101

Employee name: Arun

Basic Salary & HRA : 1000 1500

DA, Medical Allowance: 1000 2000

PF & Insurance: 1000 2500

Employee ID: 102

Employee name: Kavi

Basic Salary & HRA : 1500 2000

DA, Medical Allowance: 1200 2000

PF & Insurance: 1200 2500

Enter the Employee ID to get salary slip: 101

63
Salary Slip of Arun:

Employee ID:101

Basic Salary: 1000

House Rent Allowance: 1500

Dearness Allowance: 1000

Medical Allowance: 2000

Gross Salary: 780.00 rupees

Deductions:

Provident fund: 1000

Insurance: 2500

Net Salary: 2720.00 rupees

RESULT:
The C program to generate salary slip of employees using structures and pointers was
successfully executed.

64
Ex.No: 15
COMPUTING INTERNAL MARKS OF STUDENTS
Date:

AIM:
To write a C program to calculate internal marks of students for five different subjects
using structures and functions.

ALGORITHM:
Step 1: Start the program.

Step 2: Read number of students.

Step 3: For every student get attendance percentage.

Step 4: Calculate attendance mark based on the following conditions.

mark=0 if attendance percentage<75

mark=1 if attendance percentage>76 and 80

mark=2 if attendance percentage>81 and 90

mark=3 if attendance percentage>86 and 90

mark=4 if attendance percentage>91 and 95

mark=5 if attendance percentage>96 and 100

Step 5: Read 3 internal assessment marks for every subjects.

Step 6: Calculate internal mark out of 15 i.e) total=((m1+m2+m3)/300)*15 or


total=(m1+m2+m3)*0.05

Step 7: Add attendance mark and total mark to find internal mark.

Step 8: Print the internal mark.

Step 9: Stop the program.

PROGRAM:
#include<stdio.h>

#include<conio.h>

65
struct student

int m1;

int m2;

int m3;

};

int getattendance();

void main()

struct student s[50];

char subject[20];

int i,j,n,attmark,subtotal=0,total=0,intmark;

clrscr();

printf(“\n Enter number of students:”);

scanf(“%d”,&n);

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

attmark=getattendance();

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

printf(“\n \n Enter 3 internal Assessment Mark for subjects[%d]=\n”,j);

scanf(“%d%d%d”,&s[i].m1,&s[i].m2,&s[i].m3);

subtotal=s[i].m1+s[i].m2+s[i].m3;

total=subtotal*0.05;

intmark=total+attmark;

66
printf(“\n Internal mark of subject [%d] for Student [%d]=%d”,j,i+1,intmark);

getch();

int getattendance()

int attpercent,att;

printf(“\n Enter attendance percentage:”);

scanf(“%d”,&attpercent);

if(attpercent<75)

att=0;

else if(attpercent>76&&attpercent<80)

att=1;

else if(attpercent>81&&attpercent<85)

att=2;

else if(attpercent>86&&attpercent<90)

att=3;

else if(attpercent>91&&attpercent<95)

att=4;

else if(attpercent>96&&attpercent<100)

att=5;

return att;

67
OUTPUT:
Enter number of students:2

Enter attendance percentage:98

Enter 3 Internal Assessment Mark for Subject[1]=

98

95

96

Internal mark of subject [1] for student [1]=19

Enter 3 Internal Assessment Mark for subject[2]=

87

99

89

Internal mark of subject[2] for Student[1]=18

Enter 3 Internal Assessment Mark for subject[3]=

81

85

89

Internal mark of subject[3] for Student[1]=17

Enter 3 Internal Assessment Mark for subject[4]=

67

91

90

Internal mark of subject[4] for Student[1]=70

Enter 3 Internal Assessment Mark for subject[5]=

89

68
67

84

Internal mark of subject[5] for Student[1]=17

Enter attendance percentage: 89

Enter 3 Internal Assessment Mark for Subject[1]=

91

90

94

Internal mark of subject[1] for Student[2]=16

Enter 3 Internal Assessment Mark for Subject[2]=

78

79

69

Internal mark of subject[2] for Student[2]=14

Enter 3 Internal Assessment Mark for Subject[3]=

91

95

99

Internal mark of subject[3] for Student [2]=17

Enter 3 Internal Assessment Mark for Subject [4]=

83

89

91

Internal mark of subject[4] for Student[2]=16

Enter Internal Assessment Mark for subject[5]=

69
69

75

79

Internal mark of subject[5] for Student[2]=14

RESULT:
The C program for computing the internal marks of students was successfully executed.

70
Ex.No: 16
OPERATIONS ON TELEPHONE DIRECTORY USING RANDOM
ACCESS FILE
Date:

AIM:
To write a C program to create a telephone directory using random access file.

ALGORITHM:
Step 1: Start the program.
Step2: Declare variables, File pointer and phonebook structures.
Step 3: Create menu options for telephone directory.
Step 4: Read the option of phonebook menu.
Step 5: Develop procedures for each option.
Step 6: Call the procedure (Add, delete, display, Search and exit) for user chosen option.
Step 7: Display the message for operations performed.
Step 8: Stop the program.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Phonebook_Contacts
{
char FirstName[20];
char LastName[20];
char PhoneNumber[20];
} phone;
void AddEntry(phone * );
void DeleteEntry(phone * );
void PrintEntry(phone * );
void SearchForNumber(phone * );
int counter = 0;
int iSelection=0;

71
char FileName[256];
FILE *pRead;
FILE *pWrite;
int main (void)
{
phone *phonebook;
phonebook = (phone*) malloc(sizeof(phone)*100);

if (phonebook == NULL)
{
printf("Out of Memory. The program will now exit");
return 1;
}
else {}
do
{
printf("\n\t\t\tPhonebook Menu"); printf("\n\
n\t(1)\tAdd Friend"); printf("\n\t(2)\tDelete
Friend"); printf("\n\t(3)\tDisplay Phonebook
Entries"); printf("\n\t(4)\tSearch for Phone
Number"); printf("\n\t(5)\tExit Phonebook");
printf("\n\nWhat would you like to do? ");
scanf("%d", &iSelection);

if (iSelection == 1)
{
AddEntry(phonebook);

72
}
if (iSelection == 2)
{
DeleteEntry(phonebook);
}
if (iSelection == 3)
{
PrintEntry(phonebook);
}
if (iSelection == 4)
{
SearchForNumber(phonebook);
}
if (iSelection == 5)
{
printf("\nYou have chosen to exit the Phonebook.\n");
return 0;
}
} while (iSelection <= 4); }
void AddEntry (phone * phonebook)
{
pWrite = fopen("phonebook_contacts.dat", "a");
if ( pWrite == NULL )
{
perror("The following error occurred ");
exit(EXIT_FAILURE);
}

73
else
{
counter++;
realloc(phonebook, sizeof(phone));
printf("\nFirst Name: ");
scanf("%s", phonebook[counter-1].FirstName);
printf("Last Name: ");
scanf("%s", phonebook[counter-1].LastName);
printf("Phone Number (XXX-XXX-XXXX): ");
scanf("%s", phonebook[counter-1].PhoneNumber);
printf("\n\tFriend successfully added to Phonebook\n");
fprintf(pWrite, "%s\t%s\t%s\n", phonebook[counter-1].FirstName,
phonebook[counter-1].LastName, phonebook[counter-1].PhoneNumber);
fclose(pWrite);
}
}
void DeleteEntry (phone * phonebook)
{
int x = 0;
int i = 0;
char deleteFirstName[20]; //
char deleteLastName[20];
printf("\nFirst name: ");
scanf("%s", deleteFirstName);
printf("Last name: ");
scanf("%s", deleteLastName);
for (x = 0; x < counter; x++)

74
{
if (strcmp(deleteFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(deleteLastName, phonebook[x].LastName) == 0)
{
for ( i = x; i < counter - 1; i++ )
{
strcpy(phonebook[i].FirstName, phonebook[i+1].FirstName);
strcpy(phonebook[i].LastName, phonebook[i+1].LastName);
strcpy(phonebook[i].PhoneNumber, phonebook[i+1].PhoneNumber);
}

printf("Record deleted from the phonebook.\n\n");


--counter;
return;
}
}
}
printf("That contact was not found, please try again.");
}
void PrintEntry (phone * phonebook)
{
int x = 0;
printf("\nPhonebook Entries:\n\n ");
pRead = fopen("phonebook_contacts.dat", "r");
if ( pRead == NULL)
{
perror("The following error occurred: ");

75
exit(EXIT_FAILURE);
}
else
{
for( x = 0; x < counter; x++)
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Number: %s\n", phonebook[x].PhoneNumber);
}
}
fclose(pRead);
}
void SearchForNumber (phone * phonebook)
{
int x = 0;
char TempFirstName[20];
char TempLastName[20];
printf("\nPlease type the name of the friend you wish to find a number for.");
printf("\n\nFirst Name: ");
scanf("%s", TempFirstName);
printf("Last Name: ");
scanf("%s", TempLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(TempFirstName, phonebook[x].FirstName) == 0)
{

76
if (strcmp(TempLastName, phonebook[x].LastName) == 0)
{
printf("\n%s %s's phone number is %s\n", phonebook[x].FirstName,
phonebook[x].LastName, phonebook[x].PhoneNumber);
}
}
}
}

OUTPUT:

77
Phonebook Menu
1. Add Friend
2. Delete Friend
3. Display Phonebook Entries
4. Search for Phone Number
5. Exit Phonebook
What would you like to do? 1
First Name: Ram
Last Name: Mohan
Phone Number (XXX-XXX-XXXX): 717-675-0909
Friend successfully added to Phonebook
Phonebook Menu
1. Add Friend
2. Delete Friend
3. Display Phonebook Entries
4. Search for Phone Number
5. Exit Phonebook
What would you like to do? 3
Phonebook entries
Name: Ram Mohan
Number: 717-675-0909
Phonebook Menu
1. Add Friend
2. Delete Friend
3. Display Phonebook Entries
4. Search for Phone Number
5. Exit Phonebook
What would you like to do? 4
Please type the name of the friend you wish to find a number for.
First Name: Ram
Last Name: Mohan
Ram Mohan‟s phone number is: 717-675-0909
Phonebook Menu

78
1. Add Friend
2. Delete Friend
3. Display Phonebook Entries
4. Search for Phone Number
5. Exit Phonebook
What would you like to do? 5
Exit Phonebook

RESULT:
The C program to create a telephone directory using random access file was successfully
executed.

79
Ex.No: 17
COUNTING NUMBER OF MINIMUM BALANCE ACCOUNT HOLDERS
USING SEQUENTIAL ACCESS FILE
Date:

AIM:
To write a C program to count the number of account holders whose balance is less than
minimum balance using sequential access file.

ALGORITHM:
Step 1: Start the program.

Step 2: Read no.of.records.

Step 3: Read information for account holders.

Step 4: Store it in the file.

Step 5: Display all the details one by one.

Step 6: Read minimum balance value.

Step 7: If balance < minibalance then increment the count value.

Step 8: Print count value.

Step 9: Stop the program.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MINBAL 500
struct Bank_Account
{
char no[10];
char name[20];
char balance[15];
};
struct Bank_Account acc;
void main()
{
long int pos1,pos2,pos;
FILE *fp;

80
char *ano,*amt;
char choice;
int type,flag=0;
float bal;
do
{
clrscr();
fflush(stdin);
printf("1. Add a New Account Holder\n");
printf("2. Display\n");
printf("3. Deposit or Withdraw\n");
printf("4. Number of Account Holder Whose Balance is less than the Minimum Balance\n");
printf("5. Delete All\n");
printf("6. Stop\n");
printf("Enter your choice : ");
choice=getchar();
switch(choice)
{
case '1' :
fflush(stdin);
fp=fopen("acc.dat","a");
printf("\nEnter the Account Number : ");
gets(acc.no);
printf("\nEnter the Account Holder Name : ");
gets(acc.name);
printf("\nEnter the Initial Amount to deposit : ");
gets(acc.balance);
fseek(fp,0,2);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;
case '2' :
fp=fopen("acc.dat","r");
if(fp==NULL) printf("\
nFile is Empty"); else
{
printf("\nA/c Number\tA/c Holder Name Balance\n");
while(fread(&acc,sizeof(acc),1,fp)==1)
printf("%-10s\t\t%-20s\t%s\n",acc.no,acc.name,acc.balance);
fclose(fp);
}
break;
case '3' :
fflush(stdin);
flag=0;

81
fp=fopen("acc.dat","r+"); printf("\
nEnter the Account Number : ");
gets(ano);
for(pos1=ftell(fp);fread(&acc,sizeof(acc),1,fp)==1;pos1=ftell(fp))
{
if(strcmp(acc.no,ano)==0)
{
printf("\nEnter the Type 1 for deposit & 2 for withdraw : ");
scanf("%d",&type);
printf("\nYour Current Balance is : %s",acc.balance);
printf("\nEnter the Amount to transact : ");
fflush(stdin);
gets(amt);
if(type==1)
bal = atof(acc.balance) + atof(amt);
else
{
bal = atof(acc.balance) - atof(amt);
if(bal<0)
{
printf("\nRs.%s Not available in your A/c\n",amt);
flag=2;
break;
}
}
flag++;
break;
}

}
if(flag==1)
{
pos2=ftell(fp);
pos = pos2-pos1;
fseek(fp,-pos,1);
sprintf(amt,"%.2f",bal);
strcpy(acc.balance,amt);
fwrite(&acc,sizeof(acc),1,fp);
}
else if(flag==0)
printf("\nA/c Number Not exits... Check it again");
fclose(fp);
break;

case '4' :

82
fp=fopen("acc.dat","r");
flag=0;
while(fread(&acc,sizeof(acc),1,fp)==1)
{
bal = atof(acc.balance);
if(bal<MINBAL) flag+
+;
}
printf("\nThe Number of Account Holder whose Balance less than the Minimum Balance :
%d",flag);
fclose(fp);
break;
case '5' :
remove("acc.dat");
break;
case '6' :
fclose(fp);
exit(0);

}
printf("\nPress any key to continue.. .");
getch();
} while (choice!='6');
}

83
OUTPUT:

1. Add a New Account Holder\


2. Display
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice :1
Enter the Account Number : 5005
Enter the Account Holder Name : xyz
Enter the Initial Amount to deposit : 1000
1. Add a New Account Holder\
2. Display
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice :2

84
Number A/c Holder Name Balance
5005 xyz 1000
1. Add a New Account Holder\
2. Display
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice :3
Enter the Account Number 5005
Enter the Type 1 for deposit & 2 for withdraw : 2
Your current balance is:1000
Enter the Amount to transact:500
1. Add a New Account Holder\
2. Display
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice :4
The Number of Account Holder Whose Balance is less than the Minimum Balance :0

1. Add a New Account Holder\


2. Display
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice: 6
Stop

RESULT:

The C program to count the number of account holders whose balance in less than
minimum balance is less than minimum balance using sequential access file was successfully
executed.

85
Ex.No: 18
(MINI PROJECT)

RAILWAY RESERVATION SYSTEM


Date:

AIM:
To write C program to simulate railway reservation system using function modules.
ALGORITHM

Step 1: Start the program.


Step 2: Declare variables.
Step 3: Display the menu options.
Step 4: Read the option.
Step 5: If choice is admin mode, then read administrator password.
Step 6: If choice is create detail database, then read train no, train name, boarding point,
destination point, no of seats in first class, no of seats in second class and date of travel.
Step 7: If choice is display detail, then print its train no, train name, boarding point and
destination point.
Step 8: If choice is user management, read the concession category 1. Military 2. Senior
Citizen 3. Children below 5 years 4.none.
Step 9: If choice is display passenger, then print it‟s no of seat reserved, passenger name,
passenger age and date of reservation.
Step 10: If choice is user mode, read the user id and password.
Step 11: In user mode, read the option, 1. Reserve 2. Cancel 3. Enquiry.
Step 12: Stop the program.

PROGRAM:
#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<string.h>

#include<time.h>

char f[10]=”f”;

char s[10]=”s”;

86
int addr,ad,flag,f1,d,m,i,amt;

float tamt;

struct login

char id[100];

char pass[100];

char * password;

};

struct detail

int tno;

char tname[100];

char bp[100];

char dest[100];

int c1,c1fare;

int c2,c2fare;

int d,m,y;

};

struct reser

int pnr;

int tno;

char tname[100];

char bp[10];

char pname[10][100];

87
int age[20];

char clas[10];

int nosr;

inti ;

int d,m,y;

int con;

float amc;

}b;

struct canc

int pnr,rs;

int tno;

char tname[100];

char bp[10];

char dest[100];

char pname[10][100];

int age[20];

int i;

char clas[10];

int nosc;

int d,m,y;

float amr;

}c;

void getdetail()

88
int tno;

char tname[100];

char bp[100];

char dest[100];

int c1,c1fare;

int c2,c2fare;

int d,m,y;

struct detail a;

printf(“Enter the details as follows\n”);

printf(“\n Train no:”);

printf(“%d”,&a.tno);

printf(“\n Train name:”);

printf(“%s”,a.tname);

printf(“\n Boarding point:”);

scanf(“%s”,a.bp);

printf(“\n Destination point:”);

scanf(“%s”,a.dest);

printf(“\n No of seats in first class & fare per ticket:”);

scanf(“%d%d”,&a.c1,&a.c1fare);

printf(“\n No of seats in second class & fare per ticket:”);

scanf(“%d%d”,&a.c2,&a.c2fare);

printf(“\n Date of travel:”); scanf(“%d%d

%d”,&a.d,&a.m,&a.y);

void displaydetail()

89
{

int tno;

char tname[100];

char bp[100];

char dest[100];

int c1,c1fare;

int c2,c2fare;

int d,m,y;

struct detail a;

printf(“\n Train no: %d”,a.tno); printf(“\

n Train name: %s”,a.tname); printf(“\n

boarding point: %s”,a.bp); printf(“\n

destination point: %s”,a.dest); printf(“\n

c1:%d”,a.c1);

printf(“\n c2:%d”,a.c2);

printf(“\n c1fare: %d”,a.c1fare);

printf(“\n c2fare: %d”,a.c2fare);

printf(“\ndate: %d: %d: %d”,a.d,a.m,a.y);

void getresdet()

{
int pnr;

int tno;

char tname[100];

char bp[10];

90
char dest[100];

char pname[10][100];

int age[20];

char clas[10];

int nosr;

int i;

int d,m,y;

int con;

float amc;

printf(“\n Enter the details as follows\n”);

printf(“\n Train no:”);

scanf(“%d”,&b.tno);

printf(“\n Train name:”);

scanf(“%s”,b.train);

printf(“\n Boarding point:”);

scanf(“%s”,b.bp);

printf(“\n Destination point:”);

scanf(“%s”,b.dest);

printf(“\n No of seats required:”);

scanf(“%d”,&b.nosr);

for(i=0;i<b.nosr;i++)

printf(“\n Passenger name:”);

scanf(“%s”,b.pname[i]);

printf(“\n Passenger age:”);

91
scanf(“%d”,b.age[i]);

printf(“\n Enter the class f-first class s-second class:”);

scanf(“%s”,b.clas);

printf(“\n Date of travel:”); scanf(“%d%d

%d”,&b.d,&b.m,&b.y); printf(“\n Enter the

concession category\n”); printf(“1.Military\n

2.Senior citizen \n”); printf(“3.Children

below 5 yrs\n 4.None\n”);

scanf(“%d”,&b.con);

printf(“………………………END OF GETTING DETAILS..................................\n”);

void displayresdet()

int pnr;

int tno;

char tname[100];

char bp[10];

char dest[100];

char pname[10][100];

int age[20];

char class[20];

int nosr;

int i;

int d,m,y;

92
int con;

float amc;

printf(“........................................................................................\n”);

printf(“........................................................................................\n”);

printf(“Pnr no: %d”,b.pnr);

printf(“\n Train no: %d”,b.tno);

printf(“\n Train name: %s”);

puts(b.tname);

printf(“Boarding point:%s”);

puts(b.bp);

printf(“Destination point:%s”);

puts(“b.dest”);

printf(“No of seats reserved: %d”,b.nosr);

for(i=0;i<b.nosr;i++)

printf(“Passenger name:”);

puts(b.pname[i]);

printf(“Passenger age: %d”,b.age[i]);

printf(“\n Your class:”);

puts(b.clas);

printf(“\n Date of reservation: %d%d%d”,b.d,b.m,b.y);

printf(“\n Your concession category:%d”,b.con);

printf(“\n You must pay: %d”,b.amc);

printf(“*******************************************\n”);

93
printf(“………………END OF RESERVATION..........................................\n”);

printf(“*******************************************\n”);

void getcancdet()

{
int pnr,rs;

int tno;

char tname[100];

char bp[10];

char dest[100];

char pname[10][100];

int age[20];

int i;

char clas[10];

int nosc;

int d,m,y;

float amr;

printf(“Enter the details as follows\n”);

printf(“Pnr no: ”);

printf(“...............................................END OF GETTING
DETAILS....................................\n”);

void displaycancdet()

{
int pnr,rs;

int tno;

94
char tname[100];

char bp[10];

char dest[100];

char pname[10][100];

int age[20];

int i;

char clas[10];

int nosc;

int d,m,y;

float amr;

printf(“....................................................................................\n”);

printf(“....................................................................................\n”);

printf(“Pnr no: %d”,c.pnr);

printf(“\n Train no: %d”,c.tno);

printf(“\n Train name:”);

puts(c.tname);

printf(“Boarding point:”);

puts(c.bp);

printf(“Destination point:”);

puts(c.dest);

printf(“\n Your class:”);

puts(c.clas);

printf(“no of seats to be cancelled: %d”,c.nosc);

for(i=0;i<c.nosc;i++)

95
printf(“Passenger name:”);

puts(c.pname[i]);

printf(“Passenger age: %d”,c.age[i]);

printf(“\n Date of cancellation: %d%d%d”,c.d,c.d,c.y); printf(“\

n You can collect: %d%d”,c.amr,c.rs);

printf(“******************************************\n”);

printf(“…………………END OF CANCELLATION…..........................\n”);

printf(“******************************************\n”);

void getid()

struct login l;

char id[30];

char pass[100];

char *password;

printf(“\n Enter your id:”);

scanf(“%s”,i.id);

password=getpass(“\n Enter the password:”);

strcpy(l.pass,l.password);

puts(password);

void displayid()

{
struct login l;

96
char id[30];

char pass[30];

char *password;

printf(“Id:”);

puts(l.id);

printf(“Password:”);

puts(l.pass);

void manage();

void can();

void user();

void database();

void res();

void reserve();

void displaypassdetail();

void cancell();

void enquiry();

void main()

int ch;

clrscr();

printf(“ \n”);

printf(“WELCOME TO RAILWAY RESERVATION SYSTEM \n”);

printf(“ \n”);

do

97
{

printf(“MAIN MENU \n”);

printf(“1.Admin mode\n2.User mode \n3.Exit\n”);

printf(“Enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

case 1:

database();

break;

case 2:

user();

break;

case 3:

exit(0);

while(ch<=3);

getch();

void database()

FILE *fp;

int ch;

char c;

98
char *password;

char *pass=”jovi”;

struct detail a;

password=getpass(“Enter the administrator password:”);

if(strcmp(pass,password)!=0)

printf(“Enter the password correctly \n”);

printf(“You are not permitted to logon this mode \n”);

goto h;

if(strcmp(pass,password)==0)

char c;

do

printf(“...................................ADMINISTRATOR
MENU................................................\n”);

printf(“1.create detail data base\n 2.Add details\n”);

printf(“3.Display details\n 4.User management\n”);

printf(“5.Display passenger details\n 6.Return to main menu\n”);

printf(“Enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

case 1:

99
fp=fopen(“t.txt”,”rw”);

do

getdetail();

fwrite((char*)&a,sizeof(a),1,fp);

printf(“Do you want to add one more record? \n”);

printf(“y-for Yes \n n-for No \n”);

scanf(“%c”,&c);

while(c==‟y‟);

fclose(fp);

break;

case 2:

fp=fopen(“t.txt”,”rw”);

getdetail();

fwrite((char*)&a,sizeof(a),1,fp);

fclose(fp);

break;

case 3:

fp=fopen(“t.txt”,”rw”);

fseek(fp,addr-(7*ad),SEEK_SET);

while(fread(char*)&a,sizeof(a),1,fp);

displaydetail();

100
fclose(fp);

break();

case 4:

manage();

break;

case 5:

displaypassdetail();

break;

while(ch<=5);

fclose(fp);

h;

void reserve()

int ch;

do

printf(“1.Reserve \n2.Return to the main menu\n”);

printf(“Enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

101
case 1:

res();

break;
}

while(ch==1)

getch();

void res()

struct detail a;

struct reser b;

FILE*fp1,fp2;

time_t t;

int ch;

getresdet();

fp1=fopen(“t.txt”,”rw”);

fp2=fopen(“p.txt”,”rw”);

while(fread((char*)&a,sizeof(a),1,fp1))

if(a.tno==b.tno)

if(strcmp(b.clas,f)==0)

if(a.c1>=b.nosr)

102
{

amt=a.c1fare;

addr=ftell(fp1);

ad=sizeof(a.c1);

fseek(fp1,addr-(7*ad),SEEK_SET);

a.c1=a.c1-b.nosr;

fwrite((char*)&a.c1,sizeof(a.c1),l,fp1);

if(b.con==1)

printf(“Concession category: MILITARY PERSONNEL\n”);

b.amc=b.nosr*((amt*50)/100);

else if(b.con==2)

printf(“Concession category:SENIOR CITIZEN\n”);

b.amc=b.nosr*((amt*60)/100);

else if(b.con==3)

printf(“Concession category:CHILDREN BELOW FIVE\n”);

b.amc=0.0;

else if(b.con==4)

printf(“You cannot get any concession\n”);

103
b.amc=b.nosr*amt;

srand((unsigned)time(&t));

b.pnr=rand();

fwrite((char*)&b,sizeof(b),1,fp2);

displayresdet();

printf(“ \n”);

printf(“------------------------Your ticket is reserved -------\n”);

printf(“--------------------------End of reservation menu----------------\n”);

else

printf(“*******************Sorry req seats not available**************\n”);

else if(strcmp(b.clas,s)==0)

if(a.c2>=b.nosr)

amt=a.c2fare;

addr=ftell(fp1);

ad=sizeof(a.c2);

fseek(f1,addr-(7*ad),SEEK_SET);

a.c2=a.c2-b.nosr;

fwrite((char*)&a.c2,sizeof(a.c2),1,fp1);

104
if(b.con==1)

printf(“Concession category:MILITARY PERSONNEL\n”);

b.amc=b.nosr*((amt*50)/100);

else if(b.con==2)

printf(“Concession category:SENIOR CITIZEN\n”);

b.amc=b.nosr*((amt*60)/100);

else if(b.cpn==3)

printf(“Concession category: CHILDREN BELOW FIVE\n”);

b.amc=0.0;

else if(b.con==4)

printf(“You cannot get any concession\n”);

b.amc=b.nosr*amt;

fwrite((chra*)&b,sizeof(b),1,fp2);

displayreddet();

printf(“ \n”);

printf(“-------------------Your ticket is reserved--------------\n”);

printf(“ End of reservation \n”);

105
}

else

printf(“**************Sorry req no of seats not available*****************\n”);

getch();

goto h;

else

flag=0;

if(flag==0)

printf(“……………………Wrong train no…..................\n”);

printf(“…………Enter the train no from the data base.................\n”);

close(fp1);

close(fp2);

getch();

h:

void displaypassdetail()

106
{

FILE*fp;

struct reser b;

fopen(“p.txt”,”rw”);

fseek(fp,addr-(7*ad),SEEK_SET);

while(fread((char*)&b,sizeof(b),1,fp))

displayresdet();

fclose(fp);

getch();

void enquiry()

{
struct detail a;

FILE*fp;

fopen(“t.txt”,”rw”);

while(fread((char*)&a,sizeof(a),1,fp))

displaydetail();

getch();

void cancel()

107
struct detail a;

struct reser b;

struct canc c;

else if(b.con==3)

printf(“Concession category: CHILDREN BELOW FIVE\n”);

b.amc=0.0;

else if(b.con==4)

printf(“You cannot get any concession\n”);

b.amc=b.nosr*amt;

fwrite((char*)&b,sizeof(b),1,fp2);

displayresdet();

printf(“ \n”);

printf(“-----------------Your ticket is reserved-------------\n”);

printf(“-----------------End of reservation----------------\n”);

else

printf(“****************Sorry req no of seats not available************\n”);

getch();

108
goto h;

else

flag=0;

if(flag==0)

printf(“…………….Wrong train no…......................\n”);

printf(“……………….Enter the train no from the data base............................\n”);

close(fp1);

close(fp2);

getch();

h:

void displaypassdetail()

FILE*fp;

struct reser b;

fopen(“p.txt”,”rw”);

fseek(fp,addr-(7*ad),SEEK_SET);

while(fread((char*)&b,sizeof(b),1,fp));

displayresdet();

109
}

fclose(fp);

getch();

void enquiry()

{
struct detail a;

FILE*fp;

fopen(“t.txt”,”rw”);

while(fread((char*)&a,sizeof(a),1,fp));

displaydetail();

getch();

void cancell()

{
struct detail a;

struct reser b;

struct canc c;

int j;

FILE*fp1,*fp2,*fp3;

fp1=fopen(“t.txt”,”rw”);

fp2=fopen(“p.txt”,”rw”);

fp3=fopen(“cn.txt”,”rw”);

printf(“*******************CANCELLATION MENU****************\n”);

110
getcancdet();

if(b.pnr==c.pnr)

c.tno=b.tno;

strcpy(c.tname,b.tname);

strcpy(c.bp,b.bp);

strcpy(c.dest,b.dest);

c.nosc=b.nosr;

for(j=0;j<c.nosc;j++)

strcpy(c.pname[j],b.pname[j]);

c.age[j]=b.age[j];

strcpy(c.clas,b.clas);

if(strcmp(c.clas,f)==0)

while(fread((char*)&a,sizeof(a),1,fp1))

if(a.tno==c.tno)

a.c1=a.c1+c.nosc;

d=a.d;

m=a.m;

addr=ftell(fp1);

111
ad=sizeof(a.c1);

fseek(fp1,addr-(7*ad),SEEK_SET);

fwrite((char*)&a.c1,sizeof(a.c1),1,fp1);

tamt=b.amc;

if((c.d==d)&&(c.m==m))

printf(“You are cancelling at the date of departure\n”);

c.amr=tamt-((tamt*60)/100);

else if(c.m==m)

printf(“You are cancelling at the month of departure\n”);

c.amr=tamt-((tamt*50)/100);

else if(m>c.m)

printf(“You are cancelling one month before the date of departure\n”);

c.amr=tamt-((tamt*20)/100);

else

printf(“Cancelling after the departure\n”);

printf(“Your request cannot be completed\n”);

goto h;

112
displaycancdet();

else if(strcmp(c.clas,s)==0)

while(fread((char*)&a,sizeof(a),1,fp1))

if(a.tno==c.tno)

a.c2=a.c2+c.nosc;

d=a.d;

m=a.m;

addr=ftell(fp1);

ad=sizeof(a.c2);

fseek(fp1,addr-(5*ad),SEEK_SET);

fwrite((char*)&a.c2,sizeof(a.c2),1,fp1);

tamt=b.amc;

if((c.d==d)&&(c.m==m))

printf(“You are cancelling at the date of departure\n”);

c.amr=tamt-((tamt*60)/100);

else if(c.m==m)

113
printf(“You are cancelling at the month of departure\n”);

c.amr=tamt-((tamt*50)/100);

else

printf(“You are cancelling one month before the date of departure\n”);

c.amr=tamt-((tamt*20)/100);

else

printf(“Cancelling after the departure\n”);

printf(“Your request cannot be completed\n”);

goto h;

displaycancdet();

else

flag=0;

h:

if(flag==0)

114
{

printf(“Enter the correct pnr no\n”);

fclose(fp1);

fclose(fp2);

fclose(fp3);

getch();

void can()

int ch;

do

printf(“………………………..CANCELLATION MENU........................................\n”);

printf(“1.cancell\n2.Return to the main menu\n”);

printf(“Enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

case 1:

cancell();

break;

while(ch==1)

115
getch();

void user()

struct login l;

int ch;

char *password;

char id[100];

FILE *fp;

printf(“****************************************”);

printf(“**********************WELCOME TO THE USER


MENU***************\n”);

printf(“******************************\n”);

fp=fpopen(“id.txt”,”rw”);

puts(“Enter your id:”);

gets(id);

password=getpass(“Enter your password”);

while(fread((char*)&l,sizeof(l),1,fp))

if((strcmp(l.id,id)==0)&&(strcmp(l.pass,password)==0))

do

printf(“1.Reserve\n2.Cancell\n3.Enquiry\n4.Return to the main menu\n”);

printf(“Enter your choice:”);

116
scanf(“%d”,&ch);

switch(ch)

case 1:

reserve();

break;

case 2:

cancell();

break;

case 3:

enquiry();

break;

while(ch<=3);

goto j;

else

{ d=
1;

if(d==1)

117
printf(“Enter your user id and password correctly\n”);

getch();

j:

void manage()

int ch;

char c;

FILE *fp;

struct login l;

printf(“............................WELCOME TO THE USER MANAGEMENT


MENU..................................\n”);

do

printf(“1.create id data base\n2.Add details\n”);

printf(“3.Display details\n4.Return to the main menu\n”);

printf(“Enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

case 1:

fp=fopen(“id.txt”,”rw”);

do

118
getid();

fwrite((char*)&l,sizeof(l),1,fp);

printf(“Do you want to add one more record\n”);

printf(“y-Yes\n n-No\n”);

scanf(“%d”,&c);

while(c==‟y‟);

fclose(fp);

break;

case 2:

fp=fopen(“id.txt”,”rw”);

getid();

fwrite((char*)&l,sizeof(l),1,fp)

fclose(fp);

break;

case 3:

fp=fopen(“id.txt”,”rw”);

fseek(fp,addr-(7*ad),SEEK_SET);

while(fread((char*)&l,sizeof(l),1,fp))

displayed();

fclose(fp);

break;

119
}

while(ch<=3);

getch();

OUTPUT:

WELCOME TO RAILWAY RESERVATION SYSTEM

MAIN MENU

1.Admin mode

2.User mode

3.Exit

Enter your choice: 1

Enter the administrator password:

…………………………ADMINISTRATOR MENU…………………………………

1.Create detail data base

2.Add details

3.Display details

4.User management

5.Display passenger details

6.Return to main menu

Enter your choice: 1

Enter the details as follows

Train no: 16128

Train name: GUV express

120
Boarding point: NCJ

Destination pont: MS

No of seats in first class & fare per ticket: 30

380

No of seats in second class & fare per ticket: 30

220

Date of travel:01:11:2017

Do you want to add one more record?

y-for Yes

n-for No

Enter the details as follows

Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

Destination point: MS

No of seats in first class & fare per ticket: 30

1080

No of seats in second class & fare per ticket: 30

410

Date of travel:02:11:2017

Do you want to add one more record?

y-for Yes

n-for No

121
Enter the details as follows

Train no: 12637

Train name: Vaigai Express

Bording point: MDU

Destination point: MS

No of seats in first class & fare per ticket: 20

180

No of seats in second class & fare per ticket: 20

100

Date of travel:03:11:2017

Do you want to add one more record?

y-for Yes

n-for No

……………………………ADMINISTRATOR
MENU………………………………………

1.Create detail data base

2.Add details

3.Display details

4.User management

5.Display passenger details

6.Return to main menu

Enter your choice: 3

Train no: 16128

Train name: GUV express

122
Boarding point: NCJ

Destination point: MS

c1: 30

c2: 30

c1fare:380

c2fare:220

date:01:11:2017

Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

destination point: MS

c1: 30

c2: 30

c1fare: 1080

c2fare: 410

date: 02:11:2017

Train no: 12637

Train name: Vaigai Express

Boarding point: MDU

destination point: MS

c1: 20

c2: 20

c1fare: 180

c2fare: 100

date: 03:11:2017

123
…………………………………ADMINISTRATOR
MENU……………………………………

1.Create detail data base

2.Add details

3.Display details

4.User management

5.Display passenger details

6.Return to main menu

Enter your choice: 6

MAIN MENU

1.Admin mode

2.User mode

3.Exit

Enter your choice: 2

****************************************************************

******************WELCOME TO THE USER MENU********************

Enter your id: sugitha

Enter your password:

1. Reserve

2. Cancell

3.Enquiry

4.Return to the main menu

Enter your choice:1

1.Reserve

124
2.Return to the main menu

Enter your choice:1

Enter the details as follows

Train no:16128

Train name: GUV Express

Boarding point: NCJ

Destination point: MS

No of seats required: 5

Passenger name: Raja

Passenger age: 39

Passenger name: Rani

Passenger age:37

Passenger name: Anjali

Passenger age: 25

Passenger name: Camey

Passenger age: 20

Passenger name: Jemi

Passenger age: 18

Enter the class f-first class s-second class: f

Date of travel: 01:11:2017

Enter the concession category

1.Military

2.Senior citizen

3.Children below 5 yrs

4.None

125
4

…………………………..END OF GETTING DETAILS……………………………..

You cannot get any concession

x8271234567

Your ticket is reserved

End of reservation menu

………………………………………………………………………………………………
…..

……………………………………………………………………………………

Pnr no: 8271234567

Train no: 16128

Train name: GUV Express

Boarding point: NCJ

Destination point: MS

No of seats reserved: 5

Passenger name: Raja

Passenger age: 39

Passenger name: Rani

Passenger age:37

Passenger name: Anjali

Passenger age: 25

Passenger name: Camey

Passenger age: 20

Passenger name: Jemi

126
Passenger age: 18

Your class: f

Date of reservation: 01.11.2017

Your concession category: 4

You must pay: 5400

******************************************************************

……………..………………………….END
OFRESERVATION………………………………………………..

*********************************************************************

1.Reserve

2.Return to the main menu

Enter your choice: 1

Enter the details as follows

Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

Destination point: MS

No of seats required: 1

Passenger name: jesica

Passenger age: 35

Enter the class f-first class s-second class: s

Date of travel: 02.11.2017

Enter the concession category

1.Military

2. Senior citizen

127
3. Children below 5 yrs

4.None

……………………………………….END OF GETTING
DETAILS……………………..

You cannot get any concession

6358193729

Your ticket is reserved

End of reservation menu

………………………………………………………………………………………………
……………

………………………………………………………………………………………………
…………….

Pnr no: 6358193729

Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

Destination point: MS

No of seats required: 1

Passenger name: jesica

Passenger age: 35

Your class: s

Date of reservation: 02.11.2017

You must pay: 410

******************************************************************

128
…………………………………..END OF
RESERVATION………………………………………………………

*******************************************************************

1.Reserve

2.Retutn to the main menu

Enter your choice: 2

1.Reserve

2.Cancell

3.Enquiry

4.Return to the main menu

Enter your choice: 2

…………………………………………CANCELLATION
MENU……………………………………………….

1. Cancell

2. Return to the main menu

Enter your choice: 1

**********************CANCELLATION MENU***************************

Enter the details as follows

Pnr no: 6358193729

Date of cancellation: 02.11.2017

………………………………END OF GETTING
DETAILS…………………………………………….

You are cancelling at the date of departure

……………………………………………………………….

………………………………………………………………….

Pnr no: 6358193729

129
Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

Destination point: MS

no of seats to be cancelled: 1

Passenger name: jesica

Passenger age: 35

Your class: s

Date of cancellation: 02.11.2017

You can collect: 410

********************************************************

……………………….END OF
CANCELLATION…………………………………………

c1fare: 180

c2fare: 100

c2:20

************************************************************

…………………………………………CANCELLATION
MENU…………………………………..

1. Cancell

2. Return to the main menu

Enter your choice: 2

1.Reserve

2.Cancell

3.Enquiry

4.Return to the main menu

130
Enter your choice: 3

Train no: 16128

Train name: GUV express

Boarding point: NCJ

Destination point: MS
c1: 30

c2: 30

c1fare: 380

c2fare: 220

date: 01.11.2017

Train no: 12636

Train name: Kanyakumari Express

Boarding point: NCJ

Destination point: MS

c1: 30

c2: 30

c1fare: 1080

c2fare: 410

date: 02:11:2017

Train no: 12637

Train name: Vaigai Express

Boarding point: MDU

Destination point: MS
c1:20

date: 03:11:2017

1. Reserve

131
2. Cancell

3.Enquiry

4.Return to the main menu

Enter your choice: 4

MAIN MENU

1.Admin mode

2.User mode

3.Exit

Enter your choice: 3

RESULT:
The C program to simulate railway reservation system using function modules was
successfully executed.

132
Ex.No: 19
CIRCULAR LINKED LIST
Date:

AIM:
To write a C program to perform Circular linked list.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare variables.
Step 3: Display the menu options.
Step 4: Read the option.
Step 5: If choice is 1, then creating elements in the list.
Step 6: If choice is 2, then inserting elements at beginning of the list
Step 6.1: Create a newNode with given value.
Step 6.2: Check whether list is Empty (head == NULL)
Step 6.3: If it is Empty then, set head = newNode and newNode→next = head .
Step 6.4: If it is Not Empty then, define a Node pointer 'temp' and initialize with
'head'.
Step 6.5: Keep moving the 'temp' to its next node until it reaches to the last node
(until 'temp → next == head').
Step 6.6: Set 'newNode → next =head', 'head = newNode' and 'temp →
next = head'.
Step 7: If choice is 3, then inserting elements at Specific location in the list (After a
Node)
Step 7.1: Create a newNode with given value.
Step 7.2: Check whether list is Empty (head == NULL)
Step 7.3: If it is Empty then, set head = newNode and newNode → next = head.
Step7.4: If it is Not Empty then, define a node pointer temp and initialize
with head.
Step 7.5: Keep moving the temp to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 → data is equal
to location, here location is the node value after which we want to insert
the newNode).
Step 7.6: Every time check whether temp is reached to the last node or not
Step 7.7: If temp is reached to the exact node after which we want to insert the
newNode then check whether it is last node (temp → next == head).
Step 7.8: If temp is last node then set temp → next = newNode and newNode →
next = head.
Step 7.9: If temp is not last node then set newNode → next = temp →
next and temp → next = newNode.
Step 8: If choice is 4, then deleting elements from beginning of the list
Step 8.1: Check whether list is Empty (head == NULL)

133
Step 8.2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 8.3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2'
and initialize both 'temp1' and 'temp2' with head.
Step 8.4: Check whether list is having only one node (temp1 → next == head)
Step 8.5: If it is TRUE then set head = NULL and delete temp1.
Step 8.6: If it is FALSE move the temp1 until it reaches to the last node.
(until temp1 → next == head )
Step 8.7: Then set head = temp2 → next, temp1 → next = head and delete temp2.

Step 9: If choice is 5, then Deleting an elements in specific node from the list
Step 9.1: Check whether list is Empty (head == NULL)
Step 9.2: If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 9.3: If it is Not Empty then, define two Node pointers 'temp1' and 'temp2'
and initialize 'temp1' with head.
Step 9.4: Keep moving the temp1 until it reaches to the exact node to be deleted
or to the last node. set 'temp2 = temp1' before moving the 'temp1' to its
next node.
Step 9.5: If it is reached to the last node then display 'Given node not found in the
list! Deletion not possible!!!'.
Step 9.6: If it is reached to the exact node which we want to delete, then check
whether list is having only one node (temp1 → next == head)
Step 9.7: If list has only one node and that is the node to be deleted then
set head = NULL and delete temp1 (free(temp1)).
Step 9.8: If list contains multiple nodes then check whether temp1 is the first node
in the list (temp1 == head).
Step 9.9: If temp1 is the first node then set temp2 = head and keep
moving temp2 to its next node until temp2 reaches to the last node.
Then set head = head → next, temp2 → next = head and delete temp1.
Step 9.10: If temp1 is not first node then check whether it is last node in the list
(temp1 → next == head).
Step 9.11: If temp1 is last node then set temp2 → next = head and
delete temp1 (free(temp1)).
Step 9.12: If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1 (free(temp1)).
Step 10: If choice is 6, then displaying a elements in circular linked list
Step 10.1: Check whether list is Empty (head == NULL)
Step 10.2: If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 10.3: If it is Not Empty then, define a Node pointer 'temp' and initialize
with head.
Step 10.4: Keep displaying temp → data with an arrow (--->) until temp reaches
to the last node
Step 10.5: Finally display temp → data with arrow pointing to head → data.
Step 11: Stop the program.

134
PROGRAM:

#include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node *link;

};

struct node *head = NULL, *x, *y, *z;

void create();

void ins_at_beg();

void ins_at_pos();

void del_at_beg();

void del_at_pos();

void traverse();

void search();

void sort();

void update();

void rev_traverse(struct node *p);

void main()

int ch;

printf("\n 1.Creation \n 2.Insertion at beginning \n 3.Insertion at remaining"); printf("\

n4.Deletion at beginning \n5.Deletion at remaining \n6.traverse"); printf("\n7.Search\n8.sort\

n9.update\n10.Exit\n");

while (1)

135
{

printf("\n Enter your choice:");

scanf("%d", &ch);

switch(ch)

case 1:

create();

break;

case 2:

ins_at_beg();

break;

case 3:

ins_at_pos();

break;

case 4:

del_at_beg();

break;

case 5:

del_at_pos();

break;

case 6:

traverse();

break;

case 7:

search();

break;

136
case 8:

sort();

break;

case 9:

update();

break;

case 10:

rev_traverse(head);

break;

default:

exit(0);

/*Function to create a new circular linked list*/

void create()

int c;

x = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &x->data);

x->link = x;

head = x;

printf("\n If you wish to continue press 1 otherwise 0:");

scanf("%d", &c);

while (c != 0)

137
{

y = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &y->data);

x->link = y;

y->link = head;

x = y;

printf("\n If you wish to continue press 1 otherwise 0:");

scanf("%d", &c);

/*Function to insert an element at the begining of the list*/

void ins_at_beg()

x = head;

y = (struct node*)malloc(sizeof(struct node));

printf("\n Enter the data:");

scanf("%d", &y->data);

while (x->link != head)

x = x->link;

x->link = y;

y->link = head;

head = y;

138
/*Function to insert an element at any position the list*/

void ins_at_pos()

struct node *ptr;

int c = 1, pos, count = 1;

y = (struct node*)malloc(sizeof(struct node));

if (head == NULL)

printf("cannot enter an element at this place");

printf("\n Enter the data:");

scanf("%d", &y->data);

printf("\n Enter the position to be inserted:");

scanf("%d", &pos);

x = head;

ptr = head;

while (ptr->link != head)

count++;

ptr = ptr->link;

count++;

if (pos > count)

printf("OUT OF BOUND");

139
return;

while (c < pos)

z = x;

x = x->link;

c++;

y->link = x;

z->link = y;

/*Function to delete an element at any begining of the list*/

void del_at_beg()

if (head == NULL) printf("\

n List is empty");

else

x = head;

y = head;

while (x->link != head)

x = x->link;

head = y->link;

x->link = head;

140
free(y);

/*Function to delete an element at any position the list*/

void del_at_pos()

if (head == NULL) printf("\

n List is empty");

else

int c = 1, pos;

printf("\n Enter the position to be deleted:");

scanf("%d", &pos);

x = head;

while (c < pos)

y = x;

x = x->link;

c++;

y->link = x->link;

free(x);

/*Function to display the elements in the list*/

141
void traverse()

if (head == NULL) printf("\

n List is empty");

else

x = head;

while (x->link != head)

printf("%d->", x->data);

x = x->link;

printf("%d", x->data);

/*Function to search an element in the list*/

void search()

int search_val, count = 0, flag = 0;

printf("\nenter the element to search\n");

scanf("%d", &search_val);

if (head == NULL)

printf("\nList is empty nothing to search");

else

x = head;

142
while (x->link != head)

if (x->data == search_val)

printf("\nthe element is found at %d", count);

flag = 1;

break;

count++;

x = x->link;

if (x->data == search_val)

printf("element found at postion %d", count);

if (flag == 0)

printf("\nelement not found");

/*Function to sort the list in ascending order*/

void sort()

struct node *ptr, *nxt;


143
int temp;

if (head == NULL)

printf("empty linkedlist");

else

ptr = head;

while (ptr->link != head)

nxt = ptr->link;

while (nxt != head)

if (nxt != head)

if (ptr->data > nxt->data)

temp = ptr->data;

ptr->data = nxt->data;

nxt->data = temp;

else

break;
144
}

nxt = nxt->link;

ptr = ptr->link;

/*Function to update an element at any position the list*/

void update()

struct node *ptr;

int search_val;

int replace_val;

int flag = 0;

if (head == NULL)

printf("\n empty list");

else

printf("enter the value to be edited\n");

scanf("%d", &search_val);

fflush(stdin);

printf("enter the value to be replace\n");

scanf("%d", &replace_val);

ptr = head;

145
while (ptr->link != head)

if (ptr->data == search_val)

ptr->data = replace_val;

flag = 1;

break;

ptr = ptr->link;

if (ptr->data == search_val)

ptr->data = replace_val;

flag = 1;

if (flag == 1)

printf("\nUPdate sucessful");

else

printf("\n update not successful");

146
/*Function to display the elements of the list in reverse order*/

void rev_traverse(struct node *p)

int i = 0;

if (head == NULL)

printf("empty linked list");

else

if (p->link != head)

i = p->data;

rev_traverse(p->link);

printf(" %d", i);

if (p->link == head)

printf(" %d", p->data);

OUTPUT:

1. Creation

2. Insertion at beginning

147
3. Insertion at remaining

4.Deletion at beginning

5.Deletion at remaining

6.traverse

7.Search

8.sort

9.update

10.Exit

Enter your choice:6

List is empty

Enter your choice:5

List is empty

Enter your choice:9

empty list

Enter your choice:7

enter the element to search

12

List is empty nothing to search

Enter your choice:1

Enter the data:10

If you wish to continue press 1 otherwise 0:0

Enter your choice:3

Enter the data:20

Enter the position to be inserted:5

OUT OF BOUND

Enter your choice:2

148
Enter the data:12

Enter your choice:6

12->10

Enter your choice:3

Enter the data:13

Enter the position to be inserted:3

Enter your choice:3

Enter the data:14

Enter the position to be inserted:4

Enter your choice:6

12->10->13->14

Enter your choice:3

Enter the data:24

Enter the position to be inserted:4

Enter your choice:6

12->10->13->24->14

Enter your choice:3

Enter the data:10

Enter the position to be inserted:100

OUT OF BOUND

Enter your choice:4

Enter your choice:6

10->13->24->14

Enter your choice:5

Enter the position to be deleted:4

Enter your choice:6

149
10->13->24

Enter your choice:5

Enter the position to be deleted:2

Enter your choice:6

10->24

Enter your choice:9

enter the value to be edited

23

enter the value to be replace

24

update not successful

Enter your choice:9

enter the value to be edited

24

enter the value to be replace

26

UPdate sucessful

Enter your choice:6

10->26

Enter your choice:7

enter the element to search

26

element found at postion 1

element not found

Enter your choice:7

enter the element to search

150
27

element not found

Enter your choice:8

Enter your choice:6

10->26

Enter your choice:10

26 10

Enter your choice:11

RESULT:
The program to perform a circular linked list was successfully executed in c.

151
Ex.No: 20 STACK OPERATION

Date:

AIM:
To write a C program to perform stack operation.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare variables.
Step 3: Display the menu options.
Step 4: Read the option.
Step 5: If choice is 1, then it perform push operation,
Step 5.1: Checks if the stack is full.
Step 5.2: If the stack is full, produces an error and exit.
Step 5.3: If the stack is not full, increments top to point next empty space.
Step 5.4: Adds data element to the stack location, where top is pointing.
Step 5.5: Returns success.
Step 6: If choice is 2, then it perform pop operation,
Step 6.1: Checks if the stack is empty.
Step 6.2: If the stack is empty, produces an error and exit.
Step 6.3: If the stack is not empty, accesses the data element at which top is
pointing.
Step 6.4: Decreases the value of top by 1.
Step 6.5: Returns success.
Step 7: If choice is 3, then it perform display operation, it check the status of stack
whether it is full or empty.
Step 8: Stop the program.

PROGRAM:

#include <stdio.h>

#define MAXSIZE 5

struct stack

int stk[MAXSIZE];

int top;

};

152
typedef struct stack STACK;

STACK s;

void push(void);

int pop(void);

void display(void);

void main ()

int choice;

int option = 1;

s.top = -1;

printf ("STACK OPERATION\n");

while (option)

printf (" \n");

printf (" 1 --> PUSH \n");

printf (" 2 --> POP \n");

printf (" 3 --> DISPLAY \n");

printf (" 4 --> EXIT \n");

printf (" \n");

printf ("Enter your choice\n");

scanf ("%d", &choice);

switch (choice)

case 1:

push();

153
break;

case 2:

pop();

break;

case 3:

display();

break;

case 4:

return;

fflush (stdin);

printf ("Do you want to continue(Type 0 or 1)?\n");

scanf ("%d", &option);

/* Function to add an element to the stack */

void push ()

int num;

if (s.top == (MAXSIZE - 1))

printf ("Stack is Full\n");

return;

else

154
printf ("Enter the element to be pushed\n");

scanf ("%d", &num);

s.top = s.top + 1;

s.stk[s.top] = num;

return;

/* Function to delete an element from the stack */

int pop ()

int num;

if (s.top == - 1)

printf ("Stack is Empty\n");

return (s.top);

else

num = s.stk[s.top];

printf ("poped element is = %dn", s.stk[s.top]);

s.top = s.top - 1;

return(num);

/* Function to display the status of the stack */

void display ()

155
{

int i;

if (s.top == -1)

printf ("Stack is empty\n");

return;

else

printf ("\n The status of the stack is \n");

for (i = s.top; i >= 0; i--)

printf ("%d\n", s.stk[i]);

printf ("\n");

OUTPUT:

STACK OPERATION

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice


156
1

Enter the element to be pushed

34

Do you want to continue(Type 0 or 1)?

$ a.out

STACK OPERATION

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

Enter the element to be pushed

34

Do you want to continue(Type 0 or 1)?

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice


157
2

poped element is = 34

Do you want to continue(Type 0 or 1)?

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

Stack is empty

Do you want to continue(Type 0 or 1)?

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

Enter the element to be pushed

50

Do you want to continue(Type 0 or 1)?

158
1

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

Enter the element to be pushed

60

Do you want to continue(Type 0 or 1)?

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

The status of the stack is

60

50

159
Do you want to continue(Type 0 or 1)?

1 --> PUSH

2 --> POP

3 --> DISPLAY

4 --> EXIT

Enter your choice

RESULT:
The program to perform a stack operation was successfully executed in c.

160

You might also like