Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Programming C

The document discusses different types of control flow statements in C programming including if-else statements, loops, and jumping statements. It provides examples and explanations of for, while, do-while loops as well as break, continue, and goto statements.

Uploaded by

amrit saud
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Programming C

The document discusses different types of control flow statements in C programming including if-else statements, loops, and jumping statements. It provides examples and explanations of for, while, do-while loops as well as break, continue, and goto statements.

Uploaded by

amrit saud
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

iv.

Nested if-else statement:


An entire if-else statement written within
the body of ‘if’ part or ‘else’ part of another
if-else statement is called nested if-else
statement.
Syntax:
if (condition 1)
{
if(condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
Q. WAP that takes marks of five subjects and
calculate total marks and percentage and
division on the basis of following criteria:
Percentage Division
p>=75 and p<=100 Distinction
p>=60 and p<75 First Division
p>=40 and p<60 Second Division
p>=30 and p<40 Third Division
Otherwise Fail
(Hint: Pass mark and full marks for each
subject are 30 and 100 respectively)

Home work:
Q. WAP to accept any number then display
even or odd.
Q. WAP to input marks of any subject then
display pass or fail.
Q. WAP to input a year then display the year
is leap year or not.
Q. WAP to find whether the given number is
divisible by 5 or not.
Q. WAP to identify any number entered
through keyboard then display whether it lies
between 200 and 300 or not.

 Ternary operator (? : )
Ternary operator is also known as
conditional operator as it checks
condition to make decision. This is the
only operator used in C that takes
three operands so it is named as
ternary operator.
Syntax:
Condition? Statement 1: statement 2;

(Note: Condition is checked and if it is


found true then statement 1 is
executed otherwise statement 2 is
executed which is similar to the
working style of if-else statement.)

Q. WAP to read two integer values and


display the largest value using ternary
operator.
b) Switch case statement:
C switch statement is a multipath decision
making statement. The same task can be
performed using if-else ladder. The switch
statement body consists of a series of case
labels and optional default label.
Syntax:
Switch (expression)
{
Case constant 1:
statement 1;
break;
case constant 2:
statement 2;
break;
………………………
……………………..
case constant n:statement n-1;
break;
default :
statement n;
}

B] Looping / Iteration:
Looping is the process of executing the same
program statement or block of program statement
repeatedly for specified number of times.
Mainly there are three types of loop use in C
programming. They are:
i. For loop
ii. While loop
iii. Do- while loop

i. for loop:
It is the most common type of loop which
is used to execute program statement or
block of program statement repeatedly
for specified number of times. It consists
of three expression i.e. initialization,
condition and counter (increment /
decrement).
Syntax:
for(initialization;condition;counter)
{
Statement/ block of statements;
}

5!=5*4*3*2*1
1*2*3*4*5
1 4 9 ……upto
nth term
ii. while loop: It executes the program
statement repeatedly until the given
condition is true. It is also known as entry
control or pre-test loop.
Syntax:

Initialization;
While(condition)
{
Statements;
…………………
…………………
Counter;
}

iii. Do-while loop: it also executes program


statement repeatedly until the given
condition is true. But it executes the
program statement once at first then only
condition is checked. It is also called exit
control loop or post test loop.

Syntax:
Initialization;
Do
{
Statements;
……………….
……………….
Counter;
} while(condition);

Q. Differences between ‘for’ loop and ‘while’


loop.
For While
i. It is definite loop. i. It can be both
definite as well as
indefinite loop.
ii. It uses keyword ‘for’. ii. It uses keyword
‘while’.
iii. Syntax: iii. Syntax:
for(initialization;condition;counter) Initialization;
{ While(condition)
Statement; {
} Statement;
……………….
Counter;
}

iv. Example : iv. Example:


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
Void main() Void main()
{ {
Clrscr(); Clrscr();
Int I; Int I;
For(i=1;i<=10;i++) I=1;
{ While(i<=10)
Printf(“\n Hello world”); {
} Printf(“\n Hello
Getch(); world”);
} I++;
}
Getch();
}

