Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

CS3271 –C Programming Lab Department of CSE & IT 2021-2022

DEPARTMENT OF INFORMATION TECHNOLOGY

I Year/II Semester – B.TECH (IT)

CS3271 – PROGRAMMING IN C LABORATORY


(As per Anna University)

2021 Regulation

Academic year 2021 - 2022

AGNI COLLEGE OF TECHNOLOGY


THALAMBUR, CHENNAI 600130

1
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

CS3271 PROGRAMMING IN C LABORATORY

COURSE OBJECTIVES
 To familiarize with C Programming constructs.
 To develop programs in C using basic constructs.
 To develop programs in C using arrays.
 To develop applications in C using strings, pointers, functions.
 To develop applications in C using structures.
 To develop applications in C using file processing.

LIST OF EXPERIMENTS
1. I/O statements, operators, expressions
2. Decision-making constructs:if-else, goto, switch-case,break-continue
3. Loops: for, while,do-while
4. Arrays: 1D and 2D, Multi-dimensional arrays, traversal
5. Strings: operations
6. Functions: call, return, passing parameters by( value, by reference), passing arrays to function
7. Recursion
8. Pointers: Pointers to functions, Arrays, Strings, Pointers to Pointers, Array of Pointers
9. Structures: Nested structures, Pointers to Structures, Arrays of structures and Unions
10. Files: reading and writing, File pointers, file operations, random access, processordirectives

COURSE OUTCOMES:
On completion of this lab course, the students will be able to

C116.1 Develop a C programs for simple applications with basic language constructs, arrays and strings.
Develop C programs involving functions, recursion, pointers, and structures and Design an applications
C116.2
using sequential and random access file.

2
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

LIST OF EXPERIMENTS

S.No Name of the Program Date Page Sign


No.
1 Programs using I/O statements and expressions.
2 Programs using decision-making constructs.
3 To find whether the given year is leap year or Not.
Design a calculator to perform the operations, namely, addition,
4
subtraction, multiplication, division and square of a number.
5 Check whether a given number is Armstrong number or not
Given a set of numbers like <10, 36, 54, 89, 12, 27>,
find sum of weights based on the following conditions :
5 if it is a perfect cube
6 4 if it is a multiple of 4 and divisible by 6
3 if it is a prime number
Sort the numbers based on the weight in the increasing order as shown
below <10,its weight>,<36,its weight><89,its weight>
Populate an array with height of persons and find how many persons
7
are above the average height.
Populate a two dimensional array with height and weight of persons
8
and compute the Body Mass Index of the individuals
Given a string ―a$bcd./fg‖ find its reverse without changing the
position of special characters. (Example input:a@gh%;j and
9
Output:j@hg%;a)
Convert the given decimal number into binary, octal and hexadecimal
10
numbers using user defined functions.
From a given paragraph perform the following using built-in
functions: a. Find the total number of words.
11
b. Capitalize the first word of each sentence.
c. Replace a given word with another word
12 Solve towers of Hanoi using recursion.
13 Sort the list of numbers using pass by reference.
14 Generate salary slip of employees using structures and pointers.
Compute internal marks of students for five different subjects using
15
structures and functions.
Insert, update, delete and append telephone details of an individual or
16
a company into a telephone directory using random access file
Count the number of account holders whose balance is less than the
17
minimum balance using sequential access file
Mini Project
Create a ―Railway reservation system‖ with the following modules
 Booking
18
 Availability checking
 Cancellation
 Prepare chart
19 Implementation Of Singly Linked Lists

3
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 1 PROGRAM USING I/O STATEMENTS AND EXPRESSIONS Date:

Aim:
To write programs using I/O statements and expressions

Algorithm:
Step1. Start
Step2. Read a character, a string, a float value, an integer number, a double value from the user using
scanf() statement
Step3.store it in respective variables ch, str, flt, num, dbl.
Step 4. Display all the variables using printf() statement.
Step 5.Stop
Program:
#include <stdio.h>
int main()
{
char ch, str[20];
float flt;
int num,a=6,b=3;
double dbl;
printf(“Enter a character\n”);
scanf(“%c”,&ch);
printf(“Enter a string\n”);
scanf(“%s”,&str);
printf(“Enter a float value\n”);
scanf(“%f”,&flt);
printf(“Enter an integer number\n”);
scanf(“%d”,&num);
printf(“Enter a double value\n”);
scanf(“%”,&dbl);
printf("Displaying:\n”);
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nExpressions:\n”);
printf("Infix value is %d\n" , ((a+(2*b))/2));
return 0;
}
Output:
Enter a character
'y'
Enter a string
“welcome”
Enter a float value

4
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

10.53
Enter an integer number
350
Enter a double value
20.23451
Displaying:
Character is
'y'
String is
“welcome”
Float value is
10.53
Integer value is
350
Double value is
20.23451
Expressions:
Prefix value is8
Postfix value is8
Infix value is8
Result:

5
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 2 PROGRAM USING DECISION-MAKING CONSTRUCTS Date:

Aim:
To find the largest of three numbers using if...else if.

