Click here for C programming - I
4.2 Functions
A function is a self-contained sub program, which means to perform some specific, well defined task. A C program consists of one or more functions. Execution of every C program always begin with main(). Additional functions will be subordinate to main, and perhaps to one another. After each function has done its operation, control returns back to the main(). Then remaining statements of main() are executed. If a program contains multiple functions, their definitions may appear in any order, though they must be independent of one another.
Types of Functions
Functions are of two types: Library(built-in) function and user defined function.
4.2.1 Concept of library and user defined functions and advantages
1. Library (built-in) function:
C has the facility to provide some library function to the programmer for doing some operations. As an example C has a mathematical function which is used for finding out the square root of any number, string library functions are used for string operations, as example strlen() is used to find out the length of the string and strcmp() is used for comparison of two strings. These operations are programmed and stored as library functions, so that they can be called by any program.
Mathematical functions are called by using the preprocessor directive #include<math.h> and string library functions are called by #include<string.h>.
Example of Library Function
Program to find the sqaure root of any number
#include<stdio.h>
#include<math.h>
main()
{
int n,s;
printf("Enter any number : ");
scanf("%d",&n);
s=sqrt(n); // sqrt() is Library Function
printf("The square root of %d is %d",n,s);
}
2. User defined function:
Library functions provide the facility for doing some predefined operations. User can also create functions for doing any specific task of the program. Such functions are called user defined functions. In other words, user defined functions are functions which are created by the programmer according to the need.
A function will carry out its intended action whenever it is accessed from some other portion of the program. The same functions can be accessed from several different places within a program. Once the function has carried out its intended action, control will be returned to the point from which the function was accessed.
Example of User Defined Function
Program to find the sum of two numbers number using user defined function
#include<stdio.h>
int sum(int a, int b); // Function Prototype
main()
{
int a,b,s;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
s=sum(a,b); // Function Call
printf("Sum of %d and %d is %d",a,b,s);
}
int sum(int a,int b) // Function Definition
{
int p;
p=a+b;
return p;
}
Highlight is only done for understanding purpose. No need to do in your exercise copy.
Advantage of Function
- Function increase code reusability.
- The length of the source program can be reduced by using functions at appropriate places.
- The program development will be faster.
- The program debugging will be easier.
- Large number of programmer can be involved.
- The program can be developed in short period of time.
- The program can be developed in different places.
- The program can be tested and compiled independently by different member of a programming team.
Need for User Defined FunctionsEvery program must have a main function to indicate where the program to begin its execution. While it is possible to code any program utilizing only main function, it leads to a number of problems. The program may become too large and complex. So, debugging, testing and maintaining become difficult. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprogram called 'function' are much easier to understand, debug and test.
Difference between library and user defined function
Library Function | User Defined Function |
1. Library functions are predefined functions. |
1. User defined functions are functions which are created by the programmer according to the need. |
2. Library function requires header file to use it. |
2. User defined function requires function prototype to use it. |
3. Program development time is faster. |
3. Program development time is slower than library function. |
4. It is called at run time. |
4. It is called at compile time. |
5. The name of library function can't be changed. |
5. The name of user defined function can be changed any time. |
6. The program using library function will be usually short. |
6. The program using user defined function will be usually lengthy. |
7. Example: printf(), scanf(), strlen() etc |
7. Example: sum(), factorial(),area() etc |
Assignment-1
1. Difference between user defined and library function.
Components of Function
There are THREE components of Function.
- Function Prototype
- Function Definition
- Function Call
(1) Function Prototype or Declaration
Function prototype provides the following information to the computer.
- The type of the value returned
- The name of the function.
- The number and the type of the arguments that must be supplied in a function call
Syntax of Function Prototype:
return_value Function_name (arg1,arg2,...,argn);
Example
int sum(int, int);
In this example two arguments int types are passed inside function name 'sum' and it returns int value.
Prototype only needed if function definition comes after use in program. They are generally written at the beginning of a program, ahead of the main() function.
(2) Function Definition
A function definition has two prints principle components:
- Function header or function declaration
- Body of the function
The first line of function definition is known as function declarator and is followed by the function body. Function declarator contains the value returned by the function followed by the function name and optionally a set of arguments, separated by commas and enclosed in parenthesis. Each argument is preceded by its associated type declaration. An empty pair of parentheses must follow the function name if the function definition does not include any arguments.
Syntax of Function Definition:
return_value Function_name (arg1,arg2,...,argn)
Example
int sum(int a, int b)
{
int p;
p=a+b;
return p;
}
(3) Function Call
A function call is specified by the function name followed by the arguments enclosed in parenthesis and terminated by semicolon.
Syntax of Function Call:
variable=Function_name (arg1,arg2,...,argn);
Or Function_name(arg1,arg2,...,argn);
where passing arguments arg1,arg2,... are optional.
Example
(i) c=sum(a,b);
(ii) area(r);
Example to print square of a number using function
#include<stdio.h>
int square(int n); // Function Prototype
main()
{
int n,s;
printf("Enter any number : ");
scanf("%d",&n);
s=square(n); // Function Call
printf("Square of %d is %d",n,s);
}
int square(int n) // Function Definition
{
int p;
p=n*n;
return p;
}
Assignment-2
1. Define the terms function definition and function prototype
2. List the advantages of function.
return and void statements
return statement: One of the main features of the function is that it can return a value to the calling function. For this, a return keyword is used. So, return keyword return the program control from a function to the calling function.
Syntax of return statement:
return expression;
A function definition can obtain multiple return statements. However, only one gets executed.
Example
int great(int a, int b)
{
if(a>b)
return a;
else
return b;
}
Program 51 Write a program to print the greatest number between two numbers using function.
#include<stdio.h>
int great(int , int);
main()
{
int a,b,c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
c=great(a,b);
printf("Greatest number is %d",c);
}
int great(int a, int b)
{
if(a>b)
return a;
else
return b;
}
Program 52 Write a program to print the smallest number among three numbers using function.
#include<stdio.h>
int small(int a, int, int c);
main()
{
int a,b,c,d;
printf("Enter three numbers : ");
scanf("%d%d%d",&a,&b,&c);
d=small(a,b,c);
printf("Smallest number is %d",d);
}
int small(int a, int b, int c)
{
if(a<b && a<c)
return a;
else if (b<c)
return b;
else
return c;
}
void statement
If a function does not return a value then we say that the function's return type is void. So, no expression is present if a function return type is void. If a return keyword is used, then it is used to transfer the control at the end of the function.
Example
void evenodd(int n)
{
if(n%2==0)
printf("%d is even number",n);
else
printf("%d is odd number",n);
}
Program 53 Write a program to check whether the entered number is odd or even using function.
#include<stdio.h>
void evenodd( int );
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
evenodd(n);
}
void evenodd(int n)
{
if(n%2==0)
printf("%d is even number",n);
else
printf("%d is odd number",n);
}
Program 54 Write a program to check whether the entered number is positive, neagtive or zero using function.
#include<stdio.h>
void test( int n);
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
test(n);
}
void test(int n)
{
if(n>0)
printf("%d is positive number",n);
else if(n<0)
printf("%d is negative number",n);
else
printf("%d is zero",n);
}
Program 55 Write a program to print using function:
1 5 9 .... 10th terms.
#include<stdio.h>
void series( int n);
main()
{
int n=10;
series(n);
}
void series(int n)
{
int i,j=1;
for(i=1;i<=n;i++)
{
printf("%5d",j);
j=j+4;
}
}
Program 56 Write a program to calculate the cumulative sum of natural numbers upto n using function.
#include<stdio.h>
int sum( int n);
main()
{
int n,s;
printf("Enter any number : ");
scanf("%d",&n);
s=sum(n);
printf("Sum of natural number up to %d = %d",n,s);
}
int sum(int n)
{
int i,sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
return(sum);
}
Program 57 Write a program to print multiplication table of n number using function.
#include<stdio.h>
void mtable( int n);
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
mtable(n);
}
void mtable(int n)
{
int i;
for(i=1;i<=10;i++)
printf("%d*%d=%d\n",n,i,n*i);
}
Program 58 Write a program to calculate factorial of given number using function.
[The product of a given positive integer multiplied by all lesser positive integers: The quantity five factorial (5!) = 5 x 4 x 3 x 2 x 1 = 120.]
#include<stdio.h>
long int facto( int n);
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
printf("The factorial of given number is %ld",facto(n));
}
long int facto(int n)
{
long int f=1;
int i;
for(i=1;i<=n;i++)
{
f=f*i;
}
return(f);
}
Program 59 Write a program to print reverse of a number using function.
#include<stdio.h>
int rev( int n);
main()
{
int n;
printf("Enter multi-digit number : ");
scanf("%d",&n);
printf("The reverse of given number is %d",rev(n));
}
int rev(int n)
{
int s=0,r;
while(n!=0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
return(s);
}
Program 60 Write a program to display Fibonacci Series: 1 1 2 3 5 ... upto nth terms using function.
An integer in the infinite sequence 0,1, 1, 2, 3, 5, 8, 13, … of which the first two terms are 0 and 1 and each succeeding term is the sum of the two immediately preceding is called Fibonacci Series.
#include<stdio.h>
void fibo( int n);
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
fibo(n);
}
void fibo (int n)
{
int i,a=1,b=1,c;
for(i=1;i<=n;i++)
{
printf("%5d",a);
c=a+b;
a=b;
b=c;
}
}
Program 61 Write a program to check whether the given number is prime or composite using function.
[A number that is divisible by itself and 1 is called prime number. (e.g. 2,3,5,7,11 etc)]
#include<stdio.h>
int test( int n);
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
if(test(n)==1)
printf(" %d is prime number",n);
else
printf(" %d is composite number",n);
}
int test (int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return(1);
else
return (0);
}
Program 62 Write a program to display the prime series 2 3 5 7 11 ... nth terms using function.
#include<stdio.h>
int test( int n);
main()
{
int n,i;
printf("Enter any number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(test(i)==1)
printf(" %d ",i);
}
}
int test (int n)
{
int i,j,c;
for(i=1;i<=n;i++)
{
c=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
c++;
}
}
if(c==2)
return (1);
}
Program 63 Write a program to calculate power function p=xy using function.
#include<stdio.h>
int power( int x, int y);
main()
{
int x,y;
printf("\n The value of x : ");
scanf("%d",&x);
printf("\n The value of y : ");
scanf("%d",&y);
printf("\n The result is %d ",power(x,y));
}
int power(int x, int y)
{
int p=1,i;
for(i=1;i<=y;i++)
{
p=p*x;
}
return (p);
}
Assignment-3
1.Write a C program to find sum of first n even numbers using function.
2. Write a C program to count all those numbers which are divisible by 7 between 1 to 100?
Goto Top
4.2.2 Accessing a Function by passing values
Categories of User Defined Function
- Function returning value and passing arguments : Here, an argument is passed from the calling function to the called function and there will also be return statement in the called function.
#include<stdio.h>
int sum(int,int); // function prototype
main()
{
int a,b,c;
printf(" Enter two numbers: ");
scanf("%d%d",&a,&b);
c=sum(a,b); // function call
printf(" Sum of two numbers = %d ",c);
}
int sum(int a, int b) // function definition
{
int p;
p=a+b;
return(p);
}
- Function returning no value but passing arguments : Here, an argument is passed from the calling function to the called function but there is no need of return statement in the called function.
#include<stdio.h>
void sum(int,int); // function prototype
main()
{
int a,b;
printf(" Enter two numbers: ");
scanf("%d%d",&a,&b);
sum(a,b); // function call
}
void sum(int a, int b) // function definition
{
int p;
p=a+b;
printf("Sum of two numbers =%d",p);
}
- Function returning value and passing no arguments: Here, an argument is not passed from the calling function to the called function but there is return statement in the called function.
#include<stdio.h>
int sum(); // function prototype
main()
{
int c;
c=sum(); // function call
printf("Sum of two numbers =%d",c);
}
int sum() // function definition
{
int a,b,p;
printf(" Enter two numbers: ");
scanf("%d%d",&a,&b);
p=a+b;
return(p);
}
- Function returning no value and passing no arguments: Here, an argument is not passed from the calling function to the called function and there is no return statement in the called function.
#include<stdio.h>
void sum(); // function prototype
main()
{
sum(); // function call
}
void sum() // function definition
{
int a,b,p;
printf(" Enter two numbers: ");
scanf("%d%d",&a,&b);
p=a+b;
printf("Sum of two numbers = %d ",p); }
Function with Arrays
Like the values of simple variables, it is also possible to pass the values of an array to a function. To pass an array to a called function, it is sufficient to list the name of the array without any subscripts and the size of the array as arguments.
Program 64 Write a program to input 5 numbers and calculate their sum using array and function.
#include<stdio.h>
int sum(int a[]);
main()
{
int a[5],i,ans;
for(i=0;i<5;i++)
{
printf("Enter num[%d] : ",i+1);
scanf("%d",&a[i]);
}
ans=sum(a);
printf("Sum is %d",ans);
}
int sum(int a[])
{
int s=0,i;
for(i=0;i<5;i++)
{
s=s+a[i];
}
return (s);
}
Goto Top
4.2.3 Concept of Storage
The period of time during which memory is associated with a variable is characterized by storage class. So, storage class of a variable indicates the allocation of space to variable by the compiler. Generally C supports four storage classes automatic, external, static and register.
(i) Automatic storage class: The keyword auto is used to define automatic variable. Variables declared within function bodies are automatic by default. When a block is entered, the system allocates memory for the automatic variables. Within that block, these variables are defined and are considered "local" to the block. So the value of these variables is lost. If the block is re-entered, the system re-allocates memory but the previous values are unknown.
Example of Automatic Storage Class
#include<stdio.h>
void show();
main()
{
show();
show();
show();
}
void show()
{
auto int n=5;
printf("\n Number %d",n);
n=n+5;
}
Output is
Number 5
Number 5
Number 5
(ii) External storage class: The keyword extern is used to define external type variable. The external storage class is used to transmit information across the blocks and functions. When a variable is declared outside function storage is permanently assigned. Such a variable is considered to be global to all functions declared after it.
Example of External Storage Class
#include<stdio.h>
extern int a=1,b=2;
int show();
main()
{
int k;
k=show();
printf("\n %d ",k);
printf("\n a=%d \t b=%d",a,b);
}
int show()
{
int a,b;
a=b=4;
return(a+b);
}
Output is
8
a=1 b=2
(iii) Static storage class: The keyword static is used to define static type variable. A value is said to be static if it is allocated storage at the beginning of the segment and the storage remains allocated until the program execution terminates.
Example of Static Storage Class
#include<stdio.h>
void show();
main()
{
show();
show();
show();
}
void show()
{
static int n=5;
printf("\n Number %d",n);
n=n+5;
}
Output is
Number 5
Number 10
Number 15
(iv) Register storage class: The keyword register is used to define register type variable. The use of the register storage class is an attempt to improve execution speed. It is used only for frequently used variables only(that is limited either two or three).
Example of Register Storage Class
#include<stdio.h>
void show();
main()
{
show();
}
void show()
{
register int n=5,i;
for(i=1;i<=5;i++)
{
printf("\n Number %d ",n);
n=n+5;
}
}
Output is
Number 5
Number 10
Number 15
Number 20
Number 25
Goto Top
4.2.4 Concept of Recursion: factorial and Fibonacci problems
Recursion can be regarded as the ability of function defining an object in terms of a simpler case of itself. Recursion is a process by which a function calls itself repeatedly, until some specific condition has been satisfied. For the problem to solve recursively two conditions must be satisfied:
(a) The function should call itself.
(b) The problem statement must include a stopping point.
Program 65 Write a program to calculate sum of n natural numbers using recursion.
#include<stdio.h>
int sum(int);
main()
{
int n,ans;
printf( "Enter last number : ");
scanf("%d",&n);
ans=sum(n);
printf(" Sum is %d ",ans);
}
int sum(int n)
{
if(n<=0)
return 0;
else
return(n+sum(n-1));
}
Program 66 Write a program to calculate factorial using recursive function.
[The product of a given positive integer multiplied by all lesser positive integers: The quantity five factorial (5!) = 5 x 4 x 3 x 2 x 1 = 120.]
#include<stdio.h>
int fact(int);
main()
{
int n,ans;
printf( "Enter any number : ");
scanf("%d",&n);
ans=fact(n);
printf(" Factorial of %d is %d ",n,ans);
}
int fact(int n)
{
if(n<=1)
return (1);
else
return(n*fact(n-1));
}
Program 67 Write a program to display Fibonacci series up to nth term using recursive function.
[An integer in the infinite sequence 0,1, 1, 2, 3, 5, 8, 13, … of which the first two terms are 0 and 1 and each succeeding term is the sum of the two immediately preceding is called Fibonacci Series.]
#include<stdio.h>
int fibo(int n);
main()
{
int i,n;
printf( " Enter any number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf(" %d\t ",fibo(i));
}
}
int fibo(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return (fibo(n-1)+fibo(n-2));
}
Program 68 Write a program to find the length of a string using user defined function.
#include<stdio.h>
int strlen(char str[]);
main()
{
char str[100];
printf(" Enter any string : ");
scanf("%s",str);
printf(" The length of string is %d",strlen(str));
}
int strlen(char str[])
{
int i;
for(i=0;str[i]!='\0';i++);
return (i);
}
Worked Out Examples
Program 69 Write a program to find the greatest number among given set of 'n' numbers using function.
#include<stdio.h>
int max(int a[],int n);
main()
{
int a[100],n,i;
printf(" Enter vaule of n : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter a[%d] : ",i+1);
scanf("%d",&a[i]);
}
printf(" The greatest number is %d ",max(a,n));
}
int max(int a[],int n)
{
int i,m=a[0];
for(i=0;i<n;i++)
{
if(a[i]>m)
m=a[i];
}
return(m);
}
Program 70 Write a program to input the weight of 100 students and count the number of students having weight in between 50 to 60 kg using function.
#include<stdio.h>
int count(int w[]);
main()
{
int w[100],i;
for(i=0;i<100;i++)
{
printf(" Enter w[%d] : ",i+1);
scanf("%d",&w[i]);
}
printf(" The number of students having weights between 50 to 60 kg is %d ",count(w));
}
int count(int w[])
{
int i,c=0;
for(i=0;i<100;i++)
{
if(w[i]>=50 && w[i]<=60)
c++;
}
return(c);
}
Program 71 Write a program that inputs 'n' numbers and sort them in ascending order using function.
#include<stdio.h>
void sort(int num[],int n);
main()
{
int num[100],n,i;
printf(" Enter the array size not more than 100 : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter num[%d] : ", i+1);
scanf("%d",&num[i]);
}
sort(num,n);
}
void sort(int num[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
printf(" Numbers in ascending order \n ");
for(i=0;i<n;i++)
printf(" %d\t ",num[i]);
}
Program 72 Write a program that takes 'n' number of strings and sort them in alphabetical order using function.
#include<stdio.h>
#include<string.h>
void sort(char str[][20],int n);
main()
{
char str[50][20];
int i,n;
printf(" How many strings : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter str[%d] : ",i+1);
scanf("%s",str[i]);
}
sort(str,n);
}
void sort( char str[][20],int n)
{
int i,j;
char temp[20];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf(" Sorted strings are : \n");
for(i=0;i<n;i++)
printf(" %s\n ",str[i]);
}
Program 73 Write a program to enter elements for 2 x 2 matrix and display its transpose using function.
#include<stdio.h>
void transpose(int a[][2]);
main()
{
int a[2][2],i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("Enter a[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
transpose(a);
}
void transpose(int a[][2])
{
int i,j;
printf("\n Transpose of 2x2 matrix: \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(" %d\t ",a[j][i]);
}
printf("\n");
}
}
Program 74 Write a program to calculate and display sum of two matrices with respective size 3x3 using function.
#include<stdio.h>
void sum(int m1[][3],int m2[][3]);
main()
{
int m1[3][3],m2[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter m1[%d][%d] : ",i,j);
scanf("%d",&m1[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter m2[%d][%d] : ",i,j);
scanf("%d",&m2[i][j]);
}
}
sum(m1,m2);
}
void sum(int m1[][3],int m2[][3])
{
int m3[3][3],i,j;
printf("\n sum of two 3x3 matrices: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
printf(" %d\t ",m3[i][j]);
}
printf("\n");
}
}
Goto Top
Exercise - 4.2 (Function)
A. Short Answer Questions:
- Write syntax of function
- What is function prototype
- Define function declaration.
- What is return statement?
- Differentiate between void and return statement.
B. Long Answer Questions:
- What is function? Write advanatges of function.
- What are the types of function? Explain.
- Explain the components of function.
- What is recursion? Explain with one example.
- Differentiate between library and user defined function.
Goto Top
4.3 Structure and Union
4.3.1 Structure: Definition, Declaration, Initialization and Size of Structure
Definition of Structure:
The collection of disimilar data items treated as single unit. Each data item is called member of structure. The keyword struct is used to declare structure variable and type of strucutre variable is defined by the tag_name of the structure.
Some major features of structure
- It can be treated as a record that is a collection of interrelated data fields having different data types.
- It is possible to copy one structure variable to another by simply assignment operator (=).
- It allows nested structure that is one structure inside another structure.
- It is possible to pass structure variables as parameters to any function.
- It is possible to define a structure pointer also known as a linked list.
Declaration of structure
Syntax for structure declaration
In this example, member1, member2,....,memberN are the members of the structure and var1, var2, var3,...,varM are variables with data type tag_name.
struct tag_name
{
data_type member1;
data_type member2;
.............
data_type memberN;
};
struct tag_name var1,var2,var3,...,varM;
Example of structure variable
In this example, student is structure type and int roll_no, char fname[30] and char lname[30] are the members of the structure. S1,S2 and S3 are the strucutre variables with data type student.
struct student
{
int roll_no;
char fname[30];
char lname[30];
};
struct student S1,S2,S3;
Initialization of structure
Structure variable can be initialized quite similar to array. The folloiwng example shows the structure initialization process.
struct student
{
int roll_no;
char fname[30];
char lname[30];
} S1={1,"Ram","Lama"};
The alternate method to initialize structure variable as:
struct student S2={2,"Gaurab","Bohara"};
struct student S3={3,"Alex","Karn"};
Size of structure
The actual memory size of a variable in terms of bytes may vary from machine to machine. Therefore, the
sizeof operator helps us to determine memory size of a variable. In the following example, the memory size of the structure variable S is 64.
syntax
sizeof(struct variable);
Example
struct student
{
int roll_no; // 4 Bytes
char fname[30]; // 30*1=30 Bytes
char lname[30]; // 30*1=30 Bytes
} S;
Assignment-4
1. Define structure with its syntax and example.
4.3.2 Accessing member of structure
A member of structure can be accessed by using period (.) sign between structure variable and respective member.
Syntax:
variable.member
Example:
S1.roll_no,S2.fname,S3.lname etc.
Program 75 Write a program that takes roll_no, fname, lname and prints the records on screen.
#include<stdio.h>
struct student
{
int roll_no;
char fname[30];
char lname[30];
};
main()
{
struct student s;
printf("Enter roll , fname and lname : ");
scanf("%d%s%s",&s.roll_no,s.fname,s.lname);
printf("ROLL : %d\t Fname: %s\t Lname: %s",s.roll_no,s.fname,s.lname);
}
Assignment-5
1. Define structure data type.
4.3.3 Array of structure
It is possible to declare structure as an array; called array of structure. It is also known as the collection of structure variables having same set of members. Consider the following structure variable S with data type student and array size 5.
Example:
struct student
{
int roll_no;
char fname[30];
char lname[30];
};
struct student S[5];
Program 81 Write a program that takes roll_no, fname, lname of five students and prints the same records on screen.
#include<stdio.h>
struct student
{
int roll_no;
char fname[30];
char lname[30];
} s[5];
main()
{
int i;
for(i=0;i<5;i++)
{
printf("Enter roll , fname and lname : ");
scanf("%d%s%s",&s[i].roll_no,s[i].fname,s[i].lname);
}
printf("Output\n");
for(i=0;i<5;i++)
{
printf("%5d %10s %10s\n",s[i].roll_no,s[i].fname,s[i].lname);
}
}
Program 82 Write a program that takes roll_no, fname, lname of five students and prints the same records in ascending order on the basis of roll_no on screen.
#include<stdio.h>
struct student
{
int roll_no;
char fname[30];
char lname[30];
} s[5];
main()
{
struct student temp;
int i,j;
for(i=0;i<5;i++)
{
printf("Enter roll , fname and lname : "); scanf("%d%s%s",&s[i].roll_no,s[i].fname,s[i].lname);
}
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
{
if(s[i].roll_no>s[j].roll_no)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n Roll, Names in Ascending order\n");
for(i=0;i<5;i++)
{
printf("%5d %10s %10s\n",s[i].roll_no,s[i].fname,s[i].lname);
}
}
Assignment-6
1.Write a program that takes name and marks of 10 students. Sort data according to marks in descending order and display them.
Answer
#include<stdio.h>
struct student
{
int mark;
char name[30];
} s[5];
main()
{
struct student temp;
int i,j;
for(i=0;i<10;i++)
{
printf("Enter name and marks [%d] student : ",i+1);
scanf("%s%d",s[i].name,&s[i].mark);
}
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(s[i].mark<s[j].mark)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n Student list in descdending order\n");
for(i=0;i<10;i++)
{
printf("%10s %10d\n",s[i].name,s[i].mark);
}
}
Passing structure to function
A function can be called by passing structure variable as parameter. Structure variable can be passed in various ways: member can be passed individually or entire structure can be passed at once. The following program can take two structure variables d1 and d2 and calculate sum of two different distances.
Program 83 Write a program using function to calculate sum of two distances and distance is measured in terms of feet and inch
#include<stdio.h>
void sum(struct distance d1,struct distance d2);
struct distance
{
int feet;
int inch;
};
main()
{
struct distance d1,d2;
printf("Enter first distance in feet inch format : ");
scanf("%d%d",&d1.feet,&d1.inch);
printf("Enter second distance in feet inch format : ");
scanf("%d%d",&d2.feet,&d2.inch);
sum(d1,d2);
}
void sum(struct distance d1,struct distance d2)
{
struct distance d;
d.inch=(d1.inch+d2.inch)%12;
d.feet=d1.feet+d2.feet+(d1.inch+d2.inch)/12;
printf("\n Sum of two distances = %d Feet %d Inch ",d.feet,d.inch);
}
4.3.4 Union : Definition , Declaration
Union is similar to structure but it differs only in its storage location. The union keyword is used to define union. In strucutre , each member has its own memory block whereas all members of union can share the same memory location. Therefore, union can take less amount of memory than structure and it can access only one member at a time.
Syntax for the declaration of union
union tag_name
{
data_type member_1;
data_type member_2;
........
data_type member_n;
};
union tag_name var_1,var_2,var_3;
member_1,member_2,....,member_n are the member of the union and var_1,var_2,var_3 are variables with tag_name.
Example
union data
{
char x;
int y;
float z;
} var;
In this example, var is union variable with union_name data. It contains three members : char x, int y, float z. In this example, float z is the largest size member that requires 4 bytes memory and the same memory is shared over other two members.
4.3.5 Difference between structure and Union
Structure |
Union |
(i) It is the collection of data items having dissimilar data types. |
(i) Same as structure but it differs in its storage class. |
(ii) Memory size is determined by sum of memories allocated to all the members. |
(ii) Memory size is determined by the memory allocated to the largest member. |
(iii) Multiple members can be simultaneous accessed at a time. |
(iii) Only one member can be accessed at a time. |
(iv) The struct keyword is used to define structure. |
(iv) The union keyword is used to define union. |
(v) Syntax:
struct tag_name{
data_type member_1;
data_type member_2;
................
data_type member_n;
} var; |
(v) Syntax:
union tag_name{
data_type member_1;
data_type member_2;
................
data_type member_n;
} var; |
(vi) Example:
struct data{
char x;
int y;
float z;
} var;
Memory size for var is 9 bytes. |
(vi) Example:
union data{
char x;
int y;
float z;
} var;
Memory size for var is 4 bytes. |
Difference between structure and Array
Structure |
Array |
(i) It is the collection of data items dissimilar data types. |
(i) It is the collection of data items having similar data types. |
(ii) Each data item is called member. |
(ii) Each data item is called element. |
(iii) It is user defined data type. |
(iii) It is built in data type. |
(iv) It is possible to define array of structure. |
(iv) It is not possible to define array of array or structure of array. |
(v) Syntax:
struct tag_name{
data_type member_1;
data_type member_2;
................
data_type member_n;
} var; |
(v) Syntax:
data_type array_name[size]; |
(vi) Example:
struct temp{
int p;
float q;
} x; |
(vi) Example:
int x[10]; |
Workout Examples
Program 84 Write C program that reads name and address of different students and rearranges them on the basis of name in alphabetical order.
#include<stdio.h>
#include<string.h>
void sorting (int n);
struct student
{
char name[30];
char address[30];
} s[100];
int main()
{
int n,i;
printf("How many records do you want to enter: \n ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Name : \n ");
scanf("%s",s[i].name);
printf("Enter Address : \n ");
scanf("%s",s[i].address);
}
sorting(n);
return 0;
}
void sorting(int n)
{
struct student temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(s[i].name,s[j].name)>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n Name and address in alphabetical order\n ");
for(i=0;i<n;i++)
{
printf("%s\t %s\n",s[i].name,s[i].address);
}
}
Program 85 Write C program that takes name and marks of 20 students. Sort data according tomarks in descending order and display them.
#include<stdio.h>
void sorting(int n);
struct student
{
char name[20];
float marks;
}s[20];
int main()
{
int i,n;
printf("\nHow many records do you want to enter:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Name:");
scanf("%s",s[i].name);
printf("\nEnter Marks:");
scanf("%f",&s[i].marks);
}
sorting(n);
return 0;
}
void sorting(int n)
{
struct student temp;
int i,j;
for(i=0;i<n-1;i++) {
for(j=i+1;j<n;j++)
{
if(s[i].marks<s[j].marks)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n Records in Descending Order on the basis of Marks\n");
for(i=0;i<n;i++)
{
printf("\n%s %f",s[i].name,s[i].marks);
}
}
Program 86 Define array of structure student with members: sid, name, sub1, sub2, sub3, sub4, sub5 and total. Write an interactive program to perform the following options: Input Records, Display records in Ascending Order (On the basis of Total marks), Display the record of student scoring highest total mark, Search the record of student by using sid and Exit.
#include<stdio.h>
int menu();
void input(int n);
void display(int n);
void highestmark(int n);
void search(int n, int key);
struct student
{
int sid;
char name[50];
int sub1,sub2,sub3,sub4,sub5,total;
}s[100];
int main(){
int n,ch,key,temp;
do{
ch=menu();
switch(ch)
{
case 1:
printf("\n How many records: ");
scanf("%d",&n);
input(n);
break;
case 2:
display(n);
break;
case 3:
highestmark(n);
break;
case 4:
printf("Enter student id for searching: ");
scanf("%d",&key);
search(n,key);
break;
case 5:
printf("Thanks for using this program");
break;
}
} while(ch!=5);
return 0;
}
int menu()
{
int ch;
printf("\n 1. ----> Input Records ");
printf("\n 2. ----> Display Records ");
printf("\n 3. ----> Highest marks ");
printf("\n 4. ----> search Records ");
printf("\n 5. ----> Exit ");
printf("\n Enter your choice: ");
scanf("%d",&ch);
return (ch);
}
void input(int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Enter student id : ");
scanf("%d",&s[i].sid);
printf("Enter name : ");
scanf("%s",s[i].name);
printf("Enter marks of five subjects: ");
scanf("%d%d%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);
s[i].total=s[i].sub1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;
}
}
void display(int n)
{
struct student temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].total>s[j].total)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("\n Student ID=%d\t Name=%s\n",s[i].sid,s[i].name);
printf("\n Sub1=%d , Sub2=%d , Sub3=%d , Sub4=%d ,Sub5=%d \n",s[i].sub1,s[i].sub2,s[i].sub3,s[i].sub4,s[i].sub5);
}
}
void highestmark(int n)
{
int i,max=s[0].total;
for(i=0;i<n;i++)
{
if(s[i].total>max)
max=s[i].total;
}
for(i=0;i<n;i++)
{
if(max==s[i].total)
{
printf("\n Student ID=%d\t Name=%s\n",s[i].sid,s[i].name);
printf("\n Sub1=%d , Sub2=%d , Sub3=%d , Sub4=%d ,Sub5=%d \n",s[i].sub1,s[i].sub2,s[i].sub3,s[i].sub4,s[i].sub5);
}
}
}
void search(int n, int key)
{
int i,flag=0;
for(i=0;i<n;i++)
{
if(key==s[i].sid)
{
flag=1;
break;
}
}
if(flag==0)
printf("\n Sorry ! record not found ");
else
printf("\n Student ID=%d\t Name=%s\n",s[i].sid,s[i].name);
printf("\n Sub1=%d , Sub2=%d , Sub3=%d , Sub4=%d ,Sub5=%d \n",s[i].sub1,s[i].sub2,s[i].sub3,s[i].sub4,s[i].sub5);
}
4.4 Pointers
Definition of pointer
A pointer is a variable that points to another variable which means it contains the memory address (location) of another variable and is declared as the pointer type (It doesn't take the value of the variable). As an example if one variable is a data type and second variable the pointer type which points to the first variables type, then the contents of the second canable is the address of the first variable.
POINTS TO REMEMBER
pointer is a special type of variable that represents memory address of a rather than its value
Value at address
2000
address the first variable
Address
First
Second
Here, the second variable contains the address of the first variable. 5 is the value at address 2000, which is the address of the first variable
Pointer is one of the most powerful and useful feature of the C language, which
distinguishes it from other languages. The concept of pointers is somewhat complex but is simple when compared to its advantages. Pointer is more difficult to understand but the proper use of it makes the C language
Features of Pointe
Pointer saves memory space.
Pointer assigns the memory space and also releases it which makes the best use of the available memory (dynamic memory allocation). The execution time is faster because data manipulation is done directly inside
memory Pointer is closed to array so it is efficient for solving array and string related problems
Pointer is closed to hardware so it is very efficient for solving hardware interfacing problems
4.4.2 The Address (&) and Indirection (*) Operator
The & is the address operator, it represents the address of the variable the value at It the value at the address operator is
4.4.3 Pointer Expression and Assignment
4.4.4 Call by values and call by reference
4.5 Working with Files
4.5.1 Concept of Data Files
A data file is defined as the collection of data or information which is permanently stored inside secondary memory as a single unit. We can read , write , append and delete data in data file as per our requirements.
4.5.2 Sequential and Random Access File
1. Sequential File Processing : In this type of technique, data is sequentially accessed from/to data file. It is very time consuming technique. If we need to access the last record of a file, then we need to access all the records before that record.
2. Random File Processing : In this type of technique, data is randomly accessed anywhere from/to data file. It is more faster technique than the previous one. We can read and write data in particular part of a file with the help of the functions ftell(),seek() and rewind().
- ftell(): It takes file pointer as parameter and returns long data type that represents current position of the file in terms of bytes.
n=ftell(fp);
- rewind(): It takes file pointer as parameter and reset the position to the start of the file.
rewind(fp);
- fseek(): It helps to move the file position to the desire location within the file. It takes three parameters fp file pointer, offset position of the file in terms of bytes and position specifies three values: 0-beginning, 1-current position and 2-end of file.
fseek(fp,offset,position);
Assignment-10
1. Differentiate between sequential file access and random file access technique.
4.5.3 File Manipulation function
1. fopen() |
To create new data file |
2. fclose() |
To close data file |
3. getc() |
To read a character from data file |
4. putc() |
To write a character to data file |
5. getw() |
To read an integer from data file |
6. putw() |
To write an integer to new data file |
7. fscanf() |
To read formatted data from data file |
8. fprintf() |
To write formatted data to data file |
9. fread() |
To read record from data file |
10. fwrite() |
To write record to data file |
Defining and opening Data File
The following syntax is used to define data file.
FILE *fp;
fp=fopen("filename","mode");
The keyword FILE is used to declare file data type. The first statement defines file pointer variable with data type FILE. The second statement creates file with name filename and returns memory address that is assigned to the file pointer fp. The mode defines the purpose of file which can be one of the followings:
r | open an existing file for reading (display, count,read) |
w | open a new file for writing (create, store,write) |
a | open an existing file for appending |
r+ | open an existing file for both reading and writing |
w+ | open a new file for both reading and writing |
a+ | open an existing file for both reading and writing |
Compiler automatically assigns special character at the end of the file called EOF (end of file).
Closing data file
A data file must be closed after doing various operations such as reading , writing etc. It ensures that all the information associated with the file is flusged out from the memory and all links to the file are broken. It also helps us to protects from accidental lose if data from the file. The following syntax is used to close the file.
fclose(filePointer);
Assignment-11
1. Write different modes of file handling.
General guidelines for solving a file related problems
- Step 1: Define file pointer variable with type FILE either inside or outside main() function.
FILE *fp;
- Step 2: For the first time create new data file using fopen function in write mode.
fp=fopen("filename","w");
- Step 3: Take data from the keyboard using input functions scanf,gets and getchar and store the data to the file using write functions : fprintf,putc,putw and fwrite.
- Step 4: During read operation , first open the data file in read mode.
fp=fopen("filename","r");
- Step 5: Read the data from the file using read functions: fscanf,getc,getw and fread and display the data on screen using output functions: printf,puts and putchar.
- Step 6: Finally close the data file using function fclose.
fclose(fp);
getc() and putc() functions
Function getc() helps us to read single character from file and putc() helps us to write single character to file. In the following example, ch is character variable and fp is the file pointer.
ch=getc(fp); // to read data
putc(ch,fp);
// to write data, fp is file pointer and ch is character variable
Program 96 Write a program to write and read characters to/from file using putc() and getc().
#include<stdio.h>
main()
{
FILE *fp;
char ch;
printf("\n Input Data (to exit press ctrl +z)=");
fp=fopen("data.txt", "w");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
printf("\n Output Data \n");
fp=fopen("data.txt", "r");
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
Assignment-12
1. List out different file manipulation functions.
getw() and putw() functions
Function getw() helps us to read single integer from file and putw() helps us to write single integer to the data file. In the following example, x is integer variable and fp is file pointer.
x=getw(fp);
putw(x,fp);
Program 97 Write a program to write and read integers to/from file using putw() and getw().
#include<stdio.h>
main()
{
FILE *fp;
int x,i=0,n;
printf("\n How many numbers do you want to enter : ");
scanf("%d",&n);
fp=fopen("number.txt", "w");
while(i<n)
{
printf("Input numbers: ");
scanf("%d",&x);
putw(x,fp);
i++;
}
fclose(fp);
fp=fopen("number.txt", "r");
printf("\n The numbers are : ");
while((x=getw(fp))!=EOF)
printf("%5d",x);
fclose(fp);
}
Assignment-13
1. Write a program that write integers to a data file.
#include<stdio.h>
int main()
{
FILE *fp;
int x,i=0,n;
printf("\n How many numbers do you want to enter : ");
scanf("%d",&n);
fp=fopen("number.txt", "w");
while(i<n)
{
printf("Input numbers: ");
scanf("%d",&x);
putw(x,fp);
i++;
}
fclose(fp);
return 0;
}
2. Write a program to read integers from the data file.
#include<stdio.h>
int main()
{
FILE *fp;
int x;
fp=fopen("number.txt", "r");
printf("\n The numbers are : ");
while((x=getw(fp))!=EOF)
printf("%5d",x);
fclose(fp);
return 0;
}
fscanf() and fprintf() functions
Function fscanf () helps us to read formatted data from file and fprintf() helps us to write formatted data to file. In the following example, fp is file pointer, control string defines data type for the respective variables.
fscanf(fp,"control string",variables);
fprintf(fp,"control string",variables);
Program 98 Write a program to write roll, name and percentage of 5 students to a file.
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i=1;
fp=fopen("info.txt", "w");
do
{
printf("\n Enter roll no : ");
scanf("%d",&roll);
printf("\n Enter name : ");
scanf("%s",name);
printf("\n Enter percenatge : ");
scanf("%f",&per);
fprintf(fp,"\n %d\t %s\t %f",roll,name,per);
i++;
} while(i<=5);
fclose(fp);
return 0;
}
Program 99 Write a program to read roll, name and percentage of 5 students from the file.
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
fp=fopen("info.txt", "r");
printf("\n Data from the file \n ");
while((fscanf(fp,"\n %d\t %s\t %f",&roll,name,&per))!=EOF)
printf("\n %d\t %s\t %f", roll , name , per);
fclose(fp);
return 0;
}
Assignment-14
1. Write a program to write roll, name and percentgae of 10 students to a data file.
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i;
fp=fopen("record.txt","w");
for(i=0;i<10;i++)
{
printf("Enter roll , name and percentage : ");
scanf("%d%s%f",&roll,name,&per);
fprintf(fp,"%d\t %s\t %0.2f\n",roll,name,per);
}
fclose(fp);
return 0;
}
2. Write a program to read roll, name and percentgae of 10 students from the data file.
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i;
fp=fopen("record.txt","r");
while((fscanf(fp,"%d%s%f",&roll,name,&per))!=EOF)
printf("%d\t %s\t %0.2f\n",roll,name,per);
fclose(fp);
return 0;
}
fread() and fwrite() functions
Function fread () helps us to read structure type data i.e. record from data file and fwrite() helps us to write structure type data to the data file. In the following example, variable is structure type variable of type tagname, sizeof() functions determines the memory size of structure , 1 specifies the number of record that can be accessed at once and fp is file pointer.
fread(&variable,sizeof(tagname),1,fp);
fwrite(&variable,sizeof(tagname),1,fp);
Program 100 Write a program to write and read a record to/from a data file using fwrite()/fread() functions.
#include<stdio.h>
struct employee
{
int empid;
char name[30];
float salary;
}emp;
int main()
{
FILE *fp;
fp=fopen("employee.txt","w");
printf("Enter empid, name and salary : ");
scanf("%d%s%f",&emp.empid,emp.name,&emp.salary);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
fp=fopen("employee.txt","r");
fread(&emp,sizeof(emp),1,fp);
printf("%d\t %s\t %f",emp.empid,emp.name,emp.salary);
fclose(fp);
return 0;
}
Program 101 Write a program to write and read roll, name and percentage of 5 students to/from data file using fprintf() and fscanf().
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i;
fp=fopen("srecord.txt","w");
for(i=0;i<5;i++)
{
printf("Enter roll :");
scanf("%d",&roll);
printf("Enter name :");
scanf("%s",name);
printf("Enter Percentage :");
scanf("%f",&per);
fprintf(fp,"%d\t %s\t %0.2f\n",roll,name,per);
}
fclose(fp);
fp=fopen("srecord.txt","r");
printf("\n Data from the file \n");
while((fscanf(fp,"%d%s%f",&roll,name,&per))!=EOF)
printf("%d\t %s\t %0.2f\n",roll,name,per);
fclose(fp);
return 0;
}
Program 102 Write a program that stores roll, name and percentage of students to a data file until you press y-yes and finally displays the contents of the data file.
#include<stdio.h>
int main()
{
FILE *fp;
int roll;
char name[30];
float per;
char ch='y';
fp=fopen("srecord.txt","w");
while(ch!='n')
{
printf("\n Enter roll :");
scanf("%d",&roll);
printf("\n Enter name :");
scanf("%s",name);
printf("\n Enter Percentage :");
scanf("%f",&per);
fprintf(fp,"%d\t %s\t %0.2f\n",roll,name,per);
printf("\n Do you want to add more record (y-Yes/n-No): ");
scanf(" %c",&ch);
}
fclose(fp);
fp=fopen("srecord.txt","r");
printf("\n Data from the file \n");
while((fscanf(fp,"%d%s%f",&roll,name,&per))!=EOF)
printf("%d\t %s\t %0.2f\n",roll,name,per);
fclose(fp);
return 0;
}
Program 103 Write a program to write and read successive records to/from a data file(Using structure variable)
#include<stdio.h>
struct employee
{
int empid;
char fname[20],lname[20];
float salary;
}emp;
int main()
{
FILE *fp;
char ch='y';
fp=fopen("employee.txt","w");
while(ch!='n')
{
printf("\n Enter employee id :");
scanf("%d",&emp.empid);
printf("\n Enter first name :");
scanf("%s",emp.fname);
printf("\n Enter last name :");
scanf("%s",emp.lname);
printf("\n Enter salary :");
scanf("%f",&emp.salary);
fprintf(fp,"%d\t %s\t %s\t %0.2f\n",emp.empid,emp.fname,emp.lname,emp.salary);
printf("\n Do you want to add more record (y-Yes/n-No): ");
scanf(" %c",&ch);
}
fclose(fp);
fp=fopen("employee.txt","r");
printf("\n Data from the file \n");
while((fscanf(fp,"%d%s%s%f",&emp.empid,emp.fname,emp.lname,&emp.salary))!=EOF)
printf("%d\t %s\t %s\t %0.2f\n",emp.empid,emp.fname,emp.lname,emp.salary);
fclose(fp);
return 0;
}
4.5.4 Opening , reading, writing and appending on/from data file
The following program gives an idea about appending records to the existing file. It consists three functions void write(), void read() and void append(). void write() takes data from keyboard and stores the respective data in file "employee.txt", void read() takes data from the data file and displays the contents of the file on screen and finally void append() appends records on the existing file "employee.txt".
Program 104 Write a program to write,read and append successive records to/from a data file.
#include<stdio.h>
void write();
void read();
void append();
struct employee
{
int empid;
char ename[50];
float salary;
}emp;
FILE *fp;
int main()
{
int ch;
do
{
printf("\n 1-> Write Data ");
printf("\n 2-> Read Data ");
printf("\n 3-> Append Data ");
printf("\n 4-> Exit ");
printf("\n Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: write();
break;
case 2: read();
break;
case 3: append();
break;
default:
printf("\n Thanks for using this program");
}
}while(ch!=4);
return 0;
}
void write()
{
char choice='y';
fp=fopen("employee.txt","w");
while(choice!='n')
{
printf("\n Enter employee id , name and salary : ");
scanf("%d%s%f",&emp.empid,emp.ename,&emp.salary);
fprintf(fp,"\n %d\t %s\t %f",emp.empid,emp.ename,emp.salary);
printf("\n Do you want to add more records (y-Yes/n-No): ");
scanf(" %c",&choice);
}
fclose(fp);
}
void read()
{
fp=fopen("employee.txt","r");
printf("\n Data from file \n ");
while((fscanf(fp,"%d\t %s\t %f",&emp.empid,emp.ename,&emp.salary))!=EOF)
{
printf("\n %d\t %s\t %f",emp.empid,emp.ename,emp.salary);
}
fclose(fp);
}
void append()
{
char choice='y';
fp=fopen("employee.txt","a");
while(choice!='n')
{
printf("\n Enter employee id , name and salary : ");
scanf("%d%s%f",&emp.empid,emp.ename,&emp.salary);
fprintf(fp,"\n %d\t %s\t %f",emp.empid,emp.ename,emp.salary);
printf("\n Do you want to add more records (y-Yes/n-No): ");
scanf(" %c",&choice);
}
fclose(fp);
}
Program 105 Write a program designing a menu based system which has the following feature:
a) Appending records
b) Reading records
c) Delete Records
d) Quit
#include<stdio.h>
void append();
void read();
void deleterec();
struct employee{
int empid;
char ename[50];
float salary;
}emp;
FILE *fp1,*fp2;
int main()
{
int ch;
do{
printf("\n 1-> Appending records ");
printf("\n 2-> Reading records");
printf("\n 3-> Delete records");
printf("\n 4-> Quit");
printf("\n Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: append();
break;
case 2: read();
break;
case 3: deleterec();
break;
default:
printf("\n Thanks for using this program. ");
}
}while(ch!=4);
return 0;
}
void append()
{
char choice='y';
fp1=fopen("employee.txt","a");
while(choice!='n')
{
printf("Enter employee id, name and salary : ");
scanf("%d%s%f",&emp.empid,emp.ename,&emp.salary);
fprintf(fp1,"\n %d\t %s\t %f",emp.empid,emp.ename,emp.salary);
printf("Do you want to add more records (y-Yes/n-No) : ");
scanf(" %c",&choice);
}
fclose(fp1);
}
void read()
{
fp1=fopen("employee.txt","r");
printf("\n Data from the file \n ");
while((fscanf(fp1,"%d%s%f",&emp.empid,emp.ename,&emp.salary))!=EOF)
{
printf("\n %d\t %s\t %0.2f",emp.empid,emp.ename,emp.salary);
}
fclose(fp1);
}
void deleterec()
{
int deleteid;
fp1=fopen("employee.txt","r");
fp2=fopen("temp.txt","w");
printf("\n Enter empid to be deleted : ");
scanf("%d",&deleteid);
while((fscanf(fp1,"%d%s%f",&emp.empid,emp.ename,&emp.salary))!=EOF)
{
if(deleteid==emp.empid)
continue;
else
fprintf(fp2,"\n %d\t %s\t %f",emp.empid,emp.ename,emp.salary);
}
printf("\n One record deleted. ");
fclose(fp1);
fclose(fp2);
remove("employee.txt");
rename("temp.txt","employee.txt");
}
Remove and Rename Functions
The remove() function helps us to delete the file specified as a parameter and the generalsyntax is:
remove("filename");
The rename() function helps us to rename the existing file into new file and the general syntax is:
rename("oldfilename","newfilename");
Program 106 Write a program to delete and rename file using remove and rename command. [NEB 2067]
#include<stdio.h>
int main()
{
FILE *fp;
char name[30];
fp=fopen("oldfile.txt","w");
printf("\n Enter your name : ");
scanf("%s",name);
fprintf(fp,"%s",name);
fclose(fp);
rename("oldfile.txt","newfile.txt");
remove("newfile.txt");
return 0;
}
Program 107 Write a program which writes "Welcome to Nepal" in a data file.[NEB 2070]
#include<stdio.h>
int main()
{
FILE *fp;
char str[30]="Welcome to Nepal";
fp=fopen("Nepal.txt","w");
fprintf(fp,"%s",str);
fclose(fp);
printf("Data written successfully.");
return 0;
}
Past Questions from File Handling
Write a program to enter 'name','roll no' and 'marks' of 10 students and store them in a file. Read and display the same from the file. [NEB 2065,2068]
#include<stdio.h>
int main()
{
FILE *fp;
return 0;
}