Q. Differences between ‘while’ and ‘do-while ‘


loop.
While Do-while
i. In while loop, i. In do-while loop,
condition is condition is
checked in the checked at the
beginning. end.
ii. It is also called ii. It is also called
pre-test loop or post-test loop or
entry control exit control loop.
loop.
iii. It is not iii. It is terminated
terminated with by semi-colon.
semi-colon.
iv. It uses keyword iv. It uses keyword
‘while’. ‘do’ and ‘while’
v. In while loop, v. In do-while loop,
statements are statements are
not executed if executed once
the condition is even if the
false. condition is false.
vi. Syntax: vi. Syntax:
Initialization; Initialization;
While(condition) do
{ {
Statements; Statements;
………………… …………………
Counter; Counter;
} }while(condition);

vii. Example: viii. vii. Example:


WAP to display WAP to display
hello world 10 hello world 10
times. times.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
Void main() Void main()
{ {
Clrscr(); Clrscr();
Int I; Int I;
I=1; I=1;
While(i<=10) do
{ {
Printf(“\n Hello world”); Printf(“\n Hello world”);
I++; I++;
} }while(i<=10);
Getch(); Getch();
} }

 Nested loop: We can write an entire loop


structure inside another loop structure. This
loop inside another loop is called nested loop.
Syntax:
For(initialization;condition;counter)
{
For(initialization;condition;counter)
{
Statements;
}
Statements;
}
 Infinite loop: A loop which never terminates is
called infinite loop.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a;
for(a=2;a>=1;i=i+1)
{
printf("%d",a);
}
getch();
}

C] Jumping statement: Jumping statements


are particularly used to jump execution of
program statement from one place to another
place inside a program.
i. break statement:
ii. continue statement
iii. goto statement
i. Break: when break statement is
encountered, the entire loop or statement
is terminated.
ii. Continue statement:
When continue statement is encountered
the entire loop is not terminated; only the
particular loop is skipped.
iii. goto statement: When goto statement is
encountered in a program then it transfer
the control of the program statement
execution unconditionally to the location
specified by the goto statement within a
correct function.
Syntax:
goto label; label:
………………. ………………
………………. Or ………………
Label: goto label;

 In definite loops, the number of iterations is known before


we start the execution of the body of the loop.
Example: repeat for 10 times printing out a *.
 In indefinite loops, the number of iterations is not known
before we start to execute the body of the loop, but depends
on when a certain condition becomes true (and this depends
on what happens in the body of the loop)
Example: while the user does not decide it is time to stop,
print out a * and ask the user whether he wants to stop.

Array and string


Array: An array is a collection of similar type of
data items under the common name. it acts to
store related data under the same name with an
index, also known as subscript which helps to
access individual array element. Array data type
may be int, float, char etc depending upon the
nature of the problems.
E.g. int a[5]; float w[100]; char t[10];

Features of array:
i. The entire array elements share the common
name.
ii. The elements of array are stored in contiguous
(closest / nearby) memory location.
iii. We put the array size of the fixed length as
required that means once the size is declared
then the size will be fixed at the execution time
of the program, so called static type.

Types of array:
i. One dimensional array
ii. Two /multi-dimensional array

i. One dimensional array: An array which has only


one subscript is called one dimensional array. A
subscript is a number of large bracket in which
we put the size of array.

Declaration of one dimensional array:


Syntax:
Data_type array_name[array_size];
E.g.
Int a[5];
Float w[100];
Char name[10];

Initialization of one dimensional array:


Syntax:
Data_type array_name[size]={val1, val2, …….valn};
Example:
int m[5]={50,60,70,80,90};

m[0] m[1] m[2] m[3] m[4]