Algorithm:
Step1.Start
Step2. Read the values of x, y and z.
Step 3. If x is greater than y and x is greater than z then print x is greatest, otherwise go to step 3.
Step 4. If y is greater than z then print y is greatest, otherwise go to step 4.
Step5. display z is greatest.
Step 6. Stop

Program:

#include<stdio.h>
void main()
{
int x,y,z;
printf("Enter the values for x,y and z \n");
scanf("%d%d%d",&x,&y,&z);
if((x>y)&& (x>z))
printf(" %d is greatest",x);
else if (y>z)
printf ("%d is greatest",y);
else
printf("%d is greatest",z);
}

Output:

Enter the values for x, y and z


25
46
22
46 is greatest

Result:

6
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 3 LEAP YEAR OR NOT Date:

Aim:
To find whether the given year is leap year or Not.

Algorithm:
Step1.Start
Step2. Get the input year from the user to check for leap year.
Step3. If the year is evenly divisible by 4, go to step 3. Otherwise, go to step 6.
Step4. If the year is evenly divisible by 100, go to step 4. Otherwise, go to step 5.
Step5. If the year is evenly divisible by 400, go to step 5. Otherwise, go to step 6.
Step6. The year is a leap year (it has 366 days).
Step7. The year is not a leap year (it has 365 days).
Step8.Stop
Program:

#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0)
{
if( year%100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
return 0;
}

Output:

Enter a year: 1900


1900 is not a leap year.

Result:

7
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 4 CALCULATORS Date:

Aim:
To design a calculator to perform the operations namely, addition, subtraction, multiplication,
division and square of a number.

Algorithm:

Step1.start
Step2.read a and b
Step3.print the menu (1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square)
Step4.read the choice
Step5.switch(ch)
Step5.1 Add
Step5.1.1 Result->a+b
Step 5.1.2 Print Result
Step5.2 Subtract
Step 5.2.1 Result->a-b
Step 5.2.2 Print Result
Step5.3Multiply
Step 5.3.1 Result->a*b
Step 5.3.2 Print Result
Step5.4Divide
Step 5.4.1 Result->a/b
Step 5.4.2 Print Result
Step5.5Square
Step 5.5.1 Result->a*a
Step 5.5.2 Result1->b*b
Step 5.5.3 Print Result,Result1

Step 6. stop

Program:
#include <stdio.h>
int main()
{
int a,b,result,sq1,sq2,ch;
float divide;
printf("Enter two integer");
scanf("%d%d",&a,&b);
printf("1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square");
printf("\nEnter the choice");
scanf("%d",&ch);
switch(ch)
{
case 1:

8
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

{
result=a+b;
printf("sum=%d\n",result);
break;
}
case 2:
{
result=a-b;
printf("Difference=%d\n",result);
break;
}
case 3:
{
result=a*b;
printf("Multiplication=%d\n",result);
break;
}
case 4:
{
result=a/(float)b;
printf("Divide=%d\n",result);
break;
}
case 5:
{
sq1=a*a;
printf("Square=%d\n",sql);
sq2=b*b;
printf("Second Square number=%d",sq2);
break;
}
}

}
Output:

Enter two integer: 2 3


1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square
Enter the choice :1
Sum =5

Enter two integer: 3 2


1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square
Enter the choice :2
Subtract =1
Enter two integer: 2 3
1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square
Enter the choice :3
Multiply =6

9
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Enter two integer: 2 3


1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square
Enter the choice :4
Divide =5
Enter two integer: 2 3
1.Add, 2.Subtract 3.Multiply 4.Divide 5.Square
Enter the choice :5
Square =4
Second Square number=9

Result:

10
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 5 ARMSTRONG NUMBER OR NOT Date:

Aim:
To check whether a given number is Armstrong number or not.

Algorithm:

Step1.Initialize the value of res to 0.


Step2.Read the three digit number in num variable to check for Armstrong number.
Step3.Assign originalNum to the variable num.
Step4.Extract the digits from the num.
Step5.Find the cube of each digit in num and add them and store it in variable res.
Step6.Repeat the step 5 untill the num is not equal to zero..
Step7.Compare the res and originalNum, if it is equal display the number is an Armstrong
number, otherwise display the number is not an Armstrong number.

Program:
#include <stdio.h>
int main()
{
int num, originalNum, rem, res = 0;
printf("Enter a three digit integer: ");
scanf("%d", &originalNum);
num = originalNum;
while (num != 0)
{
rem = num%10;
res+= rem*rem*rem;
num /= 10;
}
if(res == originalNum)
printf("%d is an Armstrong number.",originalNum);
else
printf("%d is not an Armstrong number.",originalNum);
return 0;
}

Output:

Enter a three digit integer:


153
153 is an Armstrong number

Result:

11
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 6 Sorting Weight Based on Condition Date:

Aim:
To write C program to calculate sum of weight of persons and sort them in ascending order.
Algorithm
Step 1.Start the program
Step2.Read nArray, wArray, n, elem.
Step3.Find the sum of the weight.
Step4.Sort the weight of the person based on condition
Step 4.1 5 if it is a perfect cube
Step 4.2 4 if it is a multiple of 4 and divisible by 6
Step 4.3 3 if it is a prime number
Step 5. Stop the program

Program:
#include <stdio.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 : ");
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;

12
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

if(prime(nArray[i]))
wArray[i] = wArray[i] + 3;

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

Output:
Enter the number of elements in an array : 5
Enter 5 elements
27
36
15
77
23
<15,0><23,3><27,5><36,4><77,0>

Result:

13
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

ExNo:7 Program to Accept the Height of a Person & categorize person above average height.
Date:
Aim:
To write a C program to calculate the height of persons and to find the number of persons above
the average height.

Algorithm:
Step1.Start the program.
Step2.Read the values n, a[100].
Step3.Calculate the sum and average height of all persons.
Step4.Find number of persons above average height.
Step5.Terminate the program.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
float a[100],n;
int i,count=0;
float sum=0;
float avg;
clrscr();
printf("Enter no. of person");
scanf("%f",&n);
printf("\nEnter the height of the person one by one");
for(i=0;i<n;i++)
{
printf("\n Enter the height of %d person",i+1);
scanf("%f",&a[i]);
}
for(i=0;i<n;i++)
sum=sum+a[i];
avg=sum/n;
for(i=0;i<n;i++)
{
if (a[i]>avg)
count=count+1;
}
printf("Sum of the height of all person=%f",sum);
printf("Average height of all the person=%f",avg);
printf("\n Number of persons above average height are %d",count);
getch();
}
OUTPUT:
Enter no. of person 5

