Module 2 (Proc)
Module 2 (Proc)
It
Do-While loop
Syntax :
do
{
statement 1; }
statement 2; } Body of the loop
..... }
.....
......
statement n;
}
while ( test-condition );
statement X;
#include<stdio.h>
main()
{
int i=1,n,sum=0;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
do
{
sum=sum+i;
i++;
} while ( i <= n );
printf(“Sum of 1 to N numbers=%d”,sum);
}
Example 3: Find whether the given number is palindrome or not.
#include<stdio.h>
main( )
{
int i, num, rev=0, digit, temp;
printf(“Enter the number \n”);
scanf(“%d”, &num);
temp=num;
do
{
digit = num % 10;
rev = rev * 10 + digit ;
num = num / 10;
} while ( num !=0 );
if ( rev == temp )
printf(“The given number is palindrome \n”);
else
printf(“The given number is not palindrome \n”);
}
#include <stdio.h>
main()
{
int i=1,n,f1=0,f2=1,f3;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
printf(“%d%d”,f1,f2);
do
{
f3 = f1 + f2;
printf ( “ %d”, f3);
f1 = f2;
f2 = f3;
i++;
} while (i<=n);
}
Difference between while and do-while loops:
Syntax:
for (initialization; test-condition; increment or decrement)
{
…
… // Body of the loop
}
Example code 1 :
for( i=1; i<=10; i++)
{
printf(“%d”, i);
}
2. The value of the control variable is tested using the test-condition. The
test-condition is a relational expression , such as i<10 that determines
when the loop will exit. If the condition is true, the body of the loop is
executed, otherwise the loop is terminated and the execution continues
with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back
to the for statement after evaluating the last statement in the [Link]
the control variable is incremented using an assignment statement such
as i++ and the new value of the control variable is again tested ,
whether it satisfies the loop condition. If the condition is satisfied, the
body of the loop is again executed. This process continues till the value
of the control variable fails to satisfy the condition .
Example code 2 :
This loop is executed 10 times and prints the digits from 0 to 9 in one line.
Another unique aspect of for loop is that one or more sections can be
omitted, if necessary.
Consider the following example:
m = 5;
for ( ; m!= 100 ; )
{
printf(“%d \n”, m);
m = m+5;
}
Example 1:
Calculate the sum of all numbers from 1 to N using a for loop.
#include<stdio.h>
main( )
{
Int i,n,sum=0;
printf(“Enter the value of n \n”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
sum = sum + i;
}
printf (“Sum = %d”,sum);
}
Example 2:
Program to generate a multiplication table using for loop.
#include<sdtio.h>
main( )
{
int i,n,p;
printf(“Enter the table number \n”);
scanf(“%d”, &n);
for(i=1; i<=10; i++)
{
p = n * i;
printf(“%d * %d = %d”, n, i, p);
}
}
Module-III
ARRAYS
An array is a group of related data items that share a common name. I.e it is
a collection of homogeneous data items.
One-dimensional array:
A list of items can be given one variable name using only one subscript.
The subscript can begin with number 0.
int x[5];
means x[0], x[1], x[2], x[3], x[4];
If, we want to represent a set of five numbers say [10,20,30,40,50), by an
array variable num, then we may declare the variable num as follows:
int num[5];
The computer reserves five storage locations as follows :
10
20
30
40
50
Initialization of Arrays:
1) Compile time initializationb sh
2) Run time initialization
Example 1 :
Program to read and print a set of integer numbers using arrays.
#include<stdio.h>
main( )
{
Int i,n,a[10];
printf(“Enter the size of an array \n”);
scanf(“%d”, &n); // if, n=5
printf(“enter the elements of array \n”):
for(i=1; i<=n; i++)
{
scanf (“%d”, &a[i]); // 5 elements have be entered
}
printf(“ Array elements are \n”);
for (i=1; i<=n; i++)
{
printf (“%d \n”, a[i]); // It will print all the array elements
}
}
Output:
#include<stdio.h>
main( )
{
int i, n, sum=0, a[10];
printf(“Enter the size of an array \n”);
scanf(“%d”, &n); // if, n=4
printf(“enter the elements of array \n”):
for(i=1; i<=n; i++)
{
scanf (“%d”, &a[i]); // 4 elements have be entered
}
printf(“ Sum of array elements is \n”);
for (i=1; i<=n; i++)
{
sum= sum+a[i]; // It will add all array elements
}
printf (“%d”, sum);
}
Output:
Create an array of integers. Search a given element from the array and change the
existing number by the given number.
#include<stdio.h>
main( )
{
int i, n, a[10], key, new;
printf ("Enter the size of an array \n" );
scanf("%d", &n);
printf("Enter the elements\n");
for(i=1;i<=n;i++)
{
scanf("%d", &a[i]);
}
printf ("The given array is \n");
for(i=1;i<=n;i++)
{
printf("%d ", a[i]);
}
printf("Enter the number to be searched \n");
scanf("%d", &key);
for(i=1;i<=n;i++)
{
if(key == a[i])
{
printf("Enter a new element\n");
scanf("%d",&new);
a[i]=new;
}
}
printf ("The key element is replaced by new element\n");
for(i=1;i<=n;i++)
{
printf("%d ", a[i]);
}
}
Example 5: Lab program
Program to print a pascal triangle.
#include<stdio.h>
main()
{
int rows, value=1, i, j, k;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=0; i<rows; i++)
{
for (j=1; j<rows-i; j++)
printf(" ");
for (k=0; k<=i; k++)
{
if (k==0 || i==0)
value = 1;
else
value=value*(i-k+1)/k;
printf("%4d", value);
}
printf("\n");
}
}
Example 6: Lab program
#include <math.h>
#define MAX 10
main()
{
int i, n, a[MAX];
float avg, var, sd, deviation, sum=0, sumsqr =0;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d real numbers\n",n);
for(i=1; i<=n; i++)
{
scanf("%d", &a[i]);
}
Example 7:
Program to sort a list of elements using arrays.
#include<stdio.h>
main( )
{
Int i,j,n,a[50];
printf( “Enter the size of an array \n”);
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for(i=1; i<=n; i++)
scanf(“%d”,&a[i]);
for(i=1;i<=n-1;i++)
{
for(j=1; j<=n-1; j++)
{
If ( a[j] <= a[ j+1] ) // comparing each element in an array
{
t= a[j];
a[j] = a[j+1];
a[j+1]= t;
}
}
}
Syntax:
datatype array_name [row_size] [column_size];
In this above example a is an array name with three rows and three columns.
We can also write a two dimensional array in the form of a matrix as shown
below.
Example 2:
Program to calculate sum of all the elements in a given matrix.
#include<stdio.h>
main( )
{
Int i, j, m, n, a[5][5],sum=0;
printf( “Enter the size of the matrix \n”);
scanf(“%d %d”,&m,&n);
printf(“Enter the elements\n”);
for ( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=m; i++ )
{
for( j=1; j<=n; j++ )
{
sum = sum +a[i][j];
}
}
printf(“SUM = %d”, sum);
}
Example 3:
Program to find the sum of diagonal elements in a given matrix.
#include<stdio.h>
main( )
{
Int i, j, n, a[5][5],sum=0;
printf( “Enter the size of the matrix \n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for ( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
If ( i == j) // Row number equal to Column
number
sum = sum +a[i][j];
}
}
printf(“Sum of diagonal elements = %d”, sum);
}
Example 4: Program to print Upper triangle and Lower triangle from a given matrix.
#include<stdio.h>
main( )
{
int i, j, n, a[5][5] ;
printf( “Enter the size of the matrix \n”);
scanf(“%d”, &n);
printf(“Enter the elements \n”);
for ( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
scanf (“%d”, &a[i] [j] );
}
}
for( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
if ( i != j) // Row number is not equal to Column number
printf(“%d ”, a[i][j]);
}
printf(“\n”);
}
}
#include<stdio.h>
int main ( )
{
int m, n, p, q, i, j, k, A[10][10], B[10][10],C[10][10] ;
printf ("Enter number of rows and columns of first matrix (less than 10) \n");
scanf ("%d %d", &m, &n);
printf ("Enter number of rows and columns of second matrix (less than 10) \n");
scanf ("%d %d", &p, &q);
if (p==n)
{
printf ("Enter the elements of First matrix \n");
for (i=1; i<=m;i++)
for (j=1; j<=n;j++)
scanf ("%d",&A[i][j]);
printf ("First Matrix is: \n");
for (i=1; i<=m;i++)
{
for (j=1; j<=n;j++)
{
printf ("%d\t",A[i][j]);
}
printf ("\n");
}
printf ("Enter the elements of Second matrix \n");
for (i=1; i<=p;i++)
for (j=1; j<=q;j++)
scanf ("%d", &B[i][j]);
printf ("Second Matrix is: \n");
for (i=1; i<=p; i++)
{
for (j=1; j<=q; j++)
{
printf ("%d\t",B[i][j]);
}
printf ("\n");
}
for (i=1; i<=m; i++)
{
for (j=1; j<=q; j++)
{
C[i][j] = 0;
for (k=1; k<=m; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
printf ("The product of matrix A & B: \n");
for (i=1; i<=m; i++)
{
for (j=1; j<=q; j++)
{
printf ("%d\t",C[i][j]);
}
printf ("\n");
}
}
else
{
printf ("Matrix multiplication cannot be done");
} }
STRING handling functions
A String is an array of characters. Any group of characters defined between
double quotation marks is a constant string.
Example : “Computer Science”.
#include<stdio.h>
#include<string.h>
main()
{
char w1[10],w2[10] ;
printf(“Enter the text \n”);
scanf(“%s %s”, w1,w2);
printf(“\n”);
printf(“Word1 = %s”, w1);
printf(“Word2 = %s”, w2);
}
#include<stdio.h>
#include<string.h>
main( )
{
char line[80], character ;
int c = 0;
printf(“Enter the text \n”);
do
{
character = getchar();
line[c] = character;
c++;
}
while (character != ‘\n’);
c = c-1;
line[c] =’\0’;
printf(“ \n %s\n”, line);
}
Example 3: Write a program to print our country name in different formats.
#include<stdio.h>
#include<string.h>
main( )
{
static char country[5] = "INDIA";
printf("%s\n",country);
printf("%-5.3s\n",country);
printf("%5.2s\n",country);
printf("%-5.0s\n",country);
printf("%.4s\n",country);
}
Output:
INDIA
IND
IN
INDI
Example 4: Develop a C program to convert from upper case to lower case letters
using string functions.
#include<stdio.h>
#include<string.h>
int main()
{
char a[25];
int i, j=0;
printf("Enter the string \n");
gets(a);
for(i=0; a[i] != '\0'; i++)
{
j=j+1;
}
for(i=0; i<=j; i++)
{
if(a[i] >= 65 && a[i] <= 90)
{
a[i] = a[i] + 32;
}
else
if (a[i] >= 97 && a[i] <= 122)
{
a[i] = a[i] - 32;
}
}
puts(a);
}
Output:
The C language allows us to manipulate characters the same way we do with numbers.
Whenever a character constant or character variable is used in an expression, it is
automatically converted into an integer value by the system. The integer value depends on
the local character set of the system.
It will display the number 97on the screen. (97 is the ASCII value of a ).
x = ‘z’-1;
printf(“%d”,x);
A 65 a 97
B 66 b 98
.. .. .. ..
Z 97 z 122
Blank space 32
The C library supports a function that converts a string of digits into their integer
values. The function takes the form as follows:
x = atoi(string)
number =”2020”;
year = atoi(number);
Function Action
strcat( ) Concatenates two strings
Example :
S1 =
V E R Y \0
S2 =
G O O D \0
: strcat (S1,S2) ;
S1 =
V E R Y G O O D \0
S2 =
G O O D \0
strcat (strcat(string1,string2),string3);
➢ strcmp( ) function :
The strcmp function compares two strings identified by the arguments and has a
value 0 if they are equal. If they are not, it has the numeric difference between the
first non- matching characters in the strings.
strcmp (name1,name2);
strcmp(name1,”John”);
strcmp(“Ram”, “Rahim”);
Example :
x = strcmp(“PDA”,”PDA”);
It returns value zero, because both strings are equal.
x= strcmp(“their”,”there”);
It returns a value -9 which is the numerical difference between ASCII “i” and
ASCII “r”. That is, “i” minus “r” in ASCII code is -9.
➢ strcpy( ) function :
The strcpy function works almost like a string-assignment operator. It assigns the
contents of string2 to string1, string2 may be a character array variable or a string
constant.
Example : strcpy(city,”DELHI”);
➢ strlen() function:
The function counts and returns the number of characters in a string.
n = strlen(string);
Where n is an integer variable which receives the value of the length of the
string.
Example: n= strlen(“Professor”);
It returns the value 9.
Module-IV
USER-DEFINED FUNCTIONS
C functions can be classified into as two categories:
1. Library functions
2. User-Defined functions.
printf(), scanf(), sqrt(), strcat() etc are the examples of library functions.
main() is the user defined function.
If a program is divided into functional parts, then each part may be independently coded
and later combined into a single unit. These subprograms are called “functions”.
Calling a function :
Example:
main()
{
int p;
p = mult(10,5);
printf(“%d”, p);
}
Here, mult is the function name and 10,5 are the arguments.
CATEGORY OF FUNCTIONS:
No arguments
Calling Called
Function Function
(main/UDF) (UDF)
No return value
When a function has no arguments, it does not receive any data from the
calling function. Similarly, when it does not return a value, the calling function
does not receive any data from the called [Link] is no data transfer
between the calling and called function.
Example:
Program to calculate simple interest using first category function.
#include<stdio.h>
main()
{
simple_interest();
}
simple_interest()
{
int p,t,r;
float si;
printf(“enter the p,t,r values \n”);
scanf(“%d %d %d”, &p,&t,&r);
si = (p * t * r)/100;
printf(“Simple Interest = %f”, si);
}
Values of arguments
Calling
Function Called
(main/ Function
UDF) (UDF)
No return value
#include<stdio.h>
main()
{
int p,t,r;
printf("Enter the values of p,t,r \n");
scanf("%d%d%d", &p,&t,&r);
simple_interest(p,t,r);
}
simple_interest(p,t,r)
int p,t,r;
{
float si;
si = (p * t * r)/100;
printf("Simple Interest = %f", si);
}
Calling Called
function function
(main/UDF) (UDF)
With return values
In this 3rd category function, data will pass through the calling function to the
called function. The called function simply receives the data, calculates the
result and sends the value to the main function. i.e., reading the data and
printing the result will be performed by the main function.
Example :
Program to calculate simple interest using with arguments and with
return value( 3rd category function).
#include<stdio.h>
main()
{
int p,t,r;
float si;
printf("Enter the values of p,t,r \n");
scanf("%d%d%d", &p,&t,&r);
si= simple_interest(p,t,r);
printf("Simple Interest = %f", si);
}
simple_interest(p,t,r)
int p,t,r;
{
float si;
si = (p * t * r)/100;
return(si);
}
● Function with Multiple return values:
This category of function is also the same as the 3rd category function, but
with multiple return values. In this type data is supplied by the main function
and the result will be printed in the main function itself. The sub function only
perform the calculation and returns the values to the main.
#include <stdio.h>
int main()
{
int a,b,big;
scanf("%d%d",&a,&b);
big=large(a,b);
printf("Largest = %d",big);
}
large(a,b)
int a,b;
{
if(a>b)
return(a);
else
return(b);
}
Recursion:
When a called function in turn calls another function a process of
“chaining” occurs. Recursion is a special case process of calling the
function, where the function calls itself.
Example:
main( )
{
printf(“ Welcome to Recursion \n”);
main( );
}
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Recursion
Welcome to Re…..
….
….
#include<stdio.h>
main( )
{
int num,fact;
int factorial(int n);
printf(“Enter the number\n”);
scanf(“%d”,&num);
fact=factorial(num); // function name with one parameter
printf(“Factorial = %d”, fact);
}
int factorial(int n) // called function
{
int f;
if(n == 0)
return(1);
else
f = n * factorial(n-1); // The function calls itself
return(f);
}
Structures:
The ‘C’ language supports a constructed data type known as
structure,which is a method for packing data of different types. A
structure is a convenient tool for handling a group of logically related
data items. It is a collection of heterogeneous data items which
share a common name.
Syntax :
struct tag_name
{
datatype member1;
datatype member2;
...
...
...
};
Example :
struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four fields,
namely title,author,pages,price. These fields are called structure
elements or members. Each member may belong to a different type of
data. book_bank is the name of the structure or tag name.
We can declare structure variables using the tag name anywhere in the
program.
struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
};
struct book_bank book1, book2, book3;
struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
} book1, book2, book3;
struct
{
…….
…….
……
} book1, book2, book3;
The word title has no meaning whereas the phrase ”title of book3” has a
meaning. The link between a member and a variable is established using the
member operator ‘.’ which is also known as ‘dot operator’ or ‘period operator’.
Example: [Link]
It is the variable representing the price of book1 and can be treated like any
other ordinary variable.
strcpy([Link], “BASIC”);
strcopy([Link], “ Balaguruswamy”);
[Link] = 250;
[Link] = 500.25;
We can also use scanf statement to give the values through the keyboard.
The following are the valid input statements.
scanf(“%s”, [Link]);
scanf(“%s”, [Link]);
scanf(“%d”, &[Link]);
scanf(“%f”, &[Link]);
Structure initialization:
Like any other data type structure variable can be initialized.
Example:
main( )
{
static struct
{
int weight;
float height;
}
student = {62, 180.25};
…..
…..
}
main( )
{
struct st_record
{
int weight;
float height;
};
struct st_record student1 = {62, 180.25};
struct st_record student2 = {70, 185.75};
}
Comparison of structure variables:
Two variables of the same structure type can be compared the same
way as ordinary variables.
If person1 and person2 belong to the same structure , then the
following operations are valid.
Operation Meaning
Understanding Pointers:
Memory organization :
quantity Variable
250 Value
5000 Address
During the execution of the program the system always associates the name
quantity with the address 5000. We have access to the value 250 by using
either the name quantity or the address 5000. Since memory addresses are
simply numbers, they can be assigned to some variables which can be stored
in memory, like any other variable. Such variables that hold memory
addresses are called pointers.
Variable Value Address
Quantity
250 5000
p 5000 5048
Since 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 ‘pointes’ to the variable quantity. Thus , p gets the
name pointer.
Example: p = &quantity;
Would assign the address 5000 to the variable p. The & operator can be used
only with a simple variable or an array element.
#include <stdio.h>
main( )
{
char a;
int x;
float p;
a= ‘A’;
x=125;
p=10.25;
printf(“%c is stored at address %u=”, a, &a);
printf(“%d is stored at address %u=”, x, &x);
printf(“%f is stored at address %u=”, p, &p);
}
Where,
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. Pt_name needs a memory location.
3. Pt_name points to a variable of type data type.
Examples:
int *p;
Declares the variable p as a pointer variable that points to an integer
datatype.
float *x;
Declares x as a pointer to a floating point variable.
quantity = 250;
p = &quantity;
n = *p;
Pointer expressions:
Pointer variables can be used in expressions.
For example, if p1 and p2 are properly declared and initialized pointers,
then the following statements are valid.
y = *p1 * *p2; same as (*p1) * (*p2)
sum = sum + *p1;
z = *p2 / *p1;
*p2 = *p2 + 10;
Note that there is a blank space between / and * in the third item above.
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 incremented by the length of the data type
that it points to. This length is called the scale factor.
The lengths of various data type as follows:
character 1 byte
integer 2 byte
floats 4 bytes
long integers 4 bytes
double 8 bytes
Base Address
The name x is defined as a constant pointer to the first element, x[0] and
therefore the value of x is 1000 , the location where x[0] is stored.
i.e., x = &x[0] = 1000
If we declare p as an pointer, then we can make the pointer p to point to the
array x by the following assignment:
p = x;
This is equal to p = &x[0];
Now, we can access every value of x using p++ to move from one element to
another.
p = &x[0] = 1000
p+1 = &x[1] = 1002
p+2 = &x[2] = 1004
p+3 = &x[3] = 1006
p+4 = &x[4] = 1008
Example 2:
Develop a program to compute the sum of all the elements stored in an array using
pointers.
#include<stdio.h>
main( )
{
Int i, sum=0, *p;;
static int x[5] = {11,22,33,44,55};
p = x;
printf(“Element Value Address \n”);
for(i =0; i<5; i++)
{
printf (“ x[%d] %d %u \n”, i, *p, p);
sum = sum +*p;
p++;
}
printf(“\n Sum = %d\n” ,sum);
printf(“\n &x[0] = %u\n”,&x[0]);
printf(“\n p = %u\n”,p);
}
Pointers and character strings:
As we know string is an array of characters, terminated with a null character.
We can use a pointer to access the individual characters in a string.
Example 3 :
Program to determine the length of a character string using pointers.
#include <stdio.h>
#include<string.h>
main()
{
char *name;
Int length;
char *cptr = name;
name = “DELHI”;
while (*cptr != 0)
{
printf(“%c is stored at address %u \n”, *cptr, cptr);
cptr++;
}
length= cptr - name;
printf(“\n Length of the string = %d”, length);
}
Pointers to Functions:
A function, like a variable, has an address location in the memory. It is
therefore possible to declare a pointer to function, which can be 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 parentheses around *fptr are necessary.
Pointer and Structures:
The whole structure can be used for array variables with pointer.
Example:
struct inventory
{
char name[20];
int number;
float price;
} product[2], *ptr;
This statement declares the product as an array of two elements, each of the
type struct inventory and ptr as a pointer to data objects of the type struct
inventory.
ptr = product;
would assign the address of the zeroth element of the product to ptr. i.e. the
pointer ptr will now point to product[0]. Its members can be accessed using
the following notation.
ptr -> name;
ptr -> number
ptr -> price
The symbol -> is called the arrow operator and is made up of a minus sign
and a greater than sign.
When the pointer ptr is incremented by one, it is made to point to the next
record, i.e product[1]. The following for statement will print the values of
members of all the elements of the product array.
printf(“%s %d %f \n”, ptr name, ptr -> number, ptr -> price);
We would also use the notation (*ptr).number to access the member
number. The parentheses around *ptr are necessary because the member
operator “.” has a higher precedence than the operator *.
FILE MANAGEMENT IN C
The I/O functions which always use the terminal as the target place. This
works fine as long as the data is small. However , many real-life problems
involve large volumes of data and in such situations, the I/O operations pose
two problems.
1. It becomes cumbersome and time consuming to handle large volumes
of data through terminals.
2. The entire data is lost when either the program is terminated or the
computer is turned off.
It is therefore necessary to have a more flexible approach where data
can be stored on the disks and read whenever necessary, without
destroying the data. This method employs the concept of files to store
data. A file is a place on the disk where a group of related data is
stored. ‘C’ language supports a number of functions that have the ability
to perform basic file operations, which include:
➢ Naming a file
➢ Opening a file
➢ Reading data from a file
➢ Writing data to a file
➢ Closing a file
The file data is opened for reading and results is opened for writing.
Many recent compilers include additional modes of operations such as :
r+ the existing file is opened to the beginning for both reading and writing.
w+ same as w except both for reading and writing
a+ same as a except both for reading and writing .
CLOSING A FILE:
Syntax:
fclose(file_pointer);
This would close the file associated with the FILE pointer file_pointer.
This program opens two files and closes them after all operations on them
are completed. Once the file is closed, its file pointer can be reused for
another file.
Similarly, getc is used to read a character from a file that has been opened in
read mode.
c = getc(fp2);
would read a character from the file whose file pointer is fp2.
The file pointer moves by one character position for every operation of getc or
putc. The getc will return an end-of-file marker EOF, when the end of the file
has been reached. Therefore, the reading should be terminated when EOF is
encountered.
#include< stdio.h>
main( )
{
FILE *f1;
char c;
printf( “Data input \n”);
f1 = fopen(“INPUT”, ”w”);
while ((c= getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf(“Data output\n”);
f1= fopen(“INPUT”,”r”);
while((c=getc(f1)) !=EOF)
printf(“%c”,c);
fclose(f1);
}
The getw and putw functions:
The getw and putw are integer-oriented functions. They are similar to the getc
and putc functions and are used to read and write only integer values.
putw(integer,fp);
getw(fp);
#include< stdio.h>
main( )
{
FILE *f1, *f2, *f3 ;
int number;
printf( “Contents of DATA file \n”);
f1 = fopen(“DATA”, ”w”);
for(i=1; i<=50; i++)
{
scanf(“%d”, &number);
If ( number == -1) break;
putw(number, f1);
}
fclose(f1);
f1 = fopen(“DATA”, “r”);
f2=fopen(“ODD”, “w”);
f3=fopen(“EVEN”, “w”);
while(number = getw(f1)) != EOF)
{
If (number % 2 == 0)
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
fclose(f2);
fclose(f3);
}
The fprintf and fscanf functions:
So far, we have seen functions which can handle only one character or
integer at a time.
The functions fprintf and fscanf perform I/O operations that are identical to
the printf and scanf functions, except of course that work on files.
Where fp is the file pointer associated with a file that has been opened for
writing. The control string contains output specifications for the items in the
list. The list may include variables, constants and strings.
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity;
float price, value;
char item[10], filename[10];
printf(“Input file name\n”);
scanf(“%s”, filename);
fp=fopen(filename,”w”);
printf(“Input Inventory Data\n”);
printf(“Item Name Number Price Quantity \n”);
for(i=1; i<=3; i++)
{
fscanf(stdin,”%s%d%f %d”, item, &number, &price, &quantity);
fprintf(fp, “%s %d %f %d”, item, number, price, quantity);
}
fclose(fp);
fprintf(stdout, “\n”);
fp=fopen(filename, “r”);
printf(“Item Name Number Price Quantity Value \
n”);
for(i=1; i<=3; i++)
{
fscanf(fp, ”%s %d %f %d”, item, &number, &price, &quantity);
value=price * quantity;
fprintf(stdout,“%s %d %f %d %f”, item,number,price,quantity,
value);
}
fclose(fp);
}
ERROR HANDLING DURING I/O OPERATIONS:
If we fail to check such read and write errors, a program may behave
abnormally when an error occurs.
We have two status-inquiry library functions, feof and ferror that can help us
detect I/O errors in the files.
The feof function can be used to test for end-of-file condition. It takes a FILE
pointer as its only argument and returns a nonzero integer value if all of the
data from the specified file has been read, and returns zero otherwise.
If fp is a pointer to file that has just been opened for reading then the
statement:
if(feof(fp))
printf(“End of data \n”);
would display the message , “End of data” on reaching the end of the file
condition.
The ferror function reports the status of the file indicated. It also takes a FILE
pointer as its argument and returns a nonzero integer if an error has been
detected upto that point during processing. It returns zero otherwise.
The statement:
if(ferror(fp) !=0)
printf(“An error has occurred. \n”);
Would print the error message, if the reading is not successful.
We know that whenever a file is opened using the fopen function, a file
pointer is returned. If the file cannot be opened for some reason, then the
function returns a null pointer. This facility can be used to test whether a file
has been opened or not.
if(fp == NULL)
printf(“File could not be opened \n”);
#include<stdio.h>
main()
{
char *fiilename;
FILE *fp1, *fp2;
int i,number;
fp1 = fopen(“TEST”,”w”);
for(i=10; i<=100; i+=10)
putw(i, fp1);
fclose(fp1);
So far we have seen file functions that are useful for reading and writing data
sequentially. There are occasions, however, when we are interested in
accessing only a particular part of a file and not in reading the other parts.
This can be achieved with the help of the functions fseek, ftell and rewind
available in the I/O library.
➢ ftell takes a file pointer and returns a number of type long, that
corresponds to the current position. This function is useful in saving the
current position of a file.
n = ftell(fp);
n would give the relative offset (in bytes) of the current position.
➢ rewind takes a file pointer and resets the position to the starting of the
file.
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to the start of
the file by rewind.
Value Meaning
0 Beginning of file
1 Current position
2 End of file