Programming in C (BCAFY)
Programming in C (BCAFY)
Unit I
Introduction to Programming in C
* History:
By 1960 a several computer languages had come into existence, each one is
designed for a specific purpose. For example, COBOL was used for commercial
applications, FORTRAN for engineering and scientific applications and so on. At this
stage people started thinking that instead of learning and using so many languages, each
for a different purpose, why not use only one language which can programs all possible
applications. Therefore, an international committee was set up to develop such a
language. This committee came out with a language called ALGOL60. But, this language
never popular because it seemed too abstract i.e. theoretical and too general. To reduce
this abstractness and generality, a new language called Combined Programming
Language (CPL) was developed at Cambridge University. But, CPL turned out to be so
big, having so many features, that it was hard to learn and difficult to implement.
Basic Combined Programming Language (BCPL) developed by Martin Richards
at Cambridge University aimed to solve this problem by bringing CPL down to its basic
good features. Around the same time a language called B was written by Ken Thompson
at AT & T‟s Bell Labs, as a further simplification of CPL. Ritchie inherited the features
of B and BCPL and B. C‟s compactness and coherence is mainly due to the fact that it‟s a
one-man language.
C is programming language developed at AT & T’s Bell Laboratories, USA in
1972 by Dennis Ritchie. Without any advertisement C stand and spread, so as a result
it‟s user group grow fastly. It was designed to be friendly, capable and reliable.
Interpreters:
This is another type of translator used to translate a high-level language into its
equivalent machine language program. It takes one statement of the high-level language
B. C. A. First Year 1
Programming in C
program, translates program, translates it into machine language instructions, and then
executes the resulting machine language instructions immediately.
* Structure of C Program:
# include <pre-processor directives>
[ Macro declaration and definition ]
[ Global variable declaration ]
main ()
{
Local variable declaration with proper data-type;
…
…
…
statements;
…
…
…
}
[ User_Defined_Function_Definition ([arguments])
{
Statement_Block;
}
]
Explanations:
# include <pre-processor directives> :
At this place we have to include all the header files, which are prototype for the
statements, which are used in our program.
[ Macro declaration and definition ] :
At this place we have to declare and define the definition of the macro that are
used in program. It is optional.
[ Global variable declaration ]:
If we required global variables in our program then such variables are declared at
this place. It is optional.
B. C. A. First Year 2
Programming in C
main():
This is the first statement of every C program. Every C program must start with
main() function.
Local Variable Declaration:
At this place, we have to declare all the variables with proper data type, which are
used in main() in our program.
statements:
At this place, we have to write all the statements, which are used to solve the aim
of program.
[ User_defined_function_definition ]:
If any user-defined function is called in program, then its definitions are given at
this place. It is optional.
For example:
#include<stdio.h>
#include<conio.h>
main()
{
int a, b;
clrscr();
printf(“Enter any values for a & b:”);
scanf(“%d%d”, &a,&b);
printf(“\n Sum is %d”, a + b);
getch();
}
B. C. A. First Year 3
Programming in C
boxes to indicates the flow of operation, i.e., the exact sequence in which to execute the
instructions.
Flowchart Symbols:
1. Terminals: The terminals symbol indicates the beginning i.e. start,
end i.e. stop and pauses i.e. halt in a program‟s logic flow. It is the
first and last symbol in a flowchart. A pause is normally used in a
program logic under some error conditions.
2. Input / Output: The input/output symbol denotes any function of
an input/output nature in a program. Hence, all program instructions
to input/output data from any type of input/output devices such as
keyboard, mouse, scanner, monitor, printer, plotter etc.
3. Processing: A processing symbol represents arithmetic and data
movement instructions. Hence, all arithmetic processes of adding,
subtracting, multiplying and dividing are indicated by a processing
symbol in a flowchart.
4. Decision: The decision symbol indicates a decision point, i.e. a
point at which a branch to one of two or more alternative points is
possible.
5. Flow lines: Flow line with arrowhead indicates the flow of
operations, i.e., the exact sequence in which the instructions are
executed. The normal flow is from top to bottom and left to right.
6. Connectors: whenever a flowchart becomes so complex that the
number and direction of flow lines are confusing or it spreads over
more than one page, it is useful to utilize connector symbols as a
substitute for flow lines. This symbol represents an entry from, or an
exit to another part of the flowchart.
Constants:
Whose quantity doesn‟t change during program execution or whose value does not
change during program execution is called Constant. Quantity is stored in memory at a
free location. For example, in equation (5 * a), 5 is constant which is not change where as
„a‟ is variable whose value change during program execution.
B. C. A. First Year 4
Programming in C
Types of Constants:
Keywords:
Keywords are the words whose meaning has already been explained to the C
compiler. Keywords are also called as Reserved words. There are only 32 keywords
available in C as follows.
auto double int struct break
else long switch case enum
B. C. A. First Year 5
Programming in C
register union typedef char extern
return const float short unsigned
continue for signed void default
goto sizeof volatile do if
static while
* Data Types:
1) int: This data type is used to store integer values in the range of -3276 to 32767. It
takes 2 bytes in memory.
Syntax: int variable_name;
2) float: This data type is used to store decimal values in the range of 3.4E-38 to
3.4E+38. It takes 4 bytes in memory.
Syntax: float variable_name;
3) double: This data type is used to store decimal values in the range of 1.7E-308 to
1.7E+308. It takes 8 bytes in memory.
Syntax: double variable_name;
4) char: This data type is used to store characters. It takes one byte in memory to store
one character.
Syntax: char variable_name;
5) void: This data type is used with function as return data type when function has not
return any value to its calling function. Void means nothing.
Syntax: void
* Operators in C:
An operator is a symbol that tells computer i.e. compiler to perform certain
mathematical or logical manipulation. C has following types of operators.
1) Arithmetic Operators: It required two operands to perform desired operation on it.
One operand is present to the left side and second operand is present to the right side of
the operator. After performing an operation it returns an answer in single value.
Following are the arithmetic operators in C:
(a) + : This is an addition operator, which is used to add two values. For ex, 4 + 5.
(b) – : This is a subtraction operator, which is used to subtract two values. For ex, 4-5.
(c) * : This is a multiplication operator, which is used to multiply two values.
(d) / : This is a division operator, which is used to divide two values. For ex, 9 / 2 = 4.
(e) % : This is a modulus operator, which is used to return the remainder of two values.
For ex, 4 % 3 = 1.
2) Relational Operators: These are used to compare the two operands and return the
result.
(a) < : This is a less than operator, which compares the left side operand value to right
side operand value. It returns value 1 for true else returns value 0 for false. For ex, 2 < 3.
(b) > : This is a greater than operator, which compares the left side operand value to right
side operand value. It returns value 1 for true else returns value 0 for false. For ex, 7 > 3.
(c) < = : This is a less than equal to operator, which compares the left side operand value
to right side operand value. It returns value 1 for true else returns value 0 for false. For
ex, 2 <= 3.
B. C. A. First Year 6
Programming in C
(d) > = : This is a greater than equal to operator, which compares the left side operand
value to right side operand value. It returns value 1 for true else returns value 0 for false.
For ex, 7 > = 3.
(e) = = : This is a equal to operator, which compares the left side operand value to right
side operand value. It returns value 1 for true else returns value 0 for false. For ex, 2== 3.
(f) ! =: This is a not equal to operator, which compares the left side operand value to right
side operand value. It returns value 1 for true else returns value 0 for false. For ex, 2!= 3.
3) Logical Operators: These are used to combine two or more expression or operands.
(a) &&: This is a „logical and‟ operator which is used to combine two or more
expressions or operands or conditions. It returns value true or 1 if all the conditions are
true else return value false or 0. For ex, 4 > 3 && 4 > 2. (true)
(b) || : This is a „logical or‟ operator which is used to combine two or more expressions or
operands or conditions. It returns value true or 1 if either one condition is true and if all
conditions are false then it return value false or 0. For ex, 1 > 3 || 4 > 2. (true)
(c) !: This is a „logical not‟ operator. It reverses the expression answer. If answer is true
then this operator makes it false and vice versa. For ex !( 4 > 3 && 4 > 2). (false)
4) Assignment Operator (=): This operator is used to assign the value of right side
expression to left side. For ex, a = 4.
5) Conditional or Ternary Operator: It is a shortcut of if …. else. The syntax of
conditional operator is as
expression 1 ? expression 2 : expression 3
In the syntax expression 1 represents the condition and expression 2 and
expression 3 represents the action. While evaluating this operator first the condition of
expression 1 is checked, if it is true then expression 2 will execute and expression 3 will
skipped, if it is false then expression 2 will skipped and expression 3 will execute.
5) Unary Operators: The operator that acts upon a single operand to produce a new
value is known as unary operators. Unary operators usually precede their single operands,
but some unary operators are written after their operands. Following are the unary
operators:
a) unary minus (-) : When a numerical constant, variable or expression is preceded by a
minus sign then it is a unary minus operator. For ex, - 44, - 0.03
b) increment (++) : Increment operators are of two variations as:
(i) pre increment: When a ++ operator is placed before the operand then it is called as pre
increment operator. This operator increments the value of operand by 1 in current step.
For ex, ++a
(ii) post increment: When a ++ operator is placed after the operand then it is called as
post increment operator. This operator increments the value of operand by 1 in next step.
For ex, a++
c) decrement (- - ): Decrement operators are of two variations as:
(i) pre decrement: When a - - operator is placed before the operand then it is called as pre
decrement operator. This operator decrements the value of operand by 1 in current step.
For ex, -- a
(ii) post decrement: When a - - operator is placed after the operand then it is called as
post decrement operator. This operator decrements the value of operand by 1 in next step.
For ex, a - -
6) Bitwise Operator: Bitwise operators provide features to perform operation on bits.
B. C. A. First Year 7
Programming in C
a) ~ : This is a „one‟s complement‟ operator, which operates on one operand. This
operator provides a 1‟s complement of the given number. For ex, ~ 2
b) >> : This is a „right shift‟ operator, which operates on one operand. It shift each bit in
the operand to the right. For ex, 5 >> 2
c) << : This is a „left shift‟ operator, which operates on one operand. If shifts each bit in
the operand to the left. For ex, 5 << 2
d) & : This is a „bitwise and‟ operator which operates on two operands. While operating
upon these two operands they are compared on a bit by bit basis. For ex, 5 & 2.
e) | : This is a „bitwise or‟ operator which operates on two operands. While operating
upon these two operands they are compared on a bit by bit basis. For ex, 5 | 2.
f) ^ : This is a „bitwise exclusive or‟ operator, which operates on two operands. While
operating upon these two operands they are compared on a bit by bit basis, for ex, 5 ^ 2.
B. C. A. First Year 8
Programming in C
g) puts( ): This function prints a string on the standard output. This function is used with
only string type.
Syntax: puts(variable_name);
B. C. A. First Year 9
Programming in C
Unit II
Control Structures
B. C. A. First Year 10
Programming in C
“If ….Else” statement consist of two parts as „if‟ block and „else‟ block. Condition
is always written in parenthesis after „if‟ keyword in same line. To check condition we
have to use relational or logical operators.
It first check the condition, if it is true then „if block‟ i.e. statement_block1
executes and at that time „else block‟ is skipped. If the condition is false then „if block‟ is
skipped and „else block‟ i.e. statement_block2 executes. If we have to execute more than
one statement in a block then we have to write these statements within opening and
closing curly brackets {}.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int marks;
clrscr();
printf(“Enter your marks:”);
scanf(“%d”,&marks);
if (marks > = 35)
{
printf(“You are Pass.”);
}
else
{
printf(“You are Fail.”);
}
}
3) Multiple If Statement:
Syntax:
if (condition 1)
{
Statement_block1;
}
else
if (condition 2)
{
Statement_block2;
}
else
…
…
…
if (condition n)
{
Statement_block n;
}
B. C. A. First Year 11
Programming in C
else
{
Statements;
}
When more than one „if‟ are placed in a series or sequence, then such „if‟ structure
is called as „multiple if‟ structure. In this structure first „if‟ condition is checked. If it is
true, then „statement block 1‟ is executed and rest of „if‟ conditions are skipped. If
condition is false, then second „if‟ condition is checked. If it is true then, statement block
for that „if‟ is executed and rest of „if‟ conditions are skipped. If second condition is false
then third condition is checked. This process continuous till any subsequent „if‟ condition
is false. If any „if‟ condition is false, then last „else‟ part is executed.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2, ch;
clrscr();
printf(“Enter values for num1 & num2:”);
scanf(“%d%d”,&num1,&num2);
printf(“1.Add\n2.Sub\n3.Mul\n4.Div\n Type Choice (1 – 4):”);
scanf(“%d”,&ch);
if (ch = = 1)
{
printf(“\n Addition is %d”,num1+num2);
}
else
if (ch = = 2)
{
printf(“\n Subtraction is %d”,num1-num2);
}
else
if (ch = = 3)
{
printf(“\n Multiplication is %d”,num1*num2);
}
else
if (ch = = 4)
{
printf(“\n Division is %d”,num1/num2);
}
else
printf(“Invalid Choice.”);
getch();
}
B. C. A. First Year 12
Programming in C
4) Nested If Statements:
Syntax:
if (condition)
{
if (condition)
{
Statements;
}
else
{
Statements;
}
}
else
{
if (condition)
{
Statements;
}
else
{
Statements;
}
}
OR
if (condition 1)
{
if (condition 2)
{
if (condition 3)
{
Statements;
}
}
}
When entire if…else structure is placed within another if block or else block, then
such structure is called „nested if‟ structure. OR if one „if‟ is present within another „if‟,
another „if‟ present within another „if‟ and so on, then such „if‟ structure is called as
„nested if‟ structure.
In this structure first outer „if‟ condition is checked. If condition is true then „if
block‟ gets control and „else block‟ is skipped. If the condition is false then „if block‟
skipped and „else block‟ gets control. After getting control to any block again the
conditions inside it is checked, if it is true then „if block‟ is executed otherwise „else
block‟ is executed.
Program:
#include<stdio.h>
B. C. A. First Year 13
Programming in C
#include<conio.h>
main()
{
int a, b, c;
clrscr();
printf(“Enter values for a, b, c: ”);
scanf(“%d%d%d”,&a,&b,&c);
if (a > b)
{
if (a > c)
{
printf(“%d is Greater”, a);
}
else
{
printf(“%d is Greater”, c);
}
}
else
{
if (b > c)
{
printf(“%d is Greater”, b);
}
else
{
printf(“%d is Greater”, c);
}
}
}
B. C. A. First Year 14
Programming in C
Flowchart:
This is a control statement which allows to make a decision from the number of
choices. To make these control statements complete, three keywords are used as „switch,
case and default‟. The „switch‟ keyword is followed by a expression, which accept an
integer value. When we execute the program which contains the „switch‟ statement, first
the expression following the keyword „switch‟ is evaluated. When a match is found, the
program executes the statement following that case and all subsequent „case‟ and
„default‟ statement as well. If no match is found with any of the case statement, only the
statements following the „default‟ are executed.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int num1, num2, ch;
clrscr();
printf(“Enter values for num1 & num2:”);
scanf(“%d%d”,&num1,&num2);
printf(“1.Add\n2.Sub\n3.Mul\n4.Div\n Type Choice (1 – 4):”);
scanf(“%d”,&ch);
switch (ch)
{
case 1:
{
printf(“\n Addition is %d”,num1+num2);
break;
}
B. C. A. First Year 15
Programming in C
case 2:
{
printf(“\n Subtraction is %d”,num1-num2);
break;
}
case 3:
{
printf(“\n Multiplication is %d”,num1*num2);
break;
}
case 4:
{
printf(“\n Division is %d”,num1/num2);
break;
}
default:
printf(“Invalid Choice.”);
}
getch();
}
For loop is a fixed number of times loop. This loop is used when we have to
perform some series of statement for a fixed number of times. It consists of three parts.
First part represents the starting value of loop, second part specifies how many times the
loop is executed and third part represents the step value of loop.
When loop first time executes, the initial or start value is assigned to a counter
variable and loop is executed till the counter value matches the condition. In each step the
value of counter value is incremented or decremented by the step value.
B. C. A. First Year 16
Programming in C
Flowchart:
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
clrscr();
for(a=1;a<=10;a++)
{
if(a%2 == 0)
{
printf(“\n %d”,a);
}
}
}
2) While Loop:
Syntax:
while (condition)
{
Statements;
}
It is a conditional loop. This loop executes a series of statements, which are placed
between opening and closing curly brackets followed by „while‟, till the condition is
B. C. A. First Year 17
Programming in C
match. It is a pre-testing loop, means it will first check the condition. If the condition is
match, then the statements are executed. If the condition is not match, then the program
counter is moved on the next statement followed by „while loop‟. If the condition is not
match for first time, then the statements in „while loop‟ are not executed for a single time.
When we use „while loop‟, we don‟t know in advance, how many times the loop will
execute?
Flowchart:
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a = 1;
clrscr();
while (a<=10)
{
if(a%2 == 0)
{
printf(“\n %d”,a);
}
a = a + 1;
}
}
B. C. A. First Year 18
Programming in C
Statements;
} while (condition);
Flowchart:
This is a conditional loop. It executed a series of command till the given condition
is match. If the condition is match then the statements between „do‟ and „while‟ are
executed. If the given condition is not match then the program pointer jumps to the next
statement followed by „while‟. It is also called as „post-testing‟ loop because it first
executes the command and then check the condition. If the condition is true, then it
executes the command second time, else not. This loop is executed minimum one time if
the condition is not match for the first time.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a = 1;
do
{
if(a%2 == 0)
{
printf(“\n %d”,a);
}
a = a + 1;
} while (a<=10);
}
B. C. A. First Year 19
Programming in C
* Break & Continue:
Break:
This command is used to unconditionally exit from the loop. It is useful in a
situation where we want to jump out of loop immediately, without waiting to get back to
the conditional test. It is mostly used with „if‟ statement. If we wish to exit from loop for
a particular condition, then specify that particular condition using „if‟ and write the
„break‟ statement in the body of „if‟. So if the condition is match then loop is break and
first statement after loop is executed.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int num, a;
clrscr();
printf(“Enter any number: ”);
scanf(“%d”,&num);
for(a=2;a<=num-1;a++)
{
if(num % a == 0)
{
printf(“Not a Prime Number.”);
break;
}
}
if (num = = 1|| num = = a)
{
Printf(“Prime Number”);
}
}
Continue:
This command is used to skip the rest of the commands of the loop for the current
occurrence and move the program pointer to the top of the loop. When the keyword
„continue‟ is encountered inside any C loop, control automatically passes to the
beginning of the loop.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
for(a=1;a<=10;a++)
{
if(a%4 == 0)
continue;
printf(“%d\t”,a);
B. C. A. First Year 20
Programming in C
}
}
Goto:
This is a jump statement. Using this command, we can move program pointer
(jump) from one point of program to another point directly. When user jump from one
point to another point then the commands between these are not executed. User can jump
from top to bottom or bottom to top in a program.
It consists of two parts: „goto‟ keyword followed by „label name‟. The given „label
name‟ is presented in a program at any part followed by colon, means when the „goto‟
statement is occurred in the program, then it search the given label in program and moves
the program counter to that location.
Syntax:
OR
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int num;
clrscr();
printf(“Type any Number :”);
scanf(“%d”, &num);
if(num <= 0)
goto e;
printf(“\n Square is %d”,num * num);
e:
}
B. C. A. First Year 21
Programming in C
Unit III
Functions in C
* What is a function?
Function is a self-contained block of statements that perform certain tasks. User
can avoid the read and write same code over and over by using function. Every C
program musts consist of one function as „main( )‟ because program execution always
begins with main( ). The function from which any function is called, is referred as
„calling function‟. The function which is called, is referred as „called function‟.
C functions can be classified into two categories as follows.
1) Library Function: These functions are provided by C language. C contains the
required coding of such type of functions. User can directly call these functions in their
program by writing the function name and passing the necessary arguments. To access
these function in program user must have to add related header file which contains the
definition of that function. Examples of Library Functions are: scanf(), printf(), strcpy(),
sqrt() etc.
2) User Defined Function: These type of functions are developed by user as per own
requirement while writing a program. Normally the definition of such type function is in
a same program in which they called.
* Function Declaration:
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
For the above defined function max(), the function declaration is as follows −
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.
* Function Definition:
It is a place where we have to write all the commands which we required
frequently in a program. User defined function definition is written below the main( )
function definition. If we pass the arguments from the calling function to a called
function then it is compulsory to place argument in a called function definition to receive
the values from calling function.
Syntax:
B. C. A. First Year 22
Programming in C
Function_name ([argument list with proper data type])
Argument declarations
{
Local variable declaration;
Statements 1;
Statements 2;
…
….
Statements n;
}
For example:
about( )
{
printf(“C is a middle level language.”);
}
A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Function Body − The function body contains a collection of statements that define what
the function does.
Return Statement-
The return statement terminates the execution of a function and returns control to the
calling function. Execution resumes in the calling function at the point immediately
following the call. A return statement can also return a value to the calling function. See
Return Type for more information.
Syntax
return expression ;
The value of expression, if present, is returned to the calling function. If expression is
omitted, the return value of the function is undefined. The expression, if present, is
evaluated and then converted to the type returned by the function. If the function was
declared with return type void, a return statement containing an expression generates a
warning and the expression is not evaluated.
B. C. A. First Year 23
Programming in C
* Function Calling :
While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
For example −
examples
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
B. C. A. First Year 24
Programming in C
We have kept max() along with main() and compiled the source code. While running the
final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function −
2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
*Recursion:
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is
called a recursive call of the function.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
B. C. A. First Year 25
Programming in C
* Storage Classes:
1) Automatic Variable:
By default all the local variables inside the function are automatic, because they
allocate memory automatically as a function is entered and release the memory space as
soon as it leaves the function, means it‟s life is till the function is active. Automatic
variables are declared using the keyword „auto‟. By default the storage class of local
variable is „auto‟. So it is not necessary to specify „auto‟ keyword before the variable
name.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
auto int a, b, Add;
clrscr();
printf(“Enter values for a & b: ”);
scanf(“%d%d”,&a, &b);
Add = a + b;
printf(“\n Addition is %d”, Add);
getch();
}
2) Register Variables:
These type of variables are stored in CPU register. These are accessed
fastly as compared to variables which are stored in memory. The scope of „register
variable‟ is till the function is active and we cannot access the address of such type of
variables. The keyword „register‟ is used to declare such type of variable and its default
value is garbage.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
register int a = 0, b = 1, n = 5;
clrscr();
printf(“Enter values for a & b: ”);
scanf(“\n %d \n %d”, &a, &b);
fibo(a, b, n);
getch();
}
fibo(int a, int b, int n)
{
int c;
if (c = 0)
return;
c = a + b;
printf(“\n Fibonacci Series is %d”, c);
B. C. A. First Year 26
Programming in C
a = b;
b = c;
fibo (a, b, n-1);
}
3) Static Variables:
When we declare any variables as „static‟, then the contents of variables
will be returned throughout the program, means the values of such type of variables
persist (carry forward) between number of calls of same function. The scope of such
variable is local to the function in which it is declared but its life is till the program. The
default value of such variable is „zero‟. The keyword „static‟ is used for such type of
variable declaration.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
clrscr();
for (a = 1; a < = 5; a++)
{
print( );
}
}
print( )
{
static int p = 1;
printf(“\t %d”, p);
p + +;
}
4) External Variables:
These are declared outside of „main()‟ function, means at the top of the
program and this variable will have the same data type throughout the function. This
variable can also be referred as „global variable‟ and its life is till the program is active.
We can access the value of this variable in any function. The keyword „extern‟ is used to
declare such type of variable.
Program:
#include<stdio.h>
#include<conio.h>
extern float rate = 0.04;
main()
{
float amount, dur;
clrscr();
printf(“\n Interset rate = %f”, rate);
printf(“Type Amount and Duration and Rate:”);
B. C. A. First Year 27
Programming in C
scanf(“%f%f”, &amount, &dur);
loan(amount, rate);
}
loan(float amt, float d)
{
float total;
total = amt + ((amt * rate) * d);
printf(“\n Total Amount is = %f”, total);
}
* Recursion:
When a function call itself directly or indirectly in its definition, then such
function is called as „recursion‟ or „recursion function‟. While we can write recursive
function, then it is better to write or specify some conditions to exit form the function. If
you don‟t specify the „exit‟ condition, then at that time the function is executed infinite
times and no result is obtained. While writing recursive function definition „exit‟
condition is written before function calls itself. When recursion execution function, first
time it calls itself and at that time the remaining commands which are not executed,
pending in a stack and when a function is executed second time and called itself again,
then at that time the commands which are not executed, again pending in stack and the
process is continuous, till the „exit‟ condition is not match in function. when the current
execution of function is stopped, then the command, which are placed at stack is
executed on „last in first out‟ principle, which are stored last time are executed first time
and the command which are placed first are executed lastly.
Syntax:
main( )
{
..
..
abc( );
..
..
}
abc( )
{
..
..
abc( );
..
..
}
Program:
#include <stdio.h>
#include<conio.h>
main ()
{
int fact, num;
B. C. A. First Year 28
Programming in C
clrscr( );
printf ("Type any number: ”);
scanf(“%d”, &num);
fact = factorial(num);
printf(“\n Factorial is %d”, fact);
}
factorial(int n)
{
if (n == 1)
{
return 1;
}
retrun (n * factorial(n – 1));
}
* Return Keyword:
A function may or may not send back any value to the calling function. If it does,
it is done through the „return‟ statement. “This statement is used to terminate the
execution of current function and return a value or results to its calling function.” The
„return‟ statement may also be used to exit from function without returning a value. The
„return‟ statement is placed at the end of the function to stop the execution of current
function. When the „return‟ statement occurs in a program, then the execution of current
function is terminated and control pass to the calling function. The „return‟ statement can
be used with two ways:
Syntax:
return;
This syntax does not return any value. It acts as the closing brace of the function.
For ex.
if (error)
return;
return(expression);
This syntax returns value of the expression.
For ex.
mul(x,y)
int x,y;
{
int p;
p = x * y;
return(p);
}
This example returns the value „p‟ which is the product of x and y.
B. C. A. First Year 29
Programming in C
Unit IV
Arrays
* Arrays:
Array is used to store more than one values of same data type under a single
variable name in a continuous memory location. Each value has a unique index number,
first value is stored at index number zero. The address of first index value is referred as
base address. To access any value in a array, we have to provide array name followed by
index number in square bracket.
Syntax:
Date_Type ArrayName[Size of Array];
1) One Dimensional Array:
It consists of single row and multiple columns. While accessing any element from
this type of array, we have to first provide „Array name‟ followed by „Element number or
Index number or Subscript number‟. It can be represented in memory as follows:
Index Number 0 1 2 3
2 6 9 15
Memory Address 100 101 102 103
Declaration:
While declaring one dimensional array we have to specify data type followed by
array name followed by size of array in square bracket ([ ]).
Syntax:
Date_Type ArrayName[Size of Array];
Example:
int A[4]
Initialization:
We can assign the values of array elements at the time of declaration of array. All
values are enclosed within curly brackets and two values are separated by comma.
Syntax:
Date_Type ArrayName[Size of Array] = {Set of Values};
Example:
int A[4] = {20, 30, 40, 50};
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int arr[5], p;
clrscr();
printf(“Type any five numbers: \n”);
for(p=0;p<=4;p++)
{
scanf(“%d”,&arr[p]);
}
printf(“\n Reverse order is: ”);
B. C. A. First Year 30
Programming in C
for(p=4;p>=0;p--)
{
printf(“\n %d”, arr[p]);
}
getch();
}
B. C. A. First Year 31
Programming in C
for(c=0;c<=2;c++)
{
printf(“\n Enter values for Row = %d, Column = %d” r+1, c+1);
scanf(“%d”, &mat[r][c]);
}
}
printf(“\n Matrix is in Inverse Form:”);
for(r=0;r<=2;r++)
{
printf(“\n”);
for(c=0;c<=2;c++)
{
printf(“\t %d”, mat[c][r]);
}
}
getch();
}
1 2 7 8 13 14
3 4 9 10 15 16
5 6 11 12 17 18
Declaration:
While declaring three dimensional array we have to specify data type followed by
array name followed by element number followed by total number of rows followed by
total number of columns in each row. Element, Row and Column numbers are specified
in separate square brackets ([ ]).
Syntax:
Date_Type ArrayName[Element][Row][Column];
Example:
B. C. A. First Year 32
Programming in C
int A[2][3][3];
Initialization:
We can assign the values of array elements at the time of declaration of array.
Syntax:
Date_Type ArrayName[Element][Row][Column] =
{
{
{0th Row Elements},
{1st Row Elements},
…….
…….
},
{
{0th Row Elements},
{1st Row Elements},
…….
…….
},
……..
……...
};
Example:
int A[3][3] = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
},
{
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
}
}
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int mat[3][3][3], r, c, e;
clrscr();
for(e=0;e<=1;e++)
{
if (e = = 0)
printf(“Type 1st Matrix Elements: \n”);
B. C. A. First Year 33
Programming in C
else
printf(“Type 2st Matrix Elements: \n”);
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
scanf(“%d”, &mat[e][r][c]);
}
}
}
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
mat[2][r][c] = mat[0][r][c] + mat[1][r][c];
}
}
printf(“Result : \n”);
for(r=0;r<=2;r++)
{
printf(“\n”);
for(c=0;c<=2,c++)
{
printf(“\t %d”, mat[2][r][c]);
}
}
}
* Pointers:
This is used to hold the address of another variable as a value of its own. Pointer
may be of integer, character and float type. It occupies memory according to the data
type i.e. if the pointer as integer, then it occupies two bytes. Pointer variable can hold the
address of variable whose data type is same as pointer variable data type. Pointer variable
can be declared like other variable with one difference i.e. it must be preceded with „*‟.
Syntax:
data_type *variable_name;
Pointer variables are operated using following two operators.
(a) Pointer Operator: This operator can be represented by combination of „*‟ with a
variable name. This is also called as „Value at address operator‟. This operator is used to
access the value, which is to store on a memory location, which is hold by pointer
variable.
For example: Suppose, „a‟ is a pointer variable which hold memory address 100, then
„*a‟ displays the value stored at memory location 100.
(b) Address Operator: Address operator is represented by a combination of „&‟ with a
variable. This operator is used to hold the address of specified variable in a pointer
variable.
B. C. A. First Year 34
Programming in C
For example: ptr = & a;
Where, „ptr‟ is a pointer variable and „a‟ is a ordinary variable.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a = 5, *p;
*p = &a;
clrscr();
printf(“\n Value of a = %d”, a);
printf(“\n Address of a = %d”, &a);
printf(“\n Value of p = %d”, p);
printf(“\n Address of p = %d”, &p);
printf(“\n Pointer Value of p = %d”, *p);
}
* Pointer To Pointer:
When a pointer variable points to the address of another pointer variable then it is
called as pointer to pointer. The data type of pointer to pointer and pointer variable must
be same. It is declare as follows:
Syntax: data_type **variable_name;
For ex. int *p, **pp;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int a = 5, *p, **pp;
clrscr();
p = &a;
pp = &p;
printf(“\n a = %d”, a);
printf(“\n &a = %d”, &a);
printf(“\n p = %d”, p);
printf(“\n &p = %d”, &p);
printf(“\n *p = %d”, *p);
printf(“\n pp = %d”, pp);
printf(“\n &pp = %d”, &pp);
printf(“\n *pp = %d”, *pp);
printf(“\n **pp = %d”, **pp);
}
B. C. A. First Year 35
Programming in C
int value[4] = {2,4,6,8};
Suppose the base address [0th element address] of this array is 100. So 0th element
value can be accessed as „value[0]‟ or „*(value + 0)‟ or „*value‟. In „*value‟ notation we
skip index number because by default array contains base address i.e. 0th element address.
In „*(value + 0)‟ provide the contents of 0th element. So to access 3rd element from array,
any one of the notation used: value[2] or *(value + 2) or *(2+value) or 2[value].
In the 2nd and 3rd notation we have add number 2 in value. The base address of
value is 100, so after adding 2 in it, it becomes 104 (2 byte for 1 number). So, all the
above notations provide the answer is 6.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int value[4] = {100,200,300,400};
clrscr();
printf(“\n %d”, value[1]);
printf(“\n %d”, *(value + 1));
printf(“\n %d”, *(1 + value));
printf(“\n %d”, 1[value]);
}
B. C. A. First Year 36
Programming in C
variable. Then at that time we have to pass the address of variable from „calling function‟
and „called function‟ receive these address in pointer variable, so if some changes are
made in this variable or pointer then these changes are also reflected in calling function
variable such function calls are called as „call by reference‟.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int arr[5] = {10,20,30,40,50};
sum(&arr[0], 5);
}
sum(int *p, int n)
{
int i, sum = 0;
for(i=1;i<=n,i++)
{
sum = sum + *p;
p++;
}
printf(“\n Sum = %d”, sum);
}
B. C. A. First Year 37
Programming in C
Unit V
Strings
* Strings:
Collection of two or more characters are called strings. When we declare array of
character type then it is called as string. In string we can store alphabet, digits and special
symbols.
Declaration:
While declaring string we have to specify its size to store a string.
Syntax: char string[size];
For example: char str[20];
Here, we declare a string variable „str‟ of size 20 characters.
Initialization:
While declaring string we can also initialize some text or value to it.
Syntax: char string[size] = “text”;
For example: char str[20] = “Udaygiri College”
Here, we declare a string variable „str‟ of size 20 characters and assign the text
“Udaygiri College” to it.
B. C. A. First Year 38
Programming in C
}
3) strcmp( ): This function compares two strings and returns the value. If both strings are
same, then it return value zero. If first string is greater than second string, it returns value
greater than 0. If first string is less than second string, it returns value less than 0. It is
case sensitive. If we wish to ignore the case difference then we have to use „strcmpi( )‟
instead of „strcmp( )‟.
Syntax: strcmp(string1, string2);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char str1[10], str2[10];
int r;
clrscr();
printf(“Type first String: ”);
scanf(“%s”, str1);
printf(“Type second String: ”);
scanf(“%s”, str2);
r = strcmp(str1, str2);
if (r = = 0)
printf(“Both Strings are Same.”);
else
if (r >= 1)
printf(“First String is greater than Second String”);
else
if (r <= –1)
printf(“Second String is greater than First String”);
getch();
}
4) strcat( ): This function appends or add second string, at the end of first string.
Syntax: strcat(string1, string2);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char str1[10], str2[10],str3[20];
int r;
clrscr();
printf(“Type first String: ”);
scanf(“%s”, str1);
printf(“Type Second String: ”);
scanf(“%s”, str2);
B. C. A. First Year 39
Programming in C
strcpy(str3, str1);
strcat(str3, str2);
printf(“Third String is %s”,str3);
getch();
}
5) strrev( ): This function reverse the given string contents and store it again in same
string variable.
Syntax: strrev(string);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char str1[10];
clrscr();
printf(“Type String: ”);
scanf(“%s”, str);
strrev(str);
printf(“Reverse Order is %s”,str);
getch();
}
6) strchr( ): This function finds the first occurrence of given character in a given string.
if search is successful then it returns the memory address of first occurrence of given
character in a given string. If search is unsuccessful then it returns value NULL.
Syntax: strchr(string, character);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char str[10] = “Udaygiri”, *p;
p = strchr(s, „y‟);
if (p!=NULL)
printf(“\n Given character is present at position: %d”, p–s);
else
printf(“(“\n Given character is not present in a string.”);
}
B. C. A. First Year 40
Programming in C
char str1[10];
clrscr();
printf(“Type String in Uppercase: ”);
scanf(“%s”, str);
printf(“String in Lowercase is %s”, strlwr(str));
getch();
}
10) strncat( ): This function appends or add the specified part (specified number of
characters from starting) of second string, at the end of first string.
Syntax: strncat(string1, string2, number of characters);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char str1[20] = “Udaygiri”, str2[10] = “College”;
printf(“\n str1 = %s”, str1);
printf(“\n str2 = %s”, str2);
strncat(str1, str2,10);
printf(“\n Now String1 is %s”,str1);
getch();
}
11) strncpy( ): This function copies the specified part (specified number of characters
from starting) of source string into target string.
Syntax: strncpy(target_string, source_string, number of characters);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
B. C. A. First Year 41
Programming in C
char str1[20] = “Udaygiri College”, str2[10];
printf(“\n String 1 = %s”, str1);
strncpy(str2, str1, 10);
printf(“\n String 2 is %s”,str2);
getch();
}
B. C. A. First Year 42
Programming in C
Unit VI
Structures, Unions and File Handling
* Creating Structures:
This is used to combine different items of different data type, grouped together.
All the data items are stored in continuous memory location. Each data item in a structure
is called as „member‟. Each member in a structure occupies separate memory. It is
mainly used for DBMS (Data Base Management System) purpose. To access any
member of structure, we have to first write structure variable name, followed by dot (.)
followed by member name.
The structure declaration forms a template that may be used to create structure
objects. The variable that make up the structure is called „members‟. The declaration of a
structure specifies the grouping of various data items into a single unit without assigning
any memory to them.
Syntax:
struct structure_name
{
member declaration with proper data type;
};
This declaration starts with keyword „struct‟ followed by a structure name. the
members of the structure enclosed between the curly brackets and they can be of same or
different data types. The closing curly bracket is terminated with a semicolon.
* Initializing Structure:
We can initialize values to structure members at the time of declaration of
structure variable.
Syntax:
struct structure_name variable = {value1, value2, ……};
For example: struct student s = {“rahul”,”bca”,1};
Program:
#include<stdio.h>
#include<conio.h>
main()
{
/* Structure Declaration */
struct student
{
char name[10], class[10];
int roll;
};
/* Declaring a structure variable and initializing values to structure
members */
struct student s = {“Rahul”, “BCA”, 2};
/* Printing Structure Member Values */
printf(“\n %s \t %s \t %d”, s.name, s.class, s.roll);
}
B. C. A. First Year 43
Programming in C
* Accessing Structure Members:
To access any member of a structure, first we have to declare a variable to
represent the structure. When we declare a variable for structure then at that time the
required memory is occupied for the structure members and we can access these
members in a program anywhere by providing first structure variable name followed by
dot (.) followed by member name. we can assign a variable name to structure in two ways
as:
(a) While we declare the structure assign a name after closing curly bracket.
Syntax:
struct structure_name
{
Member declaration with proper data type;
}variable_name;
(b) Assign a name separately using following syntax:
Syntax:
struct structure_name variable1, variable2, .. … .. variableN;
If we declare more than one variable for structure then each variables
occupies separate memory space for each member. In such case we can not access
the values of one variable member using another variable.
* Array of Structure:
When a variable of structure is declared as array type then it is called as array of
structure. It is used to store same piece of information for more than one time. While
accessing any member first we have to write structure variable name followed by index
number followed by dot (.) followed by member name.
Syntax:
struct structure_name
{
Member declaration;
}
struct sturcutre_name variable[number];
Program:
#include<stdio.h>
#include<conio.h>
main()
{
/* Structure Declaration */
struct student
{
char name[10], class[10];
int roll;
};
struct student s[4];
int a;
printf(“Type Student Name, Class and Roll Number:”);
B. C. A. First Year 44
Programming in C
for(a=0;a<=3;a++)
{
scanf(“%s%s%d”, s[a].name, s[a].class, &s[a].roll);
}
for(a=0;a<=3;a++)
{
printf(“\n%s\t%s\t%d”, s[a].name, s[a].class, s[a].roll);
}
}
Program:
#include<stdio.h>
#include<conio.h>
main()
{
struct date
{
int day, month, year;
};
struct student
{
char name[10], class[10];
int roll;
struct date d;
B. C. A. First Year 45
Programming in C
}s;
clrscr();
printf(“Type Student Name, Class, Roll Number and Date of
Birth:”);
scanf(“%s%s%d%d%d%d”, s.name, s.class, &s.roll, &s.d.day, &s.d.month,
&s.d.year);
printf(“\n%s\t%s\t%d\t%d\t%d\t%d”, s.name, s.class, s.roll, s.d.day,
s.d.month, s.d.year);
}
* Union:
This is used to store different items of different data type in same pieces of
memory. The size of union is equal to the maximum size occupied by its member. The
values of one member is stored in a memory at a time. When we store another member
values, the first member values are removed from the memory and at his place, new
member values are stored. To access any member of union, we have to first write union
variable name, followed by dot (.) followed by member name.
B. C. A. First Year 46
Programming in C
Syntax:
union union_name
{
member declaration with proper data type;
}variable_name;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
/* Union Declaration */
union student
{
char name[10], class[10];
int roll;
};
union student s;
printf(“Type Student Name:”);
scanf(“%s”, s.name);
printf(“Type Student Class:”);
scanf(“%s”, s.class);
printf(“Type Student Roll Number:”);
scanf(“%d”, &s.roll);
}
A) fseek( ):
This function is used to move the file pointer to a specified byte position in a file.
It is generally used to move the file pointer from one record to other.
Syntax:
fseek (file pointer, offset, position);
where, „offset‟ is a number or variable which specifies the number of bytes to be
moved from the location specified by „position‟. If offset value is positive means move
forward and if it is negative means move backward. „position‟ represents possible values
are as follows
B. C. A. First Year 47
Programming in C
Value Meaning
0 or SEEK_SET Beginning of file
1 or SEEK_CUR Current position
2 or SEEK_END End of file
B) ftell( ):
By using this function, we can know where the file pointer is currently position. It
returns the position as long integer, which is an offset from the beginning of the file.
Syntax:
Variable_name = ftell (file pointer);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *p;
struct employee
{
char name[20], post[20];
int salary;
}e;
int a;
clrscr();
p = fopen(“emp.txt”, “r”);
fseek(p, 42, SEEK_CUR);
printf(“\n Second record starting address = %u”, ftell(p));
printf(“\n Name \t Post \t Salary \n”);
fread(&e, sizeof(e), 1, p);
printf(“\n %s\t%s\t%d”, e.name, e.post, e.salary);
fclose(p);
}
B. C. A. First Year 48
Programming in C
File Opening Modes (Access Modes):
(a) r: Searches the file. If the file exist, then load it into memory and read the contents
from file. If the file does not exist, it returns null.
(b) w: To write the contents to the file. It will first search the file. If the file exist, it
contents are overwritten. If the file does not exist, then the new file is created. It returns
null if it enable to return a file.
(c) a: It appends new contents at the end of a file. It will first search the file. If the file
exists, then file is loaded into the memory and the contents are loaded at the end of file. If
file does not exist, then the new file is created. It returns null, if it is enable to open a file.
2) fclose( ):
This function is used to close the file, which is opened under the specified pointer
variable. It free the link used by the particular file and the associate buffers.
Syntax: fclose(file_pointer);
For example: fclose(fp);
3) fputc( ):
This function is used to write a single character in a file which is opened under the
specified file pointer.
Syntax: fputc(variable_name, file_pointer);
Program: Write contents in a file “info.txt”.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *p;
char ch;
clrscr( );
p = fopen(“info.txt”, “w”);
printf(“Type # to Save and Exit from the File.”);
while(ch != ”#”)
{
ch = getche( );
fputc(ch, p);
}
fclose(p);
}
4) fgetc( ):
This function is used to read a single character from a file which is opened under
the specified file point.
Syntax: variable_name = fgetc(file_pointer);
Program: To Read contents in a file “info.txt” one character at a time.
#include<stdio.h>
#include<conio.h>
main()
{
B. C. A. First Year 49
Programming in C
FILE *p;
char ch;
clrscr( );
p = fopen(“info.txt”, “r”);
while(ch != EOF)
{
ch = fgetc(p);
putch(ch);
}
fclose(p);
}
5) fputs( ):
This function is used to write a string in a file which is opened under the specified
file pointer.
Syntax: fputs(string, file_pointer);
Program: Write contents in a file “info.txt” one line at a time.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
FILE *p;
char str[80];
clrscr( );
p = fopen(“info.txt”, “w”);
printf(“Type string: (Stop to Save and Exit from File):”);
while(1)
{
gets(str);
if (strcmp(str, “stop”) = = 0)
break;
fputs(str, p);
fputs(“\n”, p);
}
fclose(p);
}
6) fgets( ):
This function is used to read a specified number of characters from a file which is
opened under the specified file pointer and store it in a corresponding string variable.
This function reads a string from a file.
Syntax: fgets(string_variable, number, file_pointer);
Program: Read contents in a file “info.txt” one line at a time.
#include<stdio.h>
#include<conio.h>
#include<string.h>
B. C. A. First Year 50
Programming in C
main()
{
FILE *p;
char str[80];
clrscr( );
p = fopen(“info.txt”, “r”);
while(fgets(str,89,p))
{
printf(“%s”, str);
}
fclose(p);
}
7) fwrite( ):
This function is used to store the information, which is in the form of structure in
a file as a record.
Syntax: fwrite(address of structure variable name, size of structure, number of
record to write, file pointer);
Program: Write 5 record contents in a file “emp.txt”.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
FILE *p;
struct employee
{
char name[20], post[20];
int salary;
}e;
int a;
clrscr( );
p = fopen(“emp.txt”, “w”);
printf(“Type 5 Employee Name, Post and Salary:”);
for(a=1; a<=5; a++)
{
scanf(“%s%s%d”, e.name, e.post, &e.salary);
fwrite(&e, sizeof(e), 1, p);
}
fclose(p);
}
8) fread( ):
This function is used to read the information from the file, which is in the form of
record & store it in a structure.
Syntax: fread(address of structure variable name, size of structure, number of
record to read, file pointer);
B. C. A. First Year 51
Programming in C
Program: Read all record contents in a file “emp.txt”.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
FILE *p;
struct employee
{
char name[20], post[20];
int salary;
}e;
int a;
clrscr( );
p = fopen(“emp.txt”, “r”);
printf(“Type Employee Name, Post and Salary:”);
while(fread(&e, sizeof(e), 1, p))
{
printf(“\n%s\t%s\t%d”, e.name, e.post, e.salary);
}
fclose(p);
}
B. C. A. First Year 52