14
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Enter the height of the person one by one


Enter the height of 1 person : 4.8
Enter the height of 2 person : 5.6
Enter the height of 3 person : 5
Enter the height of 4 person : 5.2
Enter the height of 8 person : 5.9
Sum of the height of all person = 26.499998
Average height=5.300000
Number of person above average height are 2
Result:

15
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

ExNo: 8 Calculate Body Mass Index Date:

Aim:
To write C program to Populate a two dimensional array with height and weight of persons and
compute the Body Mass Index of the individuals.
Algorithm:
Step 1. Start the program and includes the header files.
Step 2. Take the height of a person as input and store it in the variable height and weight.
Step 3. Calculate BMI = (mass or weight)/(height*height) where, mass or weight is in Kg,height isin cm
Step 4. Terminate the program
.
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int stu[100][2];
int index[100];
int i,n;
float h;
clrscr();
printf("Enter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter the Height(cm) and Weight(kg) of student %d :",i+1);
scanf("%d%d",&stu[i][0],&stu[i][1]);
h = (float)(stu[i][0]/100.0);
index[i] = (float)stu[i][1]/(float)(h*h);
}
printf("\nStu.No.\tHeight\tWeight\tBMI\tResult\n");
for(i=0;i<n;i++)
{
printf("\n%d\t%d\t%d\t%d\t",i+1,stu[i][0],stu[i][1],index[i]);
if(index[i]<15)
printf("Starvation\n");
else if(index[i]>14 && index[i] < 18)
printf("Underweight\n");
else if(index[i] > 17 && index[i] < 26)
printf("Healthy\n");
else if(index[i] > 25 && index[i] < 31)
printf("Over weight\n");
else if(index[i] > 30 && index[i] < 36)
printf("Obese\n");
else
printf("Severe Obese\n");
} // for loop

16
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

getch();
}
Output:
Enter the number of students : 5
Enter the Height (cm) and Weight(kg) of student 1 : 140
44
Enter the Height (cm) and Weight(kg) of student 2 : 150
55
Enter the Height (cm) and Weight(kg) of student 3 : 140
54
Enter the Height (cm) and Weight(kg) of student 4 : 155
65
Enter the Height (cm) and Weight(kg) of student 5 : 156
51
Stu. No. Height Weight BMI Result
1 140 44 22 Healthy
2 150 55 24 Healthy
3 140 54 27 Over Weight
4 155 65 27 Over Weight
5 156 51 20 Healthy

Result:

17
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex. No: 9 Reverse String Date:


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

Algorithm:

Step1.Start the program and include the header files such as <stdio.h>, <string.h> and <ctype.h>.
Step2.Define the swap function to swap the given strings and reverse function to print the
stringStep3.in reverse order without changing the special characters.
Step4.In the main function, declare the char variable and pass the given strings.
Step5.Using strcpy method, the given string will be copied and stored it in an another variable.
Step6.Then the reverse function will be called using the function name and the given strings will be
executed.
Step7.At the end of the program the given string will be displayed in a reverse order without
affecting the special characters.

Program:

#include <stdio.h>
#include <string.h>
#include <conio.h>
void swap(char *a, char *b)
{
char t;
t = *a;
*a = *b;
*b = t;
}

// Main program
void main()
{
char str[100];
// Function Prototype
void reverse(char *);
int isAlpha(char);
void swap(char *a ,char *b);
clrscr();
printf("Enter the Given String : ");
// scanf("%[^\n]s",str);
gets(str);
reverse(str);
printf("Reverse String : %s",str);
getch();
}

18
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

void reverse(char str[100])


{
// Initialize left and right pointers
int r = strlen(str) - 1, l = 0;

// Traverse string from both ends until


// 'l' and 'r'
while (l < r)
{
// Ignore special characters
if (!isAlpha(str[l]))
l++;
else if(!isAlpha(str[r]))
r--;

else
{
swap(&str[l], &str[r]);
l++;
r--;
}
}
}