50 60 70 80 90
Index 0 index 1 index2 index3 index4
The value to the array element can be assigned as
follows:
m[0]=50
m[1]=60
m[2]=70
m[3]=80
m[4]=90

other example:
float[3]={1.5,2.5,7.3};
char n[10]={‘n’,’e’,’p’,’a’,’l’};
ii. Multi/Two-dimensional array: Multi-
dimensional array is defined as the same as one
dimensional array except that it consists of
more than one pair of square bracket that is
subscript(index).
Syntax:
Data_type array_name[row_size][column_size];

Example:
int a[3][3];
In this example, a multi dimensional array of integer
data type consisting of three rows and three
columns.
[Note: The total number of elements in an array is
given by calculating: row_size*column_size
For e.g. int a[4][5];
The total number of elements in this array is
4*5=20.]
Initialization of multi dimensional array:
In multi dimensional array (suppose 3x3 matrix), data
items are stored in memory as below:
Column 0 column 1 column 2
[0][0] [0][1] [0][2]
Row0 100 200 300
[1][0] [1][1] [1][2]
Row1 200 150 50
[2][0] [2][1] [2][2]
Row2 350 500 600
This means
int matrix[3][3]={100,200,300,200,150,50,350,500,600};
i.e.
matrix[0][0]=100;
matrix[0][1]=200;
matrix[0][2]=300;
matrix[1][0]=200;
matrix[1][1]=150;
matrix[1][2]=50;
matrix[2][0]=350;
matrix[2][1]=500;
matrix[2][2]=600;
Q. Differences between one dimensional and multi-
dimensional array
One dimensional array Multi dimensional array
1. It consists of only 1. It consists of two
one subscript. subscript.
2. Maximum size will 2. Maximum size will be
be the size of the the product of row and
array which we column size of an array
defined in the which we defined in the
program. program.
3. It stores data 3. It stores data in matrix
either row wise or form i.e. row wise and
column wise. column wise.
4. Syntax : 4. Data_type array_name[row][column];
Data_type array_name[array_size];
5. E.g. int n[5]; 5. E.g. int n[2][3];
String
A string is an array of characters. It
contains characters, symbols,
numbers etc.
Syntax:
Char string_name[string_size];
E.g.
Char name[10];
Char address[15];

Initialization of string:
Char name[10]={‘c’,’ ‘,’p’,’r’,’o’,’g’,’r’,’a’,’m’,’\0’};
Or
Char name[10]=”c program”;
Name[0] name[1] name[2] name[3] name[4]
C P R O

Name[5] name[6] name[7] name[8] name[9]


G R A M \0

Q . WAP to input string in an array then display them.

Array of string:
A two dimensional array of character is called
array of string.
Syntax:
Char string_name[number of string][length of string];
E.g.
Char name[5][10];

String handling function:


The C library supports a large number of string handling
functions that can be used to carry out many of the string
manipulation (handling). The header file
#include<string.h> is used for string handling function.
Some of the common string manipulation functions are:
a.strlen ( ): The strlen( ) returns the length of a string
which takes the string name as an argument or
parameter .
Syntax:
Variable_integer=strlen(string_name);
E.g.
a=strlen(name);
Where string_name is the name of string and
variable_integer is a variable on which length of the
string is to be stored and returns us the value.

b.strrev( ): The strrev( ) is used to reverse the given


string.
Syntax:
Strrev( str );
Where str is the string to be reversed.

Q. WAP to reverse the given string.

c. strcpy( ): The strcpy( ) is used to copy one string into


another string.
Syntax:
Strcpy( str1,str2);
Where, str1 and str2 are two strings. The content of
str2 is copied on str1.
d.strcat( ): The strcat( ) is used to join or concatenate
one string into another string.
Syntax:
Strcat(str1,str2);
Where str1 and str2 are two string variable. The
content of str2 is joined after str1.

e.Strcmp( ): The strcmp( ) is used to compare two


