C Lab Manual PDF
C Lab Manual PDF
Aim:
To write a C program using I/O statements, operators and expressions.
Algorithm:
1. Read a character, a string, a float value, an integer number, a double value from the user
using scanf() statement and store it in variables ch, str, flt, num, dbl.
2. Display all the variables using printf()statement.
3. Assign the operations like addition, subtraction, multiplication, division and modulus for the
values of a and b.
4. Display the result for various operations
Program:
#include<stdio.h>
int main ()
{
char ch,str[20];
float flt;
int num, a = 5, b = 3, c = a + b;
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\n");
scanf("%d",&num);
printf("Enter a double value\n");
scanf("%lf",&dbl);
printf("\nDisplaying:\n");
1
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",num);
printf("Double value is %lf\n",dbl);
printf("\nExpressions:\n");
printf("Prefix value is %d\n",++c);
printf("Postfix value is %d\n",c++);
printf("Infix value is %d\n",a+b);
printf("\nOperations:\n");
printf("Addition is %d\n",a+b);
printf("Subtraction is %d\n",a-b);
printf("Muliplication is %d\n",a*b);
printf("Division is %d\n",a/b);
printf("Modulus is %d\n",a%b) return 0;
2
Output:
Enter a
character
a
Enter a
string“welc
ome”
Enter a float
value10.53
Enter an integer
number350
Enter a double
value20.23451
Displaying:
Character
isa
String
is“welcome
”Float value
is10.53
Integer value
is350
Double value
is20.23451
Expressions:
Prefix value
is9
Postfix value
is9
Infix value
3
is8
Operations:
Addition is 8
Subtraction is 2
Multiplication is 15
Division is 1
Modulus is 2
Result:
Thus a C program using I/O statements, operators and expressions is executed successfully.
4
VIVA QUESTION
Arithmetic operator
Relational operators
Logical Operators
Assignment operators
An operator performs an operation like addition, subtraction and so on and produce a value.
Variables and constants upon which operations are performed are called operands.
Increment operators are used to increase the value of the variable by one anddecrement operators
are used to decrease the value of the variable by one in C programs.(Like ++, --)
5
Ex. No:2 DECISION-MAKING CONSTRUCTS: IF-ELSE,GOTO,
SWITCH-CASE, BREAK-CONTINUE
Aim:
To write a C program using decision-making constructs: if-else, goto, switch-case,
break-continue
Algorithm:
1. Start the program.
2. Declare the variables regno , t_mark , n , i, name.
3. Create a function name as student_details
4. Read the student details and check the condition 200<=t_mark, using if...else .if it is true
goto step 5 else goto step 6.
5. Display the mark range using switch case and break.
6. Display the result at theend of if-else statement.
7. Use goto statement in function call and call the function name as students_details.
8. Display the i value using loop in continue statement.
9. Display the result in various decision making statements.
10. End the program
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int regno,t_mark,n,i=1;
char name[20];
printf("Student Grade Validation\n");
students_details:
{
printf("\nEnter Name of the Student:");
scanf("%s",&name);
printf("\n Enter Student Register Number:");
scanf("%d",®no);
printf("\nEnter %s's Total Mark obtained:",name);
6
scanf("%d",&t_mark);
if(200<=t_mark)
{
printf("\n 1.450 to 500 \t 2.400 to 450 \t 3.350 to 400 \t 4.300 to 350 \t 5.200 to
300");
printf("\n Choose your mark range:");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nYour rank is FIRST class and you are passing with A Grade");
break;
case 2:
printf("\nYour rank is FIRST class and you are passing with B Grade");
break;
case 3:
printf("\nYour rank is FIRST class and you are passing with C Grade");
break;
case 4:
printf("\nYour rank is SECOND class and you are passing with D Grade");
break;
case 5:
printf("\nYour rank is SECOND class and you are passing");
break;
}
printf("\nCONGRATULATIONS!!!");
if(499==t_mark)
{
printf("\n Best wishes!!!\n You are a state first to your state!!!");
}
else
{
printf("\n Best wishes!!!\n");
7
}
}
else
{
printf("\n Sorry you are fail, Better luck next time!!!\n");
}
}
i++;
if(i==1)
{
goto students_details;
}
printf("\nContinue statement\n");
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf("%d\n",i);
}
printf("End program");
}
Output:
8
You are a state first to your state!!!
Continue statement
1
2
3
4
6
7
8
9
10
End program
6
7
8
9
10
End program
Result:
Thus a C program using decision-making constructs: if-else, goto, switch-case, break-
continue is executed successfully.
10
VIVA QUESTION
if(condition)
{
// Statements to execute if
// condition is true
}
11
Ex. No:3 Loops: for, while, do-while
Aim:
To write a C program using loops: for, while, do-while
Algorithm:
1. Start the program.
2. Declare the variables and read the values.
3. Perform check candidates age by using for, while and do-while.
4. Display the result and greetings.
5. End the program.
Program:
#include<stdio.h>
int main()
{
int i,n,s;
char name[20];
printf("\n\tVOTER'S AGE VALIDATION\n");
printf("\nEnter no of Canditates:");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("\nEnter Candidate Name:");
scanf("%s",&name);
printf("\nEnter Candidate Age:");
scanf("%d",&n);
do
{
if(n>=18)
printf("\nYou are ELIGIBLE for voting\n\n");
break;
12
}while(n>=18);
while(n<18)
{
printf("\nYou are NOT ELIGIBLE for voting\n\n");
break;
}
}
printf("\nBETTER LUCK NEXT TIME!!!\n");
return 0;
}
Output:
VOTER'S AGE VALIDATION
Enter no of Candidates:2
Enter Candidate Name: Vinitha
Enter your Age: 23
You are ELIGIBLEfor voting
Enter Candidate Name: Sharumitha
Enter Candidate Age:14
You are NOT ELIGIBLE for voting
BETTER LUCK NEXT TIME!!!
Result:
Thus a C program using Loops: for, while, do-while is executed successfully.
13
VIVA QUESTION
Loops allow the user to execute the same set of statements repeatedly without writing the
same code multiple times.
It saves time and effort and increases the efficiency.
It reduces the chance of getting errors during compilation.
} while (condition);
Ans: break statement leads to an immediate exit of the innermost switch or enclosing loop. On the
other hand, the continue statement begins the next iteration of the while, enclosing for, or do loop.
14
Ex. No:4a Arrays: 1D and 2D
Aim:
To write a C program using arrays: 1D and 2D
Algorithm:
1. Start the program.
2. Declare the variables and read the values.
3. Read the elements from the matrices.
4. Write elements into matrices using 1D and 2D of Array.
5. Display the result.
6. End the program.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5],i;
printf("Enter 5 elements into an array:\n");
for(i=0;i<=4;i++)
{
scanf("%d",&a[i]);
}
printf("The 5 elements are:\n");
for(i=0;i<=4;i++)
printf("%d\n",a[i]);
{
int a[2][2],i,j;
printf("Enter 4 elements into array:");
for(i=0;i<=1;i++)
15
{
for(j=0;j<=1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The 4 elements are:\n\t");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n\t");
}
}
getch();
}
Output:
35
23
16
45
67
11
35
23
45
67
11
6 3
2 1
Result:
Thus a C program using arrays: 1D and 2D is executed successfully.
17
VIVA QUESTION
1.What is ARRAY?
Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache friendliness.
18
Ex. No:4b Arrays: Multi-dimensional arrays, traversal
Aim:
To write a C program using arrays: Multi-dimensional arrays, traversal
Algorithm:
1. Start the program.
2. Declare the variables and read the values of first and second matrices.
3. Read the elements from the matrices.
4. Add the two matrices of rows and columns present in the array using Multi dimensional.
5. Declare another variable and values using Traversal.
6. Display the result.
7. End the program.
Program:
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],i,j,m,n,p,q;
printf("Enter the rows and columns of first Matrix\n");
scanf("%d%d",&m,&n);
printf("Enter the rows and columns of second Matrix\n");
scanf("%d%d",&p,&q);
if(m==p&&n==q)
{
printf("Enter the first Matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the second Matrix\n");
for(i=0;i<p;i++)
{
19
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\n Sum of the Matrices are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%8d",a[i][j]+b[i][j]);
}
printf("\n");
}
printf("\n");
}
int i,size;
int arr[]={1,-9,17,4,-3};
size=sizeof(arr)/sizeof(arr[0]);
printf("The array elements are:");
for(i=0;i<size;i++)
{
printf("\narr[%d]=%d",i,arr[i]);
}
}
else
20
printf("\n Operations are not possible....");
return 0;
}
Output:
Enter the rows and columns of first Matrix
2
2
Enter the rows and columns of second Matrix
2
2
Enter the first Matrix
1
2
3
4
Enter the second Matrix
5
6
7
8
Sum of the Matrices are:
6 8
10 12
Differences of the Matrices are:
-4 -4
-4 -4
The array elements are:
arr[0]=1
arr[1]=-9
arr[2]=17
arr[3]=4
arr[4]=-3
Output:
Enter the rows and columns of first Matrix
21
2
3
Enter the rows and columns of second Matrix
2
2
Operations are not possible....
Result:
Thus a C program using arrays: Multi-dimensional arrays, traversal is executed
successfully.
22
VIVA QUESTION
5. Declaration of 3D Array in C.
We can declare a 3D array with x 2D arrays each having m rows and n columns using the
syntax shown below:
type arr_name[x][m][n];
type: Type of data to be stored in each element.
arr_name: name of the array
x: Number of 2D arrays. (also called depth of the array)
m: Number of rows in each 2D array.
n: Number of columns in each 2D array.
23
Ex. No:5 Strings: operations
Aim:
To write a C program using Strings: operations
Algorithm:
1. Start the program.
2. Declare the variables.
3. Read the two strings and Perform string operations.
4. Display the result.
5. End the program.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char s1[25],s2[25],s3[25];
int l;
printf("\n\t\tString operations in C language are\n");
printf("\nEnter the first string:");
scanf("%s",&s1);
printf("\nEnter the second string:");
scanf("%s",&s2);
printf("\nString operations strat");
l=strlen(s1);
printf("\nLength of the first string is:%d",l);
strcat(s1,s2);
printf("\nConcatenation of the string is:%s",s1);
printf("\nString comparison:");
if(strcmp(s1,s2)==0)
{
24
printf("string 1 and string 2 are same.");
}
else
{
printf("String 1 and string 2 are different.");
}
strcpy(s3,s2);
printf("\nCopied string :String 3 is %s",s3);
return 0;
}
Output:
String operations in C language are
Enter the first string:Hello
Enter the second string:Sharumitha
String operations start
Length of the first string is:5
Concatenation of the string is:HelloSharumitha
String comparison :String 1 and string 2 are different
Copied string: string 3 is Sharumitha
Result:
Thus a C program using Strings: operations are executed successfully.
25
VIVA QUESTION
C also has many useful string functions, which can be used to perform certain operations
on strings.To use them, you must include the <string.h> header file in your program:
#include <string.h>
26
5) strrev(string) returns reverse string.
27
Ex. No:6a Functions: call, return, passing parameters by
(value, reference)
Aim:
To write a C program using Functions: call, return, passing parameters by (value,
reference)
Algorithm:
1. Start the program.
2. Declare the variables.
3. Define the user defined function as change by value and change by reference.
4. Display the result.
5. End the program.
Program:
#include<stdio.h>
void chan_by_val(int x)
{
printf("Before adding value inside function num=%d\n",x);
x+=100;
printf("After adding value inside function num=%d\n",x);
}
void chan_by_ref(int *x)
{
printf("Before adding value inside function num=%d\n",*x);
*x+=100;
printf("After adding value inside function num=%d\n",*x);
}
int main()
{
int x=100;
printf("\n\t\tPassing by Value");
printf("\nBefore function call x=%d\n",x);
chan_by_val(x);
printf("After function call x=%d\n",x);
printf("\n\t\tPassing by Reference");
28
printf("\nBefore function call x=%d\n",x);
chan_by_ref(&x);
printf("After function call x=%d\n",x);
return 0;
}
Output:
Passing by Value
Before function call x=100
Before adding value inside function num=100
After adding value inside function num =200
After function call x=100
Passing by Reference
Before function call x=100
Before adding value inside function num=100
After adding value inside function num =200
After function call x=200
Result:
Thus a C program using Functions: call, return, passing parameters by (value,
reference)are executed successfully.
29
VIVA QUESTION
1. What is a function?
Function is a set of instructions
Self contained block
Performs a specific task
Used to avoid redundancy of code
Algorithm:
1. Start the program.
2. Define (or) declare the user defined function and goto step3.
3. Display the function result and goto step6.
4. Declare the variables.
5. Call the user defined function and goto step2
6. Display the result.
7. End the program.
Program:
#include<stdio.h>
void display(int age1,int age2)
{
printf("%d\n",age1);
printf("%d\n",age2);
}
int main()
{
int age_array[]={2,3,7,5,6};
display(age_array[1],age_array[2]);
return 0;
}
Output:
Result:
Thus a C program using Passing arrays to function are executed successfully.
31
VIVA QUESTION
1. Define Array.
Ans:Array is a collection of similar type of values All values are stored in continuous memory
locations All values share a common name Linear data structure. The elements are organized in
a sequential order.
32
Ex. No:7 Recursion
Aim:
To write a C program using Recursion.
Algorithm:
1. Start the program.
2. Read the values.
3. Declare the variables,sum=0.
4. sum = sum+ x,n-=1.
5. Display the result.
6. End the program.
Program:
#include<stdio.h>
int sumOfRange(int);
int main()
{
int n1;
int sum;
printf("\n\nRecursion:Calculate the sum of numbers from 1 to n:\n");
printf("Input the last number of the range starting from 1:");
scanf("%d", &n1);
sum=sumOfRange(n1);
printf("\nThe sum of numbers from 1 to %d:%d\n\n",n1,sum);
return 0;
}
int sumOfRange(int n1)
{
int res;
if(n1==1)
{
return 1;
}
33
else
{
res=n1+sumOfRange(n1-1);
}
return res;
}
Output:
Result:
Thus a C program using Recursion are executed successfully.
34
VIVA QUESTION
1.What is meant by Recursive function?
Ans: If a function calls itself again and again, then that function is called Recursive function.
4. Applications of Recursion in C.
Recursion is widely used to solve different kinds of problems from simple ones like
printing linked lists to being extensively used in AI. Some of the common uses of recursion
are:
Tree-Graph Algorithms
Mathematical Problems
Divide and Conquer
Dynamic Programming
In Postfix to Infix Conversion
Searching and Sorting Algorithms
35
5. What is the difference between iteration and recursion in C?
Answer:
The following table lists the differences between recursion and iteration.
A set of instructions
Definition Function calls itself.
repeatedly executed.
36
Ex. No:8 Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointer, Array of Pointers
Aim:
To write a C program using Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointers, Array of Pointers.
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int addOne(int *ptr)
{
(*ptr)++;
return *ptr;
}
int main()
{
char p[20]="POINTER";
int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };
37
int i = 0;
char *p1;
int n=45;
int *ptr,**pptr,x,*s;
int var[]={1000,2000,3000};
int *parr[3]={var};
p1=strdup(p);
printf("\nPointer to string:");
printf("%s\n",p1);
ptr=&n;
pptr= &ptr;
a = &b;
printf("\nPointer to array:\n");
for (i = 0; i < 5; i++)
{
printf("%d\n", *(*a + i));
}
printf("\nPointer to pointer:\n");
printf("Value of var=%d\n",n);
printf("Value available at *ptr=%d\n",*ptr);
printf("Value available at **pptr=%d\n",**pptr);
for(x=0;x<1;x++)
{
printf("\nArray of pointer:");
printf("\nValue of Array[%d]=%d",x,*parr[x]);
}
i=10;
s=&i;
addOne(s);
printf("\n\nPointer to function:");
printf("\n%d",*s);
return 0;
}
38
Output:
Pointer to string:POINTER
Pointer to array:
1
2
3
4
5
Pointer to pointer:
Value of var=45
Value available at *ptr=45
Value available at **pptr=45
Array of pointer:
Value of Array[0]=1000
Pointer to function:
11
Result:
Thus a C program using Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointers, Array of Pointers are executed successfully.
39
VIVA QUESTION
1. Write the syntax for pointers to structure.
Ans:
Struct S
{
char datatype1;
int datatype2;
float datatype3;
}; Struct S *sptr; //sptr is a pointer to structure S
40
Ex.No 9a PROGRAM TO STORE STUDENT INFORMATION IN
STRUCTURE AND DISPLAY IT
AIM:
To store student information in structure and display it
ALGORITHM:
Step 1: START
Step 2: Read student details like name, mark1,2,3
Step 3: Calculate total, and average
Step 4: Display the grade Step
5: STOP
PROGRAM:
#include<stdio.h> struct student
{
int roll_no, mark1, mark2, mark3, total; float average;
char name[10],grade;
};
void struct_funct_student(struct student stu);
int main()
{
struct student stud;
printf("\nRoll No.=");
scanf("%d",&stud.roll_no);
printf("Name=");
scanf("%s",stud.name);
printf("Mark1=");
scanf("%d",&stud.mark1);
printf("Mark2=");
scanf("%d",&stud.mark2);
printf("Mark3=");
canf("%d",&stud.mark3);
struct_funct_student(stud);
41
return 0;
}
void struct_funct_student( struct student stu)
{
stu.total = stu.mark1 + stu.mark2 + stu.mark3;
stu.average = stu.total / 3;
if(stu.average >= 90) stu.grade='S';
else if(stu.average >= 80) stu.grade='A';
else if(stu.average >= 70) stu.grade='B';
else if(stu.average >= 60) stu.grade='C';
else if(stu.average >= 50) stu.grade='D';
else stu.grade='F';
printf("\n ROLL NO. \t NAME \t TOTAL \t AVG \t GRADE \n");
printf("%d \t %s \t %d \t %f \t %c", stu.roll_no,stu.name,stu.total,stu.average,stu.grade);
}
OUTPUT:
Roll No.= 1
Name= a
Mark1= 95
Mark2= 94
Mark3= 96
RESULT:
Thus the C Program to store and display student details using structures has been executed and the
result was verified.
42
VIVA QUESTION
1.Compare arrays and structures.
Comparison of arrays and structures is as follows.
Arrays Structures
An array is a collection of data items of same A structure is a collection of data items of
data type. different data types.
Arrays can only be declared. Structures can be declared and defined.
There is no keyword for arrays. The keyword for structures is struct.
An array cannot have bit fields. A structure may contain bit fields.
Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
Consumes more space compared to union. Conservation of memory is possible
43
Ex.No 9b Program To Read The Student Data And Calculate The Total Marks
AIM:
To read the student data and calculate the total marks
ALGORITHM:
Step 1: Start the program
Step 2: Get the details of the 10 students in five subjects
Step 3: Calculate the total marks of each student
Step 4 : Calculate the student who got the highest total marks Step
5: Display the results
Step 6: Stop the Program
PROGRAM:
#include<stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
int sub4;
int sub5;
};
void main()
{
struct student s[10];
int i,total=0;
clrscr(); for(i=0;i<=9;i++)
{
printf("\nEnter Marks in Five Subjects = ");
scanf("%d%d%d",& s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);
total=s[i].sub1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;
printf("\nTotal marks of s[%d] Student= %d",i,total);
}
getch();
44
}
OUTPUT:
Enter Marks in Five Subjects 80 70 90 80 98
Total Marks of 1 student = 83.6
RESULT:
Thus the C Program to print the student details has been executed and the result was verified.
45
VIVA QUESTION
1.Define C Structure Declaration.
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to declare the
structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
};
3. Uses of Structure in C.
C structures are used for the following:
The structure can be used to define the custom data types that can be used to create some
complex data types such as dates, time, complex numbers, etc. which are not present in the
language.
It can also be used in data organization where a large amount of data can be stored in different
fields.
Structures are used to create data structures such as trees, linked lists, etc.
They can also be used for returning multiple values from a function.
4. Limitations of C Structures.
In C language, structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C structures
also have some limitations.
46
Higher Memory Consumption: It is due to structure padding.
No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by
any function, anywhere in the scope of the structure.
Functions inside Structure: C structures do not permit functions inside the structure so we
cannot provide the associated functions.
Static Members: C Structure cannot have static members inside its body.
Construction creation in Structure: Structures in C cannot have a constructor inside
Structures.
5. Structure Pointer in C.
We can define a pointer that points to the structure like any other variable. Such pointers are
generally called Structure Pointers. We can access the members of the structure pointed by the
structure pointer using the ( -> ) arrow operator.
47
Ex.No:10a Telephone Directory Using Random Access File
AIM :
To insert, update, delete and append telephone details of an individual or a company into a telephone
directory using random access file.
ALGORITHM :
Step 1: Create a random access file
Step 2: call the respective procedure to insert, update, delete or append based on user choice
Step 3: Access the random access file to make the necessary changes and save
PROGRAM
#include "stdio.h"
#include "string.h"
#include<stdlib.h>
#include<fcntl.h>
struct dir
{
char name[20];
char number[10];
};
void insert(FILE *);
void update(FILE *);
void del(FILE *);
void display(FILE *);
void search(FILE *);
int record = 0;
int main(void) {
int choice = 0;
FILE *fp = fopen( "telephone.dat", "rb+" );
if (fp == NULL ) perror ("Error opening file");
while (choice != 6)
{
printf("\n1 insert\t 2 update\n");
printf("3 delete\t 4 display\n");
48
printf("5 search\t 6 Exit\n Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(fp); break;
case 2: update(fp); break;
case 3: del(fp); break;
case 4: display(fp); break;
case 5: search(fp); break;
default: ;
}
}
fclose(fp);
return 0;
}
void insert(FILE *fp)
{
struct dir contact, blank;
fseek( fp, -sizeof(struct dir), SEEK_END );
fread(&blank, sizeof(struct dir), 1, fp);
printf("Enter individual/company name: ");
scanf("%s", contact.name);
printf("Enter telephone number: ");
scanf("%s", contact.number);
fwrite(&contact, sizeof(struct dir), 1, fp);
}
void update(FILE *fp)
{
char name[20], number[10];
int result;
struct dir contact, blank;
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
49
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
printf("Enter number:");
scanf("%s", number);
strcpy(contact.number, number);
fseek(fp, -sizeof(struct dir), SEEK_CUR);
fwrite(&contact, sizeof(struct dir), 1, fp);
printf("Updated successfully\n");
return;
}
}
printf("Record not found\n");
}
void del(FILE *fp)
{
char name[20], number[10];
int result, record=0;
struct dir contact, blank = {"", ""};
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
fseek(fp, record*sizeof(struct dir), SEEK_SET);
fwrite(&blank, sizeof(struct dir), 1, fp);
printf("%d Deleted successfully\n", record-1);
return;
}
record++;
}
printf("not found in %d records\n", record);
}
50
void display(FILE *fp)
{
struct dir contact;
int result;
rewind(fp);
printf("\n\n Telephone directory\n");
printf("%20s %10s\n", "Name", "Number");
printf("*******************************\n");
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strlen(contact.name) > 0)
printf("%20s %10s\n",contact.name, contact.number);
}
printf("*******************************\n");
}
void search(FILE *fp)
{
struct dir contact;
int result; char name[20];
rewind(fp);
printf("\nEnter name:");
scanf("%s", name);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(contact.name, name) == 0)
{
printf("\n%20s %10s\n",contact.name, contact.number);
return;
}
}
printf("Record not found\n");
}
51
OUTPUT:
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 4
Telephone directory
Name Number
*******************************
bb 11111
*******************************
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 5
Enter name: bb
bb 11111
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 1
Enter individual/company name: aa
Enter telephone number: 222222
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 2
Enter name: aa
Enter number: 333333
Updated successfully
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice:
Telephone directory
Name Number
52
*******************************
bb 11111
aa 333333
*******************************
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 3
Enter name: aa
1 Deleted successfully
1 insert 2 update
3 delete 4 display
5 search 6 Exit
RESULT:
Thus the C Program to print insert, update, delete and append telephone using random access file has
been executed and the result was verified.
53
VIVA QUESTION
1. Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
You can easily move your data from one computer to another without any changes.
AIM:
To count the number of account holders whose balance is less than the minimum
balance using sequential access file.
ALGORITHM :
Step 1 : Start the program
Step 2 : Read choice to insert records & count minimum balance account
1. If choice is 1, then
Open a dat file in write mode
2. If Choice is 2, then
Open the file in Read mode
Read the records one by one using fscanf(0 function until reach the end of file.
If account balance is less than min balance, then display the account details
PROGRAM:
#include <stdio.h> void insert();
void count();
int main(void)
{
int choice = 0; while (choice != 3)
{
printf("\n1 insert records\n");
55
printf("2 Count min balance holders\n");
printf("3 Exit\n");
printf("Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(); break; case 2: count(); break;
}
}
}
void insert()
{
unsigned int account,i; char name[30];
double balance; FILE* cfPtr;
if ((cfPtr = fopen("clients.dat", "w")) == NULL) { puts("File could not be opened");
}
else {
int records,i=0;
printf("Enter the No. of records "); scanf("%d", &records);
while (i<records)
{
printf("Enter the account, name, and balance."); scanf("%d%29s%lf", &account, name, &balance);
fprintf(cfPtr, "%d %s %.2f\n", account, name, balance); i++;
}
fclose(cfPtr);
}
}
void count()
{
unsigned int account; char name[30]; double balance;
float minBal = 5000.00; int count = 0;
FILE *cfPtr;
if ((cfPtr = fopen("clients.dat", "r")) == NULL) printf("File could not be opened");
else
{
56
printf("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf(cfPtr, "%d%29s%lf", &account,
name, &balance);
while (!feof(cfPtr))
{
if (balance < minBal)
{
printf("%-10d%-13s%7.2f\n", account, name, balance); count++;
}
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
}
fclose(cfPtr);
printf("The number of account holders whose balance is less than the minimum balance:
%d", count);
}
}
OUTPUT:
1 insert records
Enter choice:1
Enter the No. of records 2
Enter the account, name, and balance.1001 A 10000
Enter the account, name, and balance.1002 B 300
1 insert records
Enter choice:2
Account Name Balance
1002 B 300.00
The number of account holders whose balance is less than the minimum balance: 1
1 insert records
2 Count min balance holders
3 Exit
57
RESULT :
Thus the C Program to count the number of account holders whose balance is less than the minimum
balance using sequential access file
58
VIVA QUESTION
1.What are two main ways a file can be organized?
Ans: i. Sequential Access — The data are placed in the file in a sequence like beads on a string.
Data are processed in sequence, one after another. To reach a particular item of data, all the data
that proceeds it first must be read.
ii. Random Access — The data are placed into the file by going directly to the location in the file
assigned to each data item. Data are processed in any order. A particular item of data can be
reached by going directly to it, without looking at any other data.
2.What is file?
Ans: A file is a semi-permanent, named collection of data. A File is usually stored on magnetic
media, such as a hard disk or magnetic tape.
Semi-permanent means that data saved in files stays safe until it is deleted or modified. Named
means that a particular collection of data on a disk has a name, like mydata.dat and access to the
collection is done by using its name.
59
ST. JOSEPH’S COLLEGE OF ENGINEERING & Format No.
ACD-
TECHNOLOGY CF-CBL
Elupatti, Thanjavur – 613 403 Issue No. 01
CONTENT BEYOND EXPERIMENT Rev. No. 00
AIM:
To write a C program to perform linear search and binary search
ALGORITHM:
Linear Search
1.Read n numbers and search value.
2.If search value is equal to first element then print value is found.
3.Else search with the second element and so on.
Binary Search
1.Read n numbers and search value.
2.If search value is equal to middle element then print value is found.
3.If search value is less than middle element then search left half of list with the same
method.
4.Else search right half of list with the same method.
PROGRAM:
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
void main()
{
int a[100],i,n,item,s=0,ch,beg,end,mid; clrscr();
printf("Enter No. of Elements:");
scanf("%d",&n);
printf("\nEnter Elements:\n");
for(i=1;i<=n;i++)
60
{ scanf("%d",&a[i]); }
while(1)
{
printf("\n1.Linear Search\n2.Binary Search\n3.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("<-----LINEAR SEARCH----->\n");
printf("\nEnter Element you want to Search:");
scanf("%d",&item);
for(i=1;i<=n;i++)
{
if(a[i]==item)
{ printf("\nData is Found at Location : %d",i); s=1;
break; }
}
if(s==0)
{ printf("Data is Not Found"); }
break;
case 2:
printf("<-----BINARY SEARCH----->\n");
printf("\nEnter Item you want to Search:");
scanf("%d",&item);
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end && a[mid]!=item)
{
if(a[mid]<item)
beg=mid+1;
else end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
61
{ printf("\nData is Found at Location : %d",mid); }
else
{ printf("Data is Not Found"); }
break;
case3:
default: exit(0); }
}
getch();
}
OUTPUT:
1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 1
<-----LINEAR SEARCH----->
Enter Element you want to Search: 1
Data is Found at Location : 5
1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 2
<-----BINARY SEARCH----->
Enter Item you want to Search: 3
Data is Found at Location : 3
62
1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 3
RESULT:
Thus a C program to implement the linear search and binary search is written and executed
successfully.
63
64