// To check x is alphabet or not if it an alphabet then return 0 else 1

int isAlpha(char x)
{
return ( (x >= 'A' && x <= 'Z') ||
(x >= 'a' && x <= 'z') );
}

Output
Enter the Given String : s@q%r&1*vt
Reverse String : t@v%r&1*qs

Result:

19
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No :10 Convert the given decimal number into binary, octal and hexadecimal numbers

Aim: Date:
To write a C program to convert the given decimal number into binary, octal and hexadecimal
numbers using user defined functions.

Algorithm:
Step1.Start the program and includes the header files.
Step2.Declare a input that takes a decimal number and converts it into binary, octal and hexadecimal
equivalents.
Step3.User defined functions are defined for each type of conversion.
Step4.The number given by the user is send to each of the user defined functions.
Step5.Use switch case to display each of the options and get choice for the user.
Step6.Terminate the program.

Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void dec_bin(long int num);
void dec_oct(long int num);
void dec_hex(long int num);
int main()
{
long int num;
clrscr();

printf("Enter the decimal number : ");


scanf("%ld",&num);

dec_bin(num);
dec_oct(num); // Calling function
dec_hex(num);
return 0;
}

void dec_bin(long int num) // Function Definition


{
long int rem[50],i=0,length=0;
while(num>0)
{
rem[i]=num%2;
num=num/2;
i++;
length++;
}
printf("\nBinary number : ");

20
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

for(i=length-1;i>=0;i--)
printf("%ld",rem[i]);
}

void dec_oct(long int num) // Function Definition


{
long int rem[50],i=0,length=0;
while(num>0)
{
rem[i]=num%8;
num=num/8;
i++;
length++;
}
printf("\nOctal number : ");
for(i=length-1;i>=0;i--)
printf("%ld",rem[i]);
}
void dec_hex(long int num) // Function Definition
{
long int rem[50],i=0,length=0;

while(num>0)
{
rem[i]=num%16;
num=num/16;
i++;
length++;
}

printf("\nHexadecimal number : ");


for(i=length-1;i>=0;i--)
{
switch(rem[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");

21
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

break;
case 15:
printf("F");
break;
default :
printf("%ld",rem[i]);
}
}
getch();
}
Output:
Enter the decimal number : 52
Binary number : 110100
Octal number : 64
Hexadecimal : 34

Result:

22
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 11(a) Find the total number of words Date:


.
Aim:

To Find the total number of words in the given string.

Algorithm:

Step1.Start the program and includes the header files.


Step2. Read the variable s,count and i
Step3. Using the looping statement check the s[i]==’ ‘
Step4. if condition is true increment the count. Repeat it until s[i]!=’\0’
Step5.Terminate the program.

Program:
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count=0,i;
printf(“Enter the string”);
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);
}

Output:
Enter the string: c programming lab exercise
Number of words in given string are 4

Result :

23
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 11(b) Capitalize the first word of each sentence Date:


Aim:

To Capitalizethe first word of each sentence.


Algorithm:
Step1.Start the program and includes the header files.
Step2. Read the variable str and i
Step3. Using the looping statement do the following steps until str[i]!=`\0`;i++)
Step3.1. check the condition str[i]>=`a` and str[i]<=`z`
Step3.2. if true assign the str[i]-32 to str[i]
Step3.3.else if check the condition str[i]>=`A` and str[i]<=`Z`
Step3.4. if true assign the str[i]+32 to str[i]
Step4. Print the string
Step5.Stopthe program.

Program:
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX]={0};
int i;
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]=str[i]-32;
continue;
}
if(str[i]==' ')
{
++i;
if(str[i]>='a' && str[i]<='z')
{
str[i]=str[i]-32;
continue;
}
}
else
{
if(str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32;
}

24
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

}
printf("Capitalize string is: %s\n",str);
return 0;
}

Output:
Enter a string: c programming laboratory
Capitalize string is: C Programming Laboratory

Enter a string: C PROGRAMMING LABORATORY


Capitalize string is: C Programming Laboratory

Result :

25
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 11(c) Replace a given word with another word Date:

Aim:
To replace a given word with another word.
Algorithm:
Step 1.Start the program and includes the header files.
Step 2. Read a string and its substring as input and store it in the newWand, oldW respectively.
Step 3. Compare each character with the array s[].
Step4. When both are same then override the current row with next row and so on upto the last row.
Step 5. Print the array str as output and exit
Step6. Stop the program.

Program:
char *replaceWord(const char *s, const char *oldW,
const char *newW)
{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);

// Counting the number of times old word


// occur in the string
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;

// Jumping to index after the old word.


i += oldWlen - 1;
}
}

// Making new string of enough length


result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);

i = 0;
while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;

26
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

}
else
result[i++] = *s++;
}

result[i] = '\0';
return result;
}