string character by character.
Syntax:
V=strcmp(str1,str2);
Where str1 and str2 are two string variable to be
compared and v is returned value in integer.
f. strlwr( ): The strlwr( ) is used to convert uppercase
characters of string into lowercase characters.
Syntax:
Strlwr(string_name);
Where, string_name is the name of the string to be
converted into lowercase string.

g.Strupr( ): The strupr( ) is used to convert lowercase


characters of string into uppercase characters.
Syntax:
Strupr(string_name);
Where, string_name is the name of the string to be
converted into uppercase string.
Function
A function is a self contained block of code that
performs a particular task.

Advantages of function:
i. Function uses code reusability.
ii. Program development will be faster.
iii. Program debugging will be easier.
iv. Larger number of programmer can be involved.

Component of function:
a.Function prototype
b.Function definition
c. Call the function or function call
a.Function prototype: It provides the following
information to the computer:
1.The type of the value returned.
2.The name of the function
3.The number and the type of the argument that
must be supplied in a function call.
Syntax:
Return_value function_name(arg1, arg2,…..argn);
Example:
int sum(int a, int b);
They are generally written at the beginning of a
program, ahead of the main ( ). It is also called
function declaration.

b.Function definition: it has two principles.


1.Function header or function declaratory
2.Body of function
Syntax:
return_type function_name(arg1, arg2,…….,argn)
example :

int sum(int a, int b) // function header


{
int c; body of function
c=a+b;
return(c);
}

c. Call the function or function call: A function call is


specified by the function name followed by the
argument enclosed in parenthesis and terminated by
a semi-colon.
Syntax:
Variable=function_name( arg1, arg2,…..,argn);
Or
Function_name( arg1, arg2,…..,argn);

Example:
b=value(a);
or
value(a);

Types of function:
Two types of function
a.Library function(Built-in Function)
b.User defined function
Library function User defined function
1.Library functions are 1.User defined
pre defined function. functions are
function which are
created by the
programmer
according to need.
2.Library function 2.User defined
required header files function requires
to use it. function prototype to
use it.
3.Program 3.Program
development time is development time is
faster. slower than library
function.
4.It is called at run 4.It is called at
time. compiled time.
5.Example: printf( ), 5.Example: day( ),
strlen( ), scanf( ), simple( ), sum( ) etc.
clrscr( ) etc.

Categories of user defined function:


a.Function returning value and passing arguments
[ int sum(int a, int b);]
b.Function returning no value but passing
arguments [ void sum(int a, int b);]
c. Function returning value and passing no
arguments[ int sum ( );]
d.Function returning no value and passing no
arguments [ void sum( );]

a.Function returning value and passing arguments


[ int sum(int a, int b);]
Q. WAP to find the sum of two numbers.
i/p,call,o/p=main()
process,return=function header
b.Function returning no value but passing arguments
[ void sum(int a, int b);]
Q. WAP to find the sum of two numbers.
i/p,call=main()
process,o/p=function header
c. Function returning value and passing no arguments
[ int sum ( );]
Q. WAP to find the sum of two numbers.
call,o/p=main()
i/p, process,return=function header

d.Function returning no value and passing no arguments


[ void sum( );]
call=main()
i/p, process,o/p=function header

Q. WAP to find the sum of two numbers.

Return and void statement:


a)Return statement: One of the main features of
the function is that it can return a value to a
calling function. For this, a “return” keyword is
used. So, ‘return’ keywords returns the program
control from a function to calling function.
Syntax:
return(expression);

b) void statement: If a function doesn’t return a


value then we say the function return type is void.
Example:
WAP to check whether entered number is even or
odd using function.
WAP to check whether entered no is divisible by 5
or not using function

Concept of recursive function:


A function called itself within a function is called
recursive function.
void sum( );
void main()
{
……………
……………
sum( ); // resurcive call
………….
}
E.g. WAP to find the factorial of a number by
using recursive function.

Function with Array:


