PPS Mid 2 Complete Notes
PPS Mid 2 Complete Notes
Functions
It has a name and it is reusable. It can be executed from as many different parts
in a program as required, it can also return a value to the calling program.
All executable code resides within a function. It takes input, does something
with it, then gives the answer.
A C program consists of one or more functions.
A computer program cannot handle all the tasks by itself. It requests other
programs like entities called functions in C.
We pass information to the function using arguments.
A function either can return a value or returns nothing. Function is a subprogram
that helps reduce coding.
Advantages of Functions:
Function makes the lengthy and complex programs easy and in short forms.
By using functions, memory space can be properly utilized and less memory is
required to run the program.
It allows more than one person to work on one program.
Function increases the execution speed of the program and makes the
programming simple.
By using the function, portability of the program is very easy.
It removes the redundancy.
Debugging (removing error) becomes very easier and fast using the function
sub-programming
Functions are more flexible than library functions.
Testing (verification and validation) is very easy by using functions.
Types of Functions:
For example, sqrt() is a mathematical library function which is used for finding the
square root of any number.
The function scanf() and printf() are input and output library functions similarly we
have strcmp() and strlen() for string manipulations.
Note: To use a library function, we have to include the corresponding header file using
the preprocessor directive #include.
For example: To use input and output functions like printf() and scanf() we have to
include stdio.h, for math library functions we have to include math.h, for string library
functions string.h should be included.
A user can create their own functions for performing any specific task of a program
called user defined functions.
1. Function Declaration
2. Function Definition
3. Function Call
Function Declaration:
The program or a function that calls a function is referred to as the calling program
or calling function. The calling program should declare any function that is to be used
later in the program, this is known as the function declaration or function prototype.
Syntax:
Function call:
When we wish to use a function, we can "call" it by name, then control is sent to the
block of code with that name.
Any values that the function needs to perform its job are listed in the parentheses that
immediately follow the name are called arguments.
The number of arguments (or values) must match the variables in the definition by
type and number.
A semicolon must be present, when the function is called within the main() function.
Syntax:
The following figure illustrates function prototype, function call and function definition.
Function definition:
The function definition consists of the whole description and code of a function. It tells
what the function is doing and what are the inputs and outputs for that.
A function is called by simply writing the name of the function followed by the argument
list inside the parenthesis.
1. Function Header
Categories of functions:
The functions are categorized into 4 types based on the arguments and return
type. They are
Here, the called function does not receive any data from the calling function and it
does not return any data back to the calling function. Hence, there is no data transfer
between the calling function and the called function.
Here, the called function receives the data from the calling function. The arguments
should match in number, data type and order. But, the called function does not return
Here, the called function does not receive any data from the calling function. It
manages with its local data to carry out the specified task. However, after the specified
processing the called function returns the computed data to the calling function. It is
also a one-way data communication between the calling function and the called
function.
Here, the called function receives data from the calling function and it can compute
the task using these arguments. After computing the task, the called function returns
the results to the calling function. In this way the main() function will have control over
A method of information interchange between the calling function and called function is
known as parameter passing. There are two methods of parameter passing:
1. Call by Value
2. Call by Reference
Call by Value: The call-by-value method copies the value of an argument into the formal
parameter of the function. Therefore, changes made by the function to the parameters have
no effect on the variables used to call it.
Call by Reference:
Call by reference method copies the address of an argument into the formal parameter. Inside
the function, this address is used to access the argument used in the call. In this way, changes
made to the parameter affect the variable used in the call to the function.
Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the
parameters must be declared as pointer types.
1. Pass Entire array (Formal Parameters as a pointer, sized array, sized unsized array)
1. In which we are calling the function again and again but with different array element
is too much time consuming.
2. It is better to pass complete array to the function so that we can save some system
time required for pushing (insertion) and popping (remove).
3. We can also pass the address of the individual array element to function so that
function can modify the original copy of the parameter directly.
Like one dimensional array, we can also pass multidimensional arrays to the functions. The
approach is similar to the passing one-dimensional arrays.
2. In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
The strings are treated as character arrays in C and therefore the rules for passing strings to
functions are very similar to those for passing arrays to functions.
1. The string to be passed must be declared as formal argument of the function when it
is defined.
Example
……………….
2. The function prototype must show that the argument is a string. For the above function
definition, the function prototype can be written as
3. A call to the function must have a string array name without subscripts as its actual
argument.
Example display(name)
Write a c program to find length of the string using functions.
Recursion
Advantages of recursion
Disadvantages of recursion
A recursive algorithm uses itself to solve one or more smaller identical problems.
= 1 [for N= 1]
= 3!
= 2! * 3
= (1! * 2) * 3
=1*2*3
C Program to find factorial of a given number.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n Factorial of a given number %d is %d",n,f);
return 0;
}
int fact(int n)
{
if(n==1||n==0)
{
return 1;
}
else
{
return n*fact(n-1);
}
#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int a,b,f;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
f=gcd(a,b);
printf("\n GCD of %d and %d is %d",a,b,f);
return 0;
}
int gcd(int n1,int n2)
{
if(n2==0)
{
return n1;
}
else
{
return gcd(n2,n1%n2);
}
}
C program to display fibonacci series using recursion
Fib(n) = fib(n-1)+fib(n-2)
Fib(0) = 0 fib(1)=1
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int i,n;
printf("\n Enter no of elements in the series:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n%d",fib(i));
}
return 0;
}
int fib(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return fib(n-1)+fib(n-2);
}
}
#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
printf("\n ack(%d,%d) = %d",a,b,ack(a,b));
return 0;
}
int ack(int x,int y)
{
if(x==0)
{
return y+1;
}
else if(y==0)
{
return ack(x-1,1);
}
else
{
return ack(x-1,ack(x,y-1));
}
}
Definition: Pointer is a variable which contains the address in memory of another variable.
Benefits of Pointers
Whenever we declare a variable the system allocates memory to hold the value of the variable.
Consider the following statement.
This statement instructs the system to find a location for the integer variable quantity and puts
the value 179 in that location. Let us assume that the system has chosen the address location
5000 for quantity.
Quantity Variable
179 Value
5000 Address
During execution of the program the system always associates the name quantity with the
address 5000. We may have access to the value 179 by using either name quantity or the address
5000. Since memory address are simply numbers they can be assigned to some variables that can
be stored in some memory. Such variables that hold memory addresses are called pointer
variables.
P 5000 5048
The value of the variable P is the address of the variable quantity, we may access the value of
quantity by using the value of p and therefore, we say that the variable p points to the variable
quantity. Thus P gets the name pointer.
Pointer Constants:- Memory address within a system are referred to as pointer constants. We
cannot change them, we can only use them to store data values.
Pointer Value: – We cannot save the value of a memory address directly. We can only obtain the
value through the variable stored there using the address operator (&) . The value thus obtained
is known as pointer value. The pointer value may change during execution of the program.
Pointer variable :- once we have a pointer value, it can be stored into another variable. The
variable that contains a pointer value is called a pointer variable.
The address of operator (&) returns the address of the variable associated with it.
e.g: p = &quantity;
The & operator can be used only with a simple variable or an array element.
If x is an array, then expressions such as &x[0] and &x[i+3] are valid and represent the address
of 0th and (i+3)th elements of x.
Syntax
data_type *pt_name;
1. the asterisk (*) tells that the variable pt_name is a pointer variable.
e.g: int *p; //p is a pointer variable that points to an integer data type.
p ? ?
int *p;
p = &quantity;
or
int *p = &quantity;
1. We must ensure that the pointer variable always point to the corresponding type of the data.
It is possible to combine the declaration of data variable, the declaration of pointer variable and
the initialization of the pointer variable in one step.
int *p = NULL;
The indirection operator (*), dereferencing operator id used to access the value of the variable
using the pointer.
e.g:
quantity = 179;
p = &quantity;
n = *p;
The first line declares quantity and n as integer variables and p as a pointer variable pointing to an
integer. The second line assigns the value 179 to quantity and the third line assigns the address of
quantity to the pointer variable p. the fourth line contain the indirection operator * . When the
operator * is placed before a pointer variable in an expression, the pointer returns the value of the
variable of which the pointer value is the address. So *p returns the value of the variable quantity.
Chain of Pointers
It is possible to make a pointer to point to another pointer, thus creating a chain of pointers.
p2 p1 variable
Address 2 Address 1 Value
here the pointer p2 contains the address of the pointer variable p1, which points to the location
that contains the desired value. This is known as multiple indirections.
int **p2;
This declaration tells the computer that p2 is a pointer to a pointer of int type. The pointer p2 is
not a pointer to an integer, but rather a pointer to an integer pointer.
void main()
{
int x, *p1, **p2;
x = 100;
p1 = &x;
p2 = &p;
printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an integer and p2 as a
pointer to a pointer to an integer.
The symbol /* is considered as the beginning of a comment and therefore the statement fails.
Note:
1. C allows us to add to or subtract integers from the pointer.
2. If p1 and p2 are the pointers point to the same array, then p2-p1 gives the number of
elements between p1 and p2.
3. Pointers can be compared using the relational operators.
4. We may not use pointers in division or multiplication.
5. Two pointers cannot be added.
An expression like
p1++;
will cause the pointer p1 to point to the next value of its type. For example, if p1 is an integer
pointer with an initial value, say 2800, then after the operation p1 = p1 + 1, the value of p1 will
be 2802, and not 2801. That is, when we increment a pointer, its value is increased by the length
of the data type that it points to, this is called the scale factor.
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],sum=0,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<5;i++,p++)
{
sum=sum+*p;
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],max,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
max=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(max < *p)
{
max=*p;
}
}
printf("\n largest value = %d\n",max);
getch();
}
Write a C program to find smallest element from the given array elements using pointers.
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i,j,*temp;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<4;i++)
{
for(j=0;j<(5-i-1);j++)
{
if(*(p+j) > *(p+j+1))
{
*temp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = *temp;
}
}
}
printf(“%s”,str1);
puts(str1);
Although str1 is a pointer to the string, it is also the name of the string. Therefore we do not need
to use indirection operator *.
#include<stdio.h>
#include<conio.h>
void main()
{
char *s;
int len=0;
clrscr();
printf("\n Enter a string \n");
scanf("%s",s);
while(*s!='\0')
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s1,*s2,*s3;
int i=0,j;
clrscr();
printf("\n Enter first string\n");
scanf("%s",s1);
printf("\n Enter second string\n");
scanf("%s",s2);
for(i=0,s3=s1;*s3!='\0';s3++,i++);
for(j=0;*s2!='\0';j++)
{
*(s3+j) = *(s2+j);
}
*(s3+j)='\0';
printf("\n concatenated string = %s\n",s1);
getch();
}
In C, a constant character string always represents a pointer to that string. And therefore, the
following statements are valid.
char *name;
name = “delhi”;
These statements will declare name as a pointer to character and assign to name the constant
character string “delhi”. We might remember that this type of assignment does not apply to
character arrays.
The statements like
char name[20];
name = “Delhi”;
do not work.
Array of Pointers
We know that rarely the individual strings will be equal lengths. Therefore, instead of making
each row a fixed number of characters, we can make it a pointer to a string of varying length.
For example:
Char *name[3] = {
“New Zealand”;
“Australia”,
“India”
};
Declares name to be an array of three pointers to characters, each pointer pointing to a particular
name as:
This declaration allocates only 28 bytes, sufficient to hold all the characters as shown.
The following statements would print out all the three names:
for(i=0;i<3;i++)
{
Printf(“%s\n”,name[i]);
}
To access the jth character in the ith name, we may write as
*(name[i]+j)
Note:
1. The character arrays with the rows of varying length are called ‘ragged arrays’ and are
better handled by pointers.
2. *p[3] declares p as an array of three pointers.
3. (*p)[3] declares p as a pointer to an array of three elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input
loop */
int main(int argc, char *argv[]) {
char (*p)[10],name[5][10],temp[10];
int i,j,k;
p=name;
printf("\n Enter 5 city names\n");
for(i=0;i<5;i++)
{
fflush(stdin);
scanf("%s",p[i]);
}
for(i=1;i<5;i++)
{
for(j=0;j<=(5-i-1);j++)
{
if(strcmp(p[j],p[j+1])>0)
{
strcpy(temp,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],temp);
}
}
}
printf("\n After sorting city names are\n");
return 0;
}
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int x,y,z;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
printf("\n Before swaping numbers are \n");
printf("%d\t%d\n",x,y);
swap(&x,&y);
printf("\n After swapping numbers are \n");
printf("%d\t%d\n",x,y);
getch();
}
void swap(int *p,int *q)
{
int *t;
*t = *p;
*p = *q;
*q = *t;
}
Output:
Enter two numbers
10
20
A function can return a single value by its name or return multiple values through pointer
parameters. Since pointers are a data type in C, we can also force a function to return a pointer to
the calling function.
C program to illustrate function returns a pointer
#include<stdio.h>
#include<conio.h>
int *large(int *p, int *q);
void main()
{
Int a=10, b=20, *p;
clrscr();
p=large(&a,&b);
printf(“%d”,*p);
getch();
}
int *large(int *c,int *d)
{
if(*c > *d)
return c;
else
return d
}
The function larger receives the addresses of the variable a and b, decides which one is larger
using the pointers x and y and then returns the address of its location. The returned value is then
assigned to the pointer variable p in the calling function. In this case, the address of b is returned
and assigned to p and therefore the output will be the value of b., b namely 20.
Pointers to functions
A function like a variable, has a type and an address location in the memory. It is therefore
possible to declare a pointer to a function, which can then be used as an argument in another
function. A pointer to a function is declared as follows
type (*fptr) ( );
this tells the compiler that fptr is a pointer to a function, which returns type value. The
parenthesis around *fptr are necessary.
#include<stdio.h>
#include<conio.h>
int fun(int,int);
int (*f)();
void main()
{
int a,b,c,*p,*q,r;
clrscr();
printf("Enter a & b Values\n");
scanf("%d%d",&a,&b);
//p=&a;
//q=&b;
f=fun;
r=(*f)(a,b);
printf("\nSum=%d",r);
}
int fun(int x,int y)
{
int z;
z = x +y;
return z;
}
Casting
Program instructions and global variables are stored in a region known as permanent storage area
and the local variables are stored in another area known as stack. The area between these two
regions is available for dynamic memory allocation during execution of a program. This free
memory is called heap. The size of the heap changes when program is executed due to creation
and death of variables that are local to functions and block. Therefore it is possible to encounter a
overflow during dynamic memory allocation process. In such situations the memory allocation
functions mentioned above return a NULL pointer.
Malloc:
A block of memory may be allocated using the function malloc. The malloc function reserves a
block of memory of specified size and returns a pointer of type void. This means we can assign it
to any type of pointer.
ptr is a pointer of type cast-type. The malloc returns a pointer to an area of memory with size
x = (int *)malloc(100*sizeof(int));
Note:
1. The storage space allocated dynamically has no name and therefore its contents can be
accessed only through pointer.
2. malloc allocates a block of contiguous bytes. The allocation can fail if the space in the heap is
not sufficient to satisfy the request. If it fails it returns a NULL.
Calloc:
Calloc is used to allocating memory space at run time for storing derived data types such as
arrays and structures. While malloc allocates a single block of storage space, calloc allocates
multiple blocks of storage, each of the same size, and then sets all bytes to 0.
realloc():
realloc is used to allocate or reduce memory size during execution of a program.
ptr= malloc(size);
Then reallocation of space may be done by the statement.
ptr = realloc( ptr, new size);
This function allocates a new memory space of size new size to the pointer variable and returns a
pointer to the first byte of the new memory block.
If the function is unsuccessful in locating additional space it returns a NULL pointer and the
original block is lost.
free():
Compile time storage of a variable is allocated and released by the system in accordance with its
storage class. With the dynamic run-time allocation, it is our responsibility to release the space
when it is not required
Free is used release the memory is created by malloc or calloc function.
Syntax:
free(ptr);
Note:
1. It is not the pointer that is being released but rather what it points to.
2. To release an array of memory that was allocated by calloc we need only to release the
pointer once. It is an error to attempt to release elements individually.
Write a program that uses a table of integers whose size will be specified interactively at
runtime.
Self-referential Structure:
Self-referential structure is a structure in which one member is a pointer which points to the same
type of structure is called self-referential structure.
struct node
{
int data;
struct node *next;
}
Visual representation
Struct node
{
Int data;
Struct node *prev;
Struct node *next;
}
In the above example, each node has three fields, they are data, previous and next. Here prev and
next are the pointers which points to the same type structure. Hence it is also called as a self-
referential structure.
Pointer Programs
};
Remember:
After defining a structure we can declare variables of that type. It includes the
following elements.
1. The keyword struct.
2. The structure tag name
3. List of structure variables (separated by commas)
4. A terminating semi colon.
Example:
Struct book_bank book1,book2,book3;
Declares book1, book2 and book3 as variables of type struct book_bank;
The use of tag is optional
struct
{
char title[10];
char author[10];
int pages;
float price;
}book1,book2,book3;
Structure Initialization
Example:
struct book_bank
{
char title[20];
char author[20];
int pages;
int price;
}book1={“Cprogramming”,”balaguruswamy”,100,200};
(OR)
Struct book_bank book1 ={“Cprogramming”,”balaguruswamy”,100,200};
Two variables of the same structure type can be copied the same way as ordinary
variables. If book1 and book2 belong to the same structure, then the following
statements are valid.
book2=book1
how ever the statement such as
book1 == book2 is invalid.
Note:
C does not permit any logical operations on structure variables. In case we need to
compare them, we may do so by comparing members individually.
Array of structures
For example in analyzing the marks obtained by a class of students, we may use a
template to describe student name and marks obtained in various subjects and then
declare all the students as structure variables.
In such cases, we may declare an array of structures, each element of the array
representing a structure variable.
e.g: struct class student[100];
defines an array called student, that consists of 100 students. Each element is
defined to be of the type struct class.
Consider the following declaration.
struct marks
{
int subject1;
int subject2;
int subject3;
};
Here the member subject contains three elements, subject[0], subject[1] and
subject[2]. These elements can be accessed using appropriate subscripts.
For example the name
Student[1].subject[2];
Would refer to the marks obtained in the third subject by the second student.
This structure defines name, department, basic pay and three kinds of allowances.
We can group all the items related to allowance together and declare them under a
substructure as shown below.
struct salary
{
char name[10];
char department;
struct
{
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}allowance;
}employee;
The salary structure contains a member named allowance, which itself is a structure
with three members. The members contained in the inner structure namely
dearness, house_rent, and city can be referred to as
Employee.allowance.dearness
Employee.allowance.house_rent
Employee.allowance.city
Note:
1. An inner-most member in a nested structure can be accessed by chaining all
the concerned structure variables with the member using dot operator.
There are three methods by which the values of a structure can be transferred from
one function to another.
1. The first method is to pass each member of the structure as an actual
argument of the function call. The actual arguments are then treated
independently like ordinary variables. This is the most elementary method and
becomes unmanageable and inefficient when the structure size is large.
2. The second method involves passing of a copy of the entire structure to the
called function. Since the function is working on a copy of the structure, any
changes to structure members within the function are not reflected in the
original structure. It is therefore necessary for the function to return the entire
structure back to the calling function, all compilers may not support this
method of passing the entire structure as a parameter.
3. The third approach employs a concept called pointers to pass the structure as
an argument. In this case, the address location of the structure is passed to
the called function. The function can access indirectly the entire structure and
work on it. This is similar to the way arrays are passed to function. This
method is more efficient as compared to the second one.
1. The called function must be declared for its type, appropriate to the data type
it is expected to return. For example if it is returning a copy of the entire
structure, then it must be declared as a struct with an appropriate tag name.
2. The structure variable used as the actual argument and the corresponding
formal argument in the called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some
data back to the calling function. The expression may be any simple variable
or structure variable or an expression using simple variables.
4. When a function returns a structure, it must be assigned to a structure of
identical type in the calling function.
5. The called functions must be declared in the calling function appropriately.
UNIONS
A union is a collection of different data types, in union all members share the same
memory location.
Union is a derived datatype.
Union is similar to structure, but the difference is in structure each member has its
own storage location, whereas all the members of a union use the same location.
Like structures, a union can be declared using the keyword union as follows.
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union item. The union contains three members,
each with a different data type. However, we can use only one of them at a time.
This is due to the fact that only one location is allocated for a union variable,
irrespective of its size.
The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
In the declaration above the member x requires 4 bytes which is the largest among
the members. The above figure shows how all the three variables share the same
address. This assumes that a float variable requires 4 bytes of storage.
Dot (.) operator is used to access a union member. Like
code.m
code.x
code.c
all are valid member variables. During accessing, we should make sure that we are
accessing the member whose value is currently stored.
e.g:
code.m = 379;
code.x=12.35;
printf(“%d”,code.m);
would produce erroneous output.
A union creates a storage location that can be used by any of its members at a time.
When a different member is assigned a new value, the new value supersedes the
previous member’s value.
Unions may be initialized when the variable is declared. But unlike structures, it can
be initialized only with a value of the same type as the first union member.
e.g:
union item abc = {100} is valid
union item abc = {10.5} is invalid, because the type of the first member is int. other
members can be initialized by either assigning values or reading from the keyboard.
sizeof()
sizeof operator tells the size of a structure or union.
Syntax: sizeof(union x);
Will evaluate the number of bytes required for union x.
Structure Programs
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&& !strcmp(book1.title,book2.title) &&
(book1.price==book2.price) && (book1.pages==book2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}
return 0;
}
4. Write a c program to illustrate array of structures
#include <stdio.h>
#include <stdlib.h>
struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {
5. Write a c program to calculate student total marks, subject’s total marks and
total marks using array of structures.
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {
sub1_total=0;
sub2_total=0;
sub3_total=0;
for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;
6. Write a c program to calculate student total marks, subject’s total marks and
total marks using array with in the structures
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {
for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;
#include <stdio.h>
#include <stdlib.h>
struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
}employee;
total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allowanc
e.CA;
printf("\n\n \t Emploee salary is:%d",total_salary);
}
8. Write a c program to pass a student structure to function and display structure
members in the function.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}
#include <stdio.h>
#include <stdlib.h>
struct complex
{
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}
#include <stdio.h>
#include <stdlib.h>
union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;
Programs
void fact();
int main(int argc, char *argv[]) {
fact();
return 0;
}
void fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
2. Write a c program to find factorial of a given number using functions with arguments
and no return type.
#include <stdio.h>
#include <stdlib.h>
void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);
return 0;
}
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
3. Write a c program to find factorial of a given number using functions with no
arguments and return type.
#include <stdio.h>
#include <stdlib.h>
int fact();
int main(int argc, char *argv[]) {
int f;
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
4. Write a c program to find factorial of a given number using functions with arguments
and return type.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
5. Write a c program to sort array elements using functions.
#include <stdio.h>
#include <stdlib.h>
void sort(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,i;
printf("\n Enter array lenth:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Before sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
sort(a,n);
printf("\n After sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
for(j=0;j<=(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
6. Write a c program to check whether given number is prime number or not using
functions.
#include <stdio.h>
#include <stdlib.h>
int prime(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=prime(n);
if(f==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}
int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
return count;
}
7. Write a c program to check whether the given number is a palindrome or not.
#include <stdio.h>
#include <stdlib.h>
int palindrome(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a value:");
scanf("%d",&n);
f=palindrome(n);
if(f==1)
{
printf("\n %d is a palindrome",n);
}
else
{
printf("\n %d is not a palindrome",n);
}
return 0;
}
int palindrome(int n)
{
int rev,rem,temp;
temp=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==temp)
{
return 1;
}
else
{
return 0;
}
}
8. Write a c program to swap two integers using call by value.
#include <stdio.h>
#include <stdlib.h>
void swap(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(a,b);
return 0;
}
void swap(int m,int n)
{
int temp;
temp=m;
m=n;
n=temp;
printf("\n After swapping a=%d b=%d\n",m,n);
}
9. Write a c program to swap two integers using call by reference.
#include <stdio.h>
#include <stdlib.h>
void swap(int*,int*);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(&a,&b);
printf("\n After swapping a=%d b=%d\n",a,b);
return 0;
}
void swap(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
10. Write a c program to find largest value from the given array elements using passing
array to the function.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause")
or input loop */
void largest(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,b,i;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest(a,n);
return 0;
}
void largest(int a[],int n)
{
int i,max;
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("\n largest number = %d",max);
}
11. Write a c program to implement Fibonacci series using functions.
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int n,f,i;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
f=fib(i);
printf("\n %d",f);
}
return 0;
}
int fib(int n)
{
int i,f0,f1,f2;
if(n==0||n==1)
{
return n;
}
else
{
f0=0;
f1=1;
for(i=2;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
}
return f2;
}
}
12. Write a c program to find sum of matrix elements using functions.
#include <stdio.h>
#include <stdlib.h>
void addition(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
addition(a,b,c,3,3);
printf("\n Matrix-C elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
void multiply(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],n,i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
multiply(a,b,c,3,3);
printf("\n Enter Matrix-C elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
}
int stringlength(char[]);
int main(int argc, char *argv[]) {
char str[10];
int l;
printf("\n Enter a string:");
gets(str);
l=stringlength(str);
printf("\n string length = %d\n",l);
return 0;
}
int stringlength(char str[])
{
int i;
for(i=0;str[i]!='\0';i++);
return i;
}
15. Write a c program to sort city names using functions.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
}
16. Write a c program to find Fibonacci series using recursion.
#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fib(n);
printf("\n fib(%d)=%d",n,f);
return 0;
}
int fib(int n)
{
if(n==0||n==1)
{
return n;
}
else
{
return fib(n-1)+fib(n-2);
}
}
17. Write a c program to find factorial of a given number using recursion.
#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
if(n==0||n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
18. Write a c program to find addition of the two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause")
or input loop */
int addition(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=addition(m,n);
printf("\n add(%d,%d)=%d",m,n,f);
return 0;
}
int addition(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return addition(m,n-1)+1;
}
}
19. Write a c program to find multiplication of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>
int multiply(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=multiply(m,n);
printf("\n mul(%d,%d)=%d",m,n,f);
return 0;
}
int multiply(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return multiply(m,n-1)+n;
}
}
20. Write a c program to implement binary search using recursion.
#include <stdio.h>
#include <stdlib.h>
void binarysearch(int[],int,int,int);
int main(int argc, char *argv[]) {
int a[10],n,i,key;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key:");
scanf("%d",&key);
binarysearch(a,0,n-1,key);
return 0;
}
void binarysearch(int a[],int l,int h,int k)
{
int mid;
if(l<=h)
{
mid=(l+h)/2;
if(a[mid]==k)
{
printf("\n Search is successful");
}
else if(k < a[mid])
{
binarysearch(a,l,mid-1,k);
}
else
{
binarysearch(a,mid+1,h,k);
}
}
else
{
printf("\n Search is unsuccessful");
}
}
21. Write a c program to find GCD of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=gcd(m,n);
printf("\n gcd(%d,%d)=%d",m,n,f);
return 0;
}
int gcd(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return gcd(n,m%n);
}
}
22. Write a c program to implement Ackermann function using recursion.
#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=ack(m,n);
printf("\n ack(%d,%d)=%d",m,n,f);
return 0;
}
int ack(int m,int n)
{
if(m==0)
{
return n+1;
}
else if((m>0)&&(n==0))
{
return ack(m-1,1);
}
else
{
return ack(m-1,ack(m,n-1));
}
}
23. Write a c program to create a structure named as Book, initialize structure members at
run time and display structure members.
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);*/
printf("\n Structure members are:\n");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}
24. Write a c program to create a structure named as Book, initialize structure members at
compile time and display structure members.
#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1={"Balaguruswamy","CProgramming",199.50,300
};
printf("\n Structure members are:");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}
25. Write a c program to illustrate copy and comparison of two structures variables.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&&
!strcmp(book1.title,book2.title)&&(book1.price==book2.price)&&(book1.pages==bo
ok2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}
return 0;
}
26. Write a c program to illustrate array of structures
#include <stdio.h>
#include <stdlib.h>
struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {
struct student std[3];
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].marks1,&std[i].marks2,&std[i].marks3);
}
printf("\n Structure members are:");
for(i=0;i<3;i++)
{
printf("\n %d student Marks are:",i+1);
printf("\t%d\t%d\t%d",std[i].marks1,std[i].marks2,std[i].marks3);
}
return 0;
}
27. Write a c program to calculate student total marks, subject’s total marks and total
marks using array of structures.
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {
struct student std[3];
int sub1_total,sub2_total,sub3_total;
int total_marks;
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].sub1,&std[i].sub2,&std[i].sub3);
}
sub1_total=0;
sub2_total=0;
sub3_total=0;
for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;
28. Write a c program to calculate student total marks, subject’s total marks and total
marks using array with in the structures
#include <stdio.h>
#include <stdlib.h>
struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {
struct student std[3];
int sub1_total,sub2_total,sub3_total;
int total_marks;
int i,j;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
for(j=0;j<3;j++)
{
scanf("%d",&std[i].sub[j]);
}
}
sub1_total=0;
sub2_total=0;
sub3_total=0;
for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;
struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
}employee;
total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allowance.
CA;
printf("\n\n \t Emploee salary is:%d",total_salary);
}
30. Write a c program to pass a student structure to function and display structure
members in the function.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}
struct complex
{
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}
union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;
struct student
{
char name[10];
int age;
};
Console I/O – it uses scanf() and printf() to read and write data. These functions always use
terminal (keyboard and screen) as the target place.
Drawbacks
1. It becomes cumbersome and time consuming to handle large volume of data through terminal.
2. The entire data is lost when either the program is terminated or the computer is turned off.
File – a file is a place on the disk where a group of related data is stored.
Types of Files:
There are two types of files, they are 1. Text files 2. Binary files
1. Text file:
Text file stores information in the form of alphabets, numbers, special symbols etc…
It requires conversion from text to binary format
This format is human understandable
C source files are text files
2. Binary File:
File Operations
Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file
If we want to store data in a file in the secondary memory we must specify three things to the
operating system. They are
File name
Data structure
Purpose
File name is a sequence of characters that make up a valid filename. It may contain two parts, a
primary name and an optional period with file extension.
Data structure of a file is defined as FILE, therefore all files should be declared as type FILE
before they are used.
For what purpose we open a file, whether the file is open for reading, writing or appending.
FILE *fp;
fp = fopen (“filename”,”mode”);
In the first statement fp as a “pointer to the data type FILE”, the second statement opens a file
named filename and assigns an identifier to the FILE type pointer fp.
CLOSING A FILE
A file must be closed after all operations have been completed.
Syntax:
fclose(file_pointer);
This would close the file associated with the FILE pointer file_pointer.
c= getc(fp1);
Read a character from the file whose file pointer is fp1 and store the character in c.
Putc():
It is used to write a character to a file.
The file must be opened in write mode.
Syntax
Putc(c,fp1);
Write the character contained in the character variable c to the file associated with FILE
pointer fp1.c and putc
Note:
1. The file pointer moves by one character position for every operation of getc and putc
2. getc will return and end-of-file marker EOF when end of the file has been reached.
1. Write a c program to write data to the input file after that read input file contents and
display on the screen.
#include <stdio.h>
#include <stdlib.h>
2. Write a c program to write characters to the input file, then read input file contents and
check if it is vowel then store it in VOWEL file, or it is a consonant then store it in
CONSONANT file. Display VOWEL files contents and CONSONANTS file contents.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
while((c=getc(fp))!=EOF)
{
if(isalpha(c))
{
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
putc(c,fp1);
}
else
{
putc(c,fp2);
fp1=fopen("vowel.txt","r");
printf("\n Vowe file contents are:");
while((c=getc(fp1))!=EOF)
{
printf("%c",c);
}
fclose(fp1);
fp2=fopen("consonant.txt","r");
printf("\n Consonant file contents are:");
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}
getw():
It is used to read an integer from a file.
The file must be opened in read mode.
Syntax
c= getw(fp);
putw():
It is used to write an integer to a file.
The file must be opened in write mode.
Syntax
putw(c,fp);
The variable c contains an integer that value writes into a file pointed by a file pointer fp.
3. Write a c program to write integers to NUMBER file. Read an integer value from
NUMBER file and display integers on the screen.
#include <stdio.h>
#include <stdlib.h>
fp=fopen("number.txt","r");
while((n=getw(fp))!=EOF)
{
printf("\n%d",n);
}
fclose(fp);
return 0;
}
4. Write a c program to write integers to the NUMBER file. Read numbers from the
NUMBER file check that number if it is even then stores it in EVEN file otherwise store
it in ODD file. Display EVEN file contents and ODD file contents on the screen.
#include <stdio.h>
#include <stdlib.h>
fp=fopen("number.txt ","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((n=getw(fp))!=EOF)
{
if(n%2==0)
{
putw(n,fp1);
}
else
{
putw(n,fp2);
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
printf("\n Even file contents are:");
while((n=getw(fp1))!=EOF)
{
printf("\n%d",n);
}
fclose(fp1);
fp2=fopen("odd.txt","r");
printf("\n Odd file contents are:");
while((n=getw(fp2))!=EOF)
{
printf("\n%d",n);
}
fclose(fp2);
return 0;
}
The above statement will read the items in the list from the file specified by fp.
fprintf()
It is used to write the list of items into a file
Syntax
fprintf(fp, ”control string “, list);
The above statement would write the items in the list into a file specified by fp.
1. Write a c program to open a file named inventory and store it in following data.
Item name item number price quantity
Aaa 111 10 2
Bbb 222 15 3
Ccc 333 12 5
Extend the program to read this data from the file inventory and display the table with
values of each item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
fp=fopen("inventory.txt","w");
i=1;
while(i<=3)
{
printf("\n Enter item name:");
scanf("%s",name);
printf("\n Enter item number:");
scanf("%d",&number);
printf("\n Enter price:");
scanf("%f",&price);
printf("\n Enter quantity:");
C provides two library functions to provide file status information. They are feof() and ferror()
1. feof( ): it takes file pointer as the argument and return a nonzero integer if all of the data
from the specified file has been read and returns zero otherwise.
Syntax:
if(feof(fp))
{
Printf(“End-of-data\n”);
}
would display the message “End-of-data” on reaching the end of file condition.
2. ferror( ): It takes the file pointer as an argument and returns a nonzero integer if an error has
been detected up to that point during processing. It returns zero otherwise.
if(ferror(fp) != 0)
printf(“An error has occurred \n”);
3. Clearerr( ) – clears the EOF and error indicator for the given stream.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("ece2.txt","w");
c=getc(fp);
if(ferror(fp))
{
printf("\n error in reading file \n");
}
clearerr(fp);
if(ferror(fp))
{
printf("error in reading from file : file.txt\n");
}
fclose(fp);
}
2. rewind( ): takes file pointer as an argument and resets the position to the start of the file.
rewind(fp);
n=ftell(fp);
would assign 0 to the n because the file position has been set to the start of the file by rewind.
3. fseek( ): It is used to move the file position to the desired position in the file.
Syntax:
Value Meaning
0 Beginning of the file
1 Current position
2 End of file
The offset may be positive meaning move forwards, or negative meaning move backwards.
Statement Meaning
fseek(fp,0L,0) go to the beginning
fseek(fp,0L,1) stay at the current position
fseek(fp,0L,2) go to the end of the file, past the last character of the file
fseek(fp,m,0) move to the (m+1)th byte in the file
fseek(fp,m,1) go forward by m bytes
fseek(fp,-m,1) go backward by m bytes from the current position
fseek(fp,-m,2) go backward by m bytes from the end
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,n;
clrscr();
fp=fopen("xyz.txt","w");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen("xyz.txt","r");
fseek(fp,0L,2);
n=ftell(fp);
printf("\n No of characters are = %d\n",n);
for(i=n;i>=0;i--)
{
fseek(fp,i,0);
ch=getc(fp);
#include <stdio.h>
#include <stdlib.h>
FILE *fp;
char ch;
int i,n;
fp=fopen("xyz.txt","w");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen("xyz.txt","r");
fseek(fp,6L,0);
ch=getc(fp);
printf("\n 6th character is = %c\n",ch);
fseek(fp,8L,0);
ch=getc(fp);
printf("\n 8th character is = %c\n",ch);
fclose(fp);
return 0;
}
A read operation reads the structure where the file position indicator is pointing to. After
reading the structure the pointer is moved to point at the next structure.
A write operation will write to the currently pointed-to structure. After the write operation the
file position indicator is moved to point at the next structure.
A memory address
Number of bytes to read per block
Number of blocks to read
A file variable
fread(&my_record,sizeof(struct rec),1,file_pointer);
This fread statement says to read x bytes (size of rec) from the file file_pointer into memory
address &my_record. Only one block is requested. Changing the one into ten will read in ten
blocks of x bytes at once.
fwrite(&my_record,sizeof(struct rec),1,file_pointer)
This fwrite statement says to write x bytes (size of rec) from the my record into the file
pointed by the file pointer.
Write a C program to write data from the file using binary file concept
#include<stdio.h>
#include<conio.h>
struct rec
{
int x,y,z;
};
void main()
{
struct rec a;
Where PROGRAM is the filename where the executable code of the program is stored. This
eliminates the need for the program to request the user to enter the filenames during execution.
Main takes two arguments called argc and argv and the information contained in the command
line is passed on to the program through these arguments, when main is called up by the system.
/* run this program using the console pauser or add your own getch, system("pause") or
input loop */
/* run this program using the console pauser or add your own getch, system("pause") or
input loop */
/* run this program using the console pauser or add your own getch, system("pause") or
input loop */
4. Write a C program to copy one file contents into another file using command line
arguments.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or
input loop */
while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);
fp2=fopen(argv[2],"r");
printf("\n %s file contents are \n",argv[2]);
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}