// Driver Program
int main()
{
char str[] = "xxforxx";
char c[] = "xx";
char d[] = "Geeks";

char *result = NULL;

// oldW string
printf("Old string: %sn", str);

result = replaceWord(str, c, d);


printf("New String: %sn", result);

free(result);
return 0;
}
Output:
Old string: xxforxx
New String: GeeksforGeeks
Total number of words :3
Total number of character in new string 13

Result :

27
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 12 Towers of Hanoi using recursion. Date:

Aim:
To solve towers of Hanoi using recursion.

Algorithm:
1. Define a function tower to recursively move across discs
2. Recursive functions are used for every n scenario
3. if(n==1) one disk is moved directly from from_rod to to_rod
4. Otherwise,n-1 disk are shifted.
5. Stop the program
Program:
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle


void tower(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;
}
tower(n-1, from_rod, aux_rod, to_rod);
printf("n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
tower(n-1, aux_rod, to_rod, from_rod);
}

void main()
{
int n = 4; // Number of disks
tower(n, 'A', 'C', 'B'); // A, B and C are names of rods
}
Output:
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
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
Result:

28
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 13 Sort the elements using pass by reference. Date:

Aim:
To sort the elements in an array by using pass by reference.
Algorithm:
1. Start
2. Get the number of elements n to be inserted in the array
3. Get the elements in arr[]
4. Intially the smallest number of the array is found using the smallest function
5. Using sort function,the smallest number is swapped to the k position
6. The above process is repeated for n elements using for loop
7. Return the sorted array arr and print it
8. Stop the program
Program:
#include<stdio.h>
int smallest(int arr[],int k,int n)//smallest function
{
int pos=k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void sort(int arr[],int n)//sorting function
{
int k,pos,temp;
for(k=0 ; k < n ; k++)
{
pos=smallest(arr,k,n);
temp=arr[k];
arr[k]=arr[pos];
arr[pos]=temp;
}
}

void main()
{
int arr[20],i,n,j,k;
printf("\nEnter the number of elements in the array: ");
scanf("%d",&n);

printf("\nEnter the elements of the array");


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

29
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

{
printf("\n arr[%d] = ",i);
scanf("%d",&arr[i]);
}
sort(arr,n);
printf("\nThe sorted array is: \n");
for(i=0 ; i< n ; i++)
printf("%d\t",arr[i]);
}
Output:
Enter the number of elements in the array:5
Enter the elements of the array4
1
5
2
6
The sorted array is:
1 2 4 5 6

Result:

30
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No:14 Generate salary slip of employees using structures and pointers. Date:

Aim:
To Generate salary slip of employees using structures and pointers.

Algorithm:
1. Start the program
2. Create a structure emp with structure variables name ,bpay, allo,ded and npay.
3. Create a structure pointer p to access each structure variables
4. Compute net pay using the formula npay=bpay+allo-ded
5. Display npay, bpay,all and ded using structure pointer p .
6. Terminate the program
Program:
#include<stdio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
};
void main()
{
struct emp e,*p;
int i, n ;
p=&e;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i< n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &(p+i)->empno) ;
printf("\nEnter the name : ") ;
scanf("%s", (p+i)->name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &(p+i)->bpay, &(p+i)->allow, &(p+i)->ded) ;
(p+1)->npay = (p+i)->bpay + (p+i)->allow - (p+i)->ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i< n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", (p+i)->empno,
(p+i)->name, (p+i)->bpay, (p+i)->allow, (p+i)->ded, (p+i)->npay) ;
}
}
Output:
Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250

31
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Enter the employee number : 102


Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow DedNpay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750
Result:

32
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 15 Compute internal marks of students for five different subjects using structures

Aim: Date:
To compute internal marks of students for five different subjects using structures and functions

Algorithm:
1. Start the program.
2. Create structure sub with three variables m1,m2and m3
3. Declare struct variable s to access structure members.
4. Get three assessment marks in m1 ,m2 ,m3 using struct variable
5. Compute internals using the formula internals=(result/150)*20 in function internal()
6. Repeat for five different subjects
7. Print the internals
8. Stop the program
Program
#include<stdio.h>
struct sub
{
int m1,m2,m3;
};
int internals(int m1,m2,m3)
{
int internals;
float result=0;
result=result+m1+m2+m3;
internals=(result/150)*20;
return internals;
}
void main()
{
struct sub s; //structure variable
int i,internal; //pointer to student structure
printf("\n Enter assesment marks obtained for 50in each subject: ");
for (i=1;i<=5;i++)
{ printf ("\n Enter marks obtained in subject%d ",i);

printf("\n Enter assessment 1mark");


scanf("%d",&s.m1);
printf("\n Enter assessment 2 mark");
scanf("%d",&s.m2);
printf("\n Enter assessment 3mark");
scanf("%d",&s.m3);
internal=internals(s.m1,s.m2,s.m3);
printf(“the internal is %d”,internal);
} }

Output:
Enter assesment marks obtained for 50 in each subject
Enter marks obtained in subject 1

33
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Enter assessment 1mark 25


Enter assessment 2 mark 25
Enter assessment 3mark 25
the internal is 10
Enter assesment marks obtained for 50 in each subject
Enter marks obtained in subject 2
Enter assessment 1mark 20
Enter assessment 2 mark 20
Enter assessment 3mark 20
the internal is 8
Enter assesment marks obtained for 50 in each subject
Enter marks obtained in subject 3
Enter assessment 1mark 40
Enter assessment 2 mark 40
Enter assessment 3mark 40
the internal is 16
Enter assessment 3mark 15
the internal is 6