Like the values of simple variables, it is 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 subscript/index
and the size of the array as argument.
e.g. int sum(int a[ ]);
Q. WAP to input 5 numbers and print the sum of it
using array and function.

Structure and Union:


Structure: Structure is defined as the collection of
one or more data items with different data types
treated as single unit. Each data item is called
member of structure. The keyword ‘struct’ is
used declare structural variable and type of
structure variable is defined by the tag name of
the structure.

Syntax:
Struct tag_name
{
Data_type member1;
Data_type member2;
………………………………..
Data_type membern;
};
Struct tag_name v1,v2,………,vn;
Or v1,v2,…….vn;

Example:

Struct student
{
Int roll;
Char fname[50];
Char lname[40];
};
Struct student s1,s2,s3;
Or
S1,s2,s3;

Structure initialization:
Struct student
{
Int roll;
Char fname[50];
Char lname[40];
};
Struct student s1={1,”ram”,”Shrestha”};
Struct student s2={2,”Sita”,”Chaudhary”};
struct student s3={3,”Hari”,”Pandey”};

Accessing structure member:


A member of structure can be accessed by using
period(.) sign between structure variable and
respective member.
Syntax:
Variable.member
Example
S1.roll, s2.fname, s3.lname

Q. WAP that will take roll number, first name and


last name then print the record on screen using
structure.

User Defined data type (typedef):


The “typedef” keyword allows us to define new
data types that are equivalent to existing data
type.
Syntax:
typedef data_type new_datatype
E.g
typedef int age;
age male, female;

Here, male and female are structural variable with


data type age.
Nested Structure:
Structure is defined as a member of another
structure. It is also known as nested structure.
Example:
Struct data
{
Int year;
Int month;
Int day;
};
Struct student
{
Int roll;
Char fname[40];
Char lname[30];
Struct data d; // date of birth
};

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 variable having same set of
members.
Example:
Struct student
{
Int roll;
Char fname[20];
Char lname[30];
};
Struct student s[5];

Roll roll roll roll roll


Fname fname fname fname fname
lname lname lname lname lname
s[0] s[1] s[2] s[3] s[4]

printf(“\n Enter name”);


scanf(“%s”,s[i].name);

Q. WAP that takes roll no, first name and last


name of 10 students then display the same record
on screen using structure.
Q. WAP to accept students data as name, age,
class, faculty and percentage of 5 students then
display the same record on the screen using
structure.
sizeof structure:
The actual memory size of a variable in term of
bytes may differ from machine to machine.
Therefore, the “sizeof” operator helps us to
determine memory size of a variable.
Syntax:
Sizeof( variable);
Example:
Struct student
{
Int roll;
Char fname[30];
Char lname[30];
};
Struct student s;
sizeof(s);

Roll: 2byte
Fname:30 byte
Lname: 30 byte
Total : 62 byte
Introduction to Union
Union is similar to structure but it differ only in its storage
location. The “union” keyword is used to define union.
Syntax:
union tag_name
{
Data_type member1;
Data_type member2;
………………………………….
Data_type membern;
};
Union tag_name v1,v2,….vn;

Example:

union student
{
int roll;
char fname[50];
char lname[40];
};
union student s;
Q. Differences between structure and union
Structure Union
1.It is the collection of data 1.Same as structure but
items having dissimilar it differ in its storage
data types. class.
2.Multiple members can be 2.Only one member can
simultaneously accessed be accessed at a time.
at a time.
3.The “struct” keyword is 3.The “union” keyword
used to define structure. is used to define
union.
4.Syntax: 4.Syntax:
Struct tag_name union tag_name
{ {
Data_type member1; Data_type
Data_type member2; member1;
……………………………….. Data_type
Data_type membern; member2;
}; ………………………………..
Struct tag_name v1,v2,………,vn; Data_type
membern;
};
union tag_name
v1,v2,………,vn;

5.Example: 5.Example:
struct student union student
{ {
int roll;
char fname[50]; int roll;
char lname[40]; char fname[50];
};
struct student s; char lname[40];
};
union student s;