Result:

34
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 16 Telephone Directories Using Random Access File Date:

Aim:

To create a telephone directory using random access file

Algorithm:

1. Start
2. Inserts person name and telephone number in a file
3. Display all records from a file
4. Search telephone number based on person name from a file
5. Search person name based on telephone number from a file
6. Update telephone number by providing person name
7. Stop

Program

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

struct person{
char name[20];
long telno;
};
void appendData(){
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","a");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);
}
void showAllData(){
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","r");
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t===============\n\n");
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);

35
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

printf("%20s %30ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}

void findData(){
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
clrscr();
fp=fopen("data.txt","r");
printf("*****Display Specific Records*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}
}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);
getch();
}

void main(){
char choice;
while(1){
clrscr();
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice){
case'1' : //call append record
appendData();
break;

36
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

case'2' : //call find record


findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' :
case 27 : exit(1);
}
}
}

Output:
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) Exit
Enter Name:JACK
Enter Telephone Number:9176628799

******DISPLAY ALL RECORDS********


JACK 9176628799
RAM 78289993

Result:

37
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex.No: 17 LOW BALANCE ENQUIRY USING SEQUENTIAL ACCESS FILE Date:

Aim
To calculate low balance enquiry using sequential access file

Algorithm
1. Start
2. Open the file in read mode
3. Read the contents of the file using read mode
4. Check the balance amount in the account
5. If the balance amount is less, make a count of it
6. Report the count
7. Stop

Program
#include <stdio.h>
struct clientData {
unsigned int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
double balance; // account balance
}; // end structure clientData

int main( void ) {


FILE *cfPtr; // credit.dat file pointer
// create clientData with default information
struct clientData client = { 0, "", "", 0.0 };
// fopen opens the file; exits if file cannot be opened
if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) {
puts( "File could not be opened." );
} // end if
else {
// require user to specify account number
printf( "%s", "Enter account number"
" ( 1 to 100, 0 to end input )\n? " );
scanf( "%d", &client.acctNum );
// user enters information, which is copied into file
while ( client.acctNum != 0 ) {
// user enters last name, first name and balance
printf( "%s", "Enter lastname, firstname, balance\n? " );
// set record lastName, firstName and balance value
fscanf( stdin, "%14s%9s%lf", client.lastName,
client.firstName, &client.balance );
// seek position in file to user-specified record
fseek( cfPtr, ( client.acctNum - 1 ) *
sizeof( struct clientData ), SEEK_SET );
// write user-specified information in file
fwrite( &client, sizeof( struct clientData ), 1, cfPtr );

38
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

// enable user to input another account number


printf( "%s", "Enter account number\n? " );
scanf( "%d", &client.acctNum );
} // end while
fclose( cfPtr ); // fclose closes the file
} // end else
} // end main

Output:
Enter account number ( 1 to 100, 0 to end input )
? 37
Enter lastname, firstname, balance
? Barker Doug 0.00
Enter account number
? 29
Enter lastname, firstname, balance
? Brown Nancy -24.54
Enter account number
? 96
Enter account number
?0

Result:

39
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex. No: 18 ONLINE TICKET RESERVATION SYSTEM Date:

1. PROBLEM STATEMENT:
This project is about online ticket reservation and consists of two modules. The reservation and
the cancellation module. The reservation module allows the user to reserve tickets for a particular train
on a particular date. If there is a ticket available, the users can know the vacancy details through the
enquiry module. The cancellation module allows user to cancel the tickets for a particular date through
reservation officer (system). This module performs status reveal before tickets are being reserved and
after they get booked. All these modules together prove to be a flexible online reservation system and it
provides complete flexibility to end users and it assumes the desired performance.
2. OVERALL DESCRIPTION:
2.1 MODULES:
 Login
 Display train list
 Search for train
 Reservation
 Cancellation
 Train Status

2.2 MODULE DELIVERABLES:


1. LOGIN
Basic Flow
This use case starts when the passenger wishes to Login to the Online Ticket Reservation system
1. The System requests that the passenger enter his/her name and password
2. The passenger enters his/her name and password
3. The System validates the entered name and password and logs the passenger into the System
Alternative Flows: Invalid Name/Password
If, in the Basic flow, the passenger enters an invalid name and/or password, the system displays an error
message. The passenger chooses to either return to the beginning of the Basic flow or cancel the login, at
which point the use case ends.
Pre-Conditions: None
Post-Conditions: If the use case was successful, the passenger is now logged into the system. If not, the
system State is unchanged.

2. Display Train List


Basic Flow: This use case gives passenger information about each train namely train no, train name,
Stations passes, Arrival Time, Departure Time etc.
Alternative Flows: None
Pre-Conditions: None
Post-Conditions: If the use case was successful, the passenger information about each train namely train
no, train name, Stations passes, Arrival Time, Departure Time etc.

3. Search for Train