6.It occupies 7 byte memory 6.It occupies 4 byte


space. memory space.

Q. Differences between structure and array


Structure Array
1.It is the collection of 1.It is the collection of
data items having data items having
dissimilar data types. similar data types.
2.Each data item is called 2.Each data item is called
member. element.
3.It is possible to define 3.It is not possible to
array of structure. define structure of
array.
4.Syntax: 4.Syntax:
Struct tag_name
{ Data_type array_name[size];
Data_type member1;
Data_type member2;
………………………………..
Data_type membern;
};
Struct tag_name
v1,v2,………,vn;
5.Example: 5.Example:
struct student int n[5];
{
int roll;
char fname[50];
char lname[40];
};
struct student s;

Pointer
A pointer is a special type of variable that
represent memory address of a variable rather
than its value.

Value at address Address of first variable


5 * 20000 &

First variable Second Variable

5
2000
Features of pointer:
a.Pointer saves memory space.
b.It assigns dynamic memory allocation.
c. The execution time is faster because data
manipulation is done directly inside memory.
d.Pointers are very efficient for solving array and
string related problems.

The address (&) and indirection (*)


operator:
The “&” is the address operator. It represent the
address of the variable and “ * ” operator is the
value at address operator. It represents the value at
the specified address.
Example:
Int *p;
Int q;
P=&q;

Declaration of pointer variable :


Syntax:
Data_type *variable_name;
E.g.
Char *p;
Float *q;
Int *r;
Q. WAP showing simple pointer arithmetic.

Note 1: Pointer can be increment or decrement to


point to different location.
Example
int a=5;
int *b;
b=&a;
b++; // means 1000+2=1002
b--; // means 1000-2=998

In other example
int a=5;
a++; // means 5+1=6
a--; // means 5-1=4

Note2: It p1 and p2 are properly declared and