Basic flow
The passenger can obtain train information either by entering train no or Source and Destination Station
1. If the passenger train no gives the information about train
2. If the passenger enter Source and Destination Station from list gives information about list of trains
passing through station. From the list link will be provided to each train, which contains the information

40
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Alternate flow: If the passenger enters an invalid train no then it gives error message invalid train no and
asks the passenger to enter a valid train no.
Pre-Conditions: None
Post-Conditions: If the use case was successful, the passenger can able to view the list of trains.

4.Reservation
Basic flow
1. The user reserves the ticket by giving following
a) Passenger name, Sex, Age, Address
b) Credit Card No, Bank Name
c) Class through passenger is going to travel i.e First class or Second class or AC
d) Train no and Train name, Date of Journey and number of tickets to be booked.
2. If the ticket is available in a train then the ticket will be issued with PNR No.else the ticket will be
issued with a waiting list number.
Alternative flow: If the passenger gives an invalid credit card no or specified a bank where does have
any account. Error message will be displayed.
Pre-Conditions: The passenger has to decide about the train he is going to travel.
Post-Conditions: If the use case was successful, the passenger will get the ticket.

5. Cancellation
Basic flow
This use case used by passenger to cancel the ticket, which he/she booked earlier by Entering PNR No.
The cancellation has been done reallocating the tickets allotted to the Passenger.
Alternate flow: If the Passenger had entered invalid PNR No then has been asked to enter valid PNR No.
Pre-Conditions: The Passenger had reserved tickets in a train.
Post-Conditions: If the use case was successful, the passenger can cancel the ticket.

6. Ticket Status
Basic flow
1. The passenger should give PNR No to know the status of ticket, which he/she booked earlier.
2. If the PNR No is valid, the status of the ticket will be displayed.
Alternate flow: If passenger had entered an invalid no or PNR NO, which does not exists then error
Message will be displayed.
Pre-Conditions: The Passenger had reserved tickets in a train.
Post-Conditions: If the use case was successful, the passenger can view status of the ticket.

3. INFRASTRUCTURES

3.1HARDWARE REQUIREMENTS:
Processor : i5 speed 2.5GHZ
RAM : 8 GB
Hard disk : 500 GB
Operating System : CentOS.

3.2SOFTWARE REQUIREMENTS
 C CODING
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

41
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

#include<string.h>
#define MAX_sno 30

struct product{
int sno;
char name[10];
int batchno;
int mfd;
int exp;
};
struct product * createproduct(struct product *ptr,char name[20],int mfd,intexp,int price){

static int i=1;


ptr->batchno = i;
strcpy(ptr->name,name);
ptr->mfd = mfd;
ptr->exp = exp;
ptr->price = price;
i++;
return ptr;
}
int file_read(struct train **trains){
int count=0;
FILE *fpr;
fpr = fopen("train_details.txt","r");

while(fread(trains[count],sizeof(struct train),1,fpr)){
count++;
}

fclose(fpr);
return count;
}
void file_write(struct train **trains, int count){

int i;
FILE *fpw;
remove("train_details.txt");
fpw = fopen("train_details.txt","w");
for(i=0;i<count;i++){
fwrite(trains[i],sizeof(struct train),1,fpw);
}
fclose(fpw);
}

int main()
{
int ch,id,count=0,i,new_count=0;
char type;

42
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

char sp[20],ep[20];
struct train * trains[100];

count = file_read(trains);

while(1){
printf("\n------------------------------------------------------------------------");
printf("\n---------------------------Train Reservation------------------------------");
printf("\n------------------------------------------------------------------------");
printf("\n");
printf("\n1. Add Train\n2. Display Trains\n3. Book Ticket\n4. Cancel Ticket\n5.
Exit\n\nChoose your option: ");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\n\n-----------Add Train-------------\n");
printf("\nEnter the train id: ");
scanf("%d",&id);
fflush(stdin);
printf("\nEnter the type: ");
scanf("%c",&type);
printf("\nEnter the starting point: ");
scanf("%s",sp);
printf("\nEnter the destination point: ");
scanf("%s",ep);
trains[count] = createtrain(id,type,sp,ep);
count++;new_count++;
printf("\nTrain added succesfully.");
getch();
system("cls");
break;
case 2:
printf("\n\n---------Present Trains----------\n");
if(count==0)
printf("Currently no trains are present.");
else{
for(i=0;i<count;i++)
{
printf("\nTrain Id: %d",trains[i]->train_id);
printf("\nType: %c",trains[i]->type);
printf("\nSeats Filled: %d",trains[i]->seats);
printf("\nStarting Point: %s",trains[i]->sp);
printf("\nDestination Point: %s",trains[i]->ep);
printf("\n");
}
}
getch();
system("cls");
break;

43
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

case 3:
printf("\n\n---------Book a Ticket----------\n");
printf("\nEnter the train id: ");
scanf("%d",&id);
i = 0;
while(trains[i]->train_id!=id&&i<count)
i++;
if(i<count){
if(trains[i]->seats<MAX_SEATS){
trains[i]->seats+=1;
printf("\nTicket booked successfully.\n");
printf("\nYour ticket: \n");
printf("\n\n*****************");
printf("\n* Adult - 1 *");
printf("\n* Train Id - %d *",id);
printf("\n*****************\n");
}
else
printf("Sorry the train is full.");
}
else
printf("\nInvalid train id.\n");

getch();
system("cls");
break;
case 4:
printf("\n\n---------Cancel a Ticket----------\n");
printf("\nEnter the train id: ");
scanf("%d",&id);
i = 0;
while(trains[i]->train_id!=id&&i<count)
i++;
if(i<count){
if(trains[i]->seats>0){
trains[i]->seats-=1;
printf("\nOne ticket cancelled successfully.\n");
}
else
printf("Sorry the train is empty.");
}
else
printf("\nInvalid train id.\n");

getch();
system("cls");
break;
case 5:
file_write(trains,count);

44
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

exit(1);
}
}
}
Output