initialized pointer, the following operation are valid.
Val=val+*p1;
*p1=*p2+2;
Mul=*p1**p2;
Div=*p1/*p2;

Note3: Expression like p1==p2, p1<p2 are not


allowed.
Note4: These operations can never be done with
pointers and gives an error:
a.Addition between two pointers. For e.g.
val=p1+p2;
b.Multiplication between pointer and any number.
For E.g. val=p1*p2;
c. Division between pointer and any number. For e.g
val=p1/p2

Difference between array and pointer


Ans: There is a strong relationship between arrays
and pointers.
Let us consider one dimensional array name as “
num[10]” then
a.The address of the first array element can be
expressed as either &num[0] or num.
b. Similarly, the address of the second array element
be &num[1] or (num+1) and so on.
c. In general, the address element (i+1) will be
expressed as &num[i] or (num+i).

The relation of pointer and array is presented in


the following table.
Address of array element
Array element Equivalent pointer
notation
&num[0] num or (num+0)
&num[1] (num+1)
…………………… ………………….
&num[i] (num+i)

value of array element


Array element Equivalent pointer
notation
num[0] *num or (num+0)
num[1] *(num+1)
…………………… ………………….
num[i] *(num+i)

Q. WAP to input 10 numbers then display them


using pointer.

Uses of pointer:
a.Int *p; Ans: *p is declared as pointer variable
which would point to address of int data type of
value.
b.P=&a; Ans: p is initialized with the address of int
variable a.
c. Printf(“\n Address of a=%u”,&a);
Ans: &a(“address of” operator) is printing the
address of int variable a. %u is used to print
address in unsigned integer.
d.Printf(“\n Address of p=%u”,&p);
Ans : &p prints the address of pointer variable p.
e.Printf(“\n value of p=%d”,*p);
Ans : *p(“value at address” operator) prints the
value of address of pointer variable p.

Pointer and function:


As we have already studied about the function and
about the argument or parameter passing in
function. The parameters to the functions are
passed in two ways:
a.Call by value
b.Call by reference(address)

a.Call by value: In call by value, the values of the


variables are passed. When an argument is
passed by value, the data item is copied to the
function.

Q. WAP to swap two numbers showing call by


value.

b.Call by reference: In call by reference, the


address of the variable is passed. Any change
that is made to the data item will be recognized
in both the function and the calling function.

Q. WAP to swap two numbers showing call by


reference.
Working with files

Concept of data file:


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 (modify) and delete data in data file
as per our requirement.
C language supports number of function to perform
various operation such as defining file, opening file,
reading file, writing file, appending file and closing
file.
fopen( ): To create new file.
fclose( ): To close file
getc( ) : To read a character from a data file.
putc( ) : To write a character to data file.
getw( ): To read an integer from data file.
putw( ): To write an integer to a data file.
fscanf( ): To read formatted data from data file.
fprintf( ): To write formatted data to a data file.
fread( ): To read record from data file.
fwrite( ): To write record to data file.

Read: (getc(),getw(),fscanf(),fread())
Write:(putc(),putw(),fprintf(),fwrite())
 Defining and opening data file:
Syntax:

FILE *fp;
fp=fopen(“file name”,”file mode”);
E.g.
fp=fopen(“data.txt”,”w”);

The keyword “FILE “is used to declare file data type.

File Mode:
r = open an existing file for reading
w = open a new file for writing
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.

Note: Compiler automatically assign special character


at the end of the file called EOF(End of File).

Define EOF(End of File):


EOF is a special character (an integer with ASCII value
26) that indicates the end-of file has been reached.
This character can be generated from the keyboard by
typing ctrl+z. It is defined in <stdio.h>. When we are
creating a file, the special character EOF is inserted
after the last character of the file by an operating
system.

 Closing a data file: A data file must be closed after


doing various operation such as reading, writing etc.
E.g fclose(fp);

 getc( ) and putc( ) : Function getc() helps to read


single character from file and putc( ) helps us to write
single character to file. In the following example, ch is
a character variable and fp is the file pointer.
E.g.
ch=getc(fp); // to read data
putc(ch,fp); // to write data

Q. WAP to read and write characters from/to file


using getc( ) and putc().

 getw() and putw(): 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 the file pointer.
x=getw(fp); // read single integer from file
putw(x,fp); // write single integer to file

Q. WAP to read and write integer from/to file using


getw() and putw() function.
 fscanf() and fprintf(): 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
the file pointer and control string defines data types
for the respective variables.
Syntax:
fscanf(fp,”control string”,variable); //read data
fprintf(fp,”control string”,variable); //write data

Q. WAP to read and write roll number, name and


percentage of a students from/to data file using
fscanf() and fprintf().

. fwrite() and fread(): Function fread() helps us to read


structure type data i.e. record from data file and
function 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.
Syntax:
fread(&variable,sizeof(variable),1,fp);
fwrite(&variable,sizeof(variable),1,fp);
Q. WAP to write and read a record to/from a data file
named “ employee.txt” that contain employee ID,
name and salary of employee using fwrite() and
fread() function.

Sequential and Random Access File:


Two types of file processing techniques are used for
accessing the data file. They are:
a.Sequential file processing
b.Random file processing.

a.Sequential: 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.
b. Random: 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(), rewind()
and fseek().
 ftell(): It takes file pointer as parameter and returns
long data type that represent current position of the
file in terms of byte.

Syntax:
n=ftell(fp);
 rewind(): It takes file pointer as parameter and reset
the position to the start of the file.
Syntax:
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.
Syntax:
fseek(fp,offset, position);

 remove(): The remove() function helps us to delete


the file specified as a parameter.
Syntax:
remove(“file name”);

 rename(): The rename() function helps us to rename


the existing file into new file.
Syntax:
rename(“old file name”,”new file name”);

Q. WAP to delete and rename data file using remove


and rename function.

You might also like