Result:

45
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Ex. No:19 IMPLEMENTATION OF SINGLY LINKED LISTS Date:

Aim
To write a C program to implement List ADT using Linked List.

Algorithm
Step 1:- Define a list as a node of a structure with one DATA and one LINK pointing to the next
element in the structure.
Step 2:- Declare the function prototypes create( ),insert( ),delete( ) and display( ) to perform the list
functions.
Step 3:- Declare necessary pointer variables as struct node data type.
Step 4:- Get a choice from the user. If the choice is create, Get first data from the user by calling the
function create( ), and display contents of the list.
Step 5:- If the choice is insert, Get data and its position by calling the function insert( ), and assign the
LINK field of the given data node according to the position. Display the contents of the list.
Step 6:- If the choice is delete, get the position of the data which is going to be removed from the list
and assign LINK field of the previous node to the address of the next node.
Step 7:- Repeat the steps 4, 5 & 6 until the choice is exit.
Step 8:- Terminate the execution.

Program
#include<stdio.h>
#include<stdlib.h>
void create();
void insert();
void del();
void display();
void find();
struct node
{
int data;
struct node *link;
};
struct node *first=NULL,*last=NULL,*next,*prev,*cur,*cur2;
void create()
{
cur=(struct node *)malloc(sizeof(struct node));
printf("enter the data:");
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;
}
void insert()
{
int pos,c=1;
cur=(struct node*)malloc(sizeof(struct node));
printf("enter the data:");

46
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

scanf("%d",&cur->data);
printf("Enter the position:");
scanf("%d",&pos);
if(pos==1&&first!=NULL)
{
cur->link=first;
first=cur;
}
else
{
next=first;
while( c<pos)
{
prev=next;
next=prev->link;
c++; }
if(prev==NULL)
{
printf("invalid position");
}
else
{
cur->link=prev->link;
prev->link=cur;
}}}
void del()
{
int pos,c=1;
printf("Enter the position to be deleted");
scanf("%d",&pos);
if(first==NULL)
{
printf("list is empty");
}
else
if(pos==1 && first->link==NULL)
{
printf("Deleted element is %d",first->data);
free(first);
first=NULL;}
else
if(pos==1 && first->link!=NULL)
{
cur=first;
first=first->link;
cur->link=NULL;
printf("Deleted element is %d",cur->data);
free(cur);}
else

47
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

{
next=first;
while(c<pos)
{
cur=next;
next=next->link;
c++;}
cur->link=next->link;
next->link=NULL;
if(next==NULL)
{printf("invalid position");}
else
{
printf("Deleted element is %d",next->data);
free(next);}}}
void display()
{

cur=first;
printf("Forward Link---");
printf("The elements in the list are:\n");
printf("\t\tHead");
while(cur!=NULL)
{
printf("---->%d",cur->data);
cur=cur->link;
}
printf("---->NULL\n");
printf("Backward Link is not possible in Singly linked List");
}
/*void find()
{
int search;
cur2=first;
printf("Enter the elements to find----->");
scanf("%d",&search);
printf("running1");
while(cur2!=NULL)
{
printf("running2");
if(cur2->data=search)
{
printf("Element Found");
cur2=cur2->link;
printf("Next element of %d",cur2->data);
cur2=NULL;
}
cur2=cur2->link;
}

48
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

}*/

void main()
{
int ch;
printf("singly linked list:");
do
{
printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Exit \n");
printf("\n\nEnter your option");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
insert();
display();
break;
case 3:
del();
display();
break;
case 4:
exit(0);
}
}
while(ch<=4);
}

Output
singly linked list:
1.Create
2.Insert
3.Delete
4.Exit
Enter your option1
enter the data:101
Forward Link---The elements in the list are:
Head---->101---->NULL
Backward Link is not possible in Singly linked List
1.Create
2.Insert
3.Delete
4.Exit
Enter your option2
enter the data:105

49
CS3271 –C Programming Lab Department of CSE & IT 2021-2022

Enter the position:2


Forward Link---The elements in the list are:
Head---->101---->105---->NULL
Backward Link is not possible in Singly linked List
1.Create
2.Insert
3.Delete
4.Exit
Enter your option3
Enter the position to be deleted2
Deleted element is 105
Forward Link---The elements in the list are:
Head---->101---->NULL
Backward Link is not possible in Singly linked List
Enter your option4

Result:

50

You might also like