0% found this document useful (0 votes)
10 views25 pages

IP-Unit-5-2023-24

C program

Uploaded by

seethalsomisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views25 pages

IP-Unit-5-2023-24

C program

Uploaded by

seethalsomisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT- V

FUNCTIONS:

 A function is self contained program segment or block of code(or statements) that


performs a specific and well defined task.
 This allows you to break your program down into manageable pieces and reuse
your code.
The advantages of functions are:
1. Function makes the lengthy and complex program easy and in short forms. It
means large program can be sub-divided into self-contained and convenient
small modules having unique name.
2. The length of source program can be reduced by using function, by using it at
different places in the program according to the user’s requirement.
3. By using function, memory space can be properly utilized. Also less memory is
required to run program if function is used.
4. Function increases the execution speed of the program and makes the
programming simple.
5. It removes the redundancy (occurrence of duplication of programs) i.e. avoids
the repetition and saves the time and space.
6. Debugging (removing error) becomes very easier and fast using the function
sub-programming.
7. Testing (verification and validation) is very easy by using functions.

Types of Functions :
The functions are classified into standard functions and user-defined
functions.
Standard Functions :
 In simple words, the standard functions can be defined as "the ready made
functions defined by the system to make coding more easy".
 The standard functions are also called as library functions or pre-defined functions
or built in functions.
 A user can not understand the internal working of the standard functions and can
not be modified but can only use all standard functions.
 C language provides a rich set of standard library functions whose definitions have
been written and are ready to use.
 The user must include the prototype declarations(header files) to use the standard
library functions.
 The some of standard functions are scanf(), printf(), sqrt(), abs(), log(), sin(), pow()
etc.

User defined functions:


 User defined functions are the functions defined by the user according to the
requirements.
 The user understands the internal working of the function.
I B.Tech C StudyMaterial 1 D.Madhu Babu, M.Tech.
 The main() functions is also a user defined function except that the name of the
function, the number of arguments, and the argument types are defined by the
language.

 You can write as many functions as you like in a program as long as there is only one
main ().
 As long as these functions are saved in the same file, you do not need to include a
header file. They will be found automatically by the compiler.

The general form of function definition is as follows:


Return_typefunction_name( parameters_list)
{
Local variable declaration; /* with in the function */
Executable statements;
----------
----------
return (expresion);
}

 Return_type specifies the type of value that the function's return statement
returns.If nothing is returned to the calling function, then data type is void.
 function_name is a user-defined function name. It must be a valid C identifier.
 Parameter list declares the variables that will receive tha data sent by the
calling function. They serve as input data to the function to carry out the specified
task. Since they represent actual input values, they are often rerred to as formal
parameters.
 returnis a keyword used to send the output of the function, back to the calling
function. It is a means of communication from the called function to the calling
function. There may be one or more return statements. When a return is
encountered, the control is transferred to the calling function.

I B.Tech C StudyMaterial 2 D.Madhu Babu, M.Tech.


The following figure shows the flow through a function:
 All the statements placed
between the left brace
and the corresponding
right brace constitute the
body of a function.

{ ……>is the beginning
of the function.
} ……..>is the end of
function.

Function Declaration(or Function Prototype):


 Like variable, all functions in a C program must be declared, before they are
invoked.
 Function declarations is also called as function prototype.
 It is declared in the declaration part of the main program.
 The default return value from a function is always an integer.
 If the function is returning a value other than an integer, it must be declared with
the data type of the value it returns.
The general form of function prototype is as follows:
Return_typefunction_name(parameter_list);
This is very similar to the function header line except the terminating semicolon.
For example: long int factorial(int n);
Function Call :
 A function can be called by simply using the function name followed by a list of
actual paramenter(or arguments), if any , enclosed in parentheses.

The general form of a function call is as follows:


function_name (actual parameters);

Function Parameters(or Arguments):


 Function parameters are the means of communication between the calling and
called functions. They can be classified into Actual parameters and Formal
parameters.

I B.Tech C StudyMaterial 3 D.Madhu Babu, M.Tech.


The Actual parameters, often known as arguments, are specified in the function call.
These are written within the parentheses followed by the name of the function. These
are accepted in the main program (or calling function).
The Formal parameters(commonly called parameters) are the parameters given in the
function declaration and function definition. These are not the accepted values but they
receive values from the calling function.
Example:
/* Sending and receiving values between functions */

main( )
{
int a, b, c, sum ;
printf( "\nEnter any three numbers " ) ;
scanf( "%d %d %d", &a, &b, &c ) ;
sum = calsum( a, b, c ) ;
printf( "\nSum = %d", sum ) ;
}

calsum( int x, int y, int z )


{
int d ;
d=x+y+z;
return ( d ) ;
}
Output...:
Enter any three numbers 10 20 30
Sum = 60
There are a number of things to note about this program:
(a) In this program, from the function main( ) the values of a, b and c are passed on to
the function calsum( ), by making a call to the function calsum( ) and mentioning a,
b and c in the parentheses:
sum = calsum( a, b, c ) ;
In the calsum( ) function these values get collected in three variables x, y and z:
calsum( int x, int y, int z )

(b) The variables a, b and c are called ‘actual arguments’, whereas the variables x, y
and z are called ‘formal arguments’.
(c) Any number of arguments can be passed to a function being called.
(d) However, the type, order and number of the actual and formal arguments must
always be same.
(e) Instead of using different variable names x, y and z, we could have used the same
variable names a, b and c. But the compiler would still treat them as different
variables since they are in different functions.
There are two methods of declaring the formal arguments. The one that we have used
in our program is known as ANSI method and is more commonly used these days.
calsum( int x, int y, int z )
Another method is,
calsum( x, y, z )
I B.Tech C StudyMaterial 4 D.Madhu Babu, M.Tech.
int x, y, z ;
{
// Body of the function
}
This method is known as Kernighan and Ritchie (or just K & R) method.
(f) In the above program, however, we want to return the sum of x, y and z. Therefore,
it is necessary to use the return statement. The return statement serves two
purposes:

1.On executing the return statement it immediately transfers the control back to
the callingprogram.
2. It returns the value present in the parentheses after return, to the calling
program. In
the above program the value of sum of three numbers is being returned.
Example:
fun( )
{
char ch ;
printf( "\nEnter any alphabet " ) ;
scanf( "%c", &ch ) ;
if ( ch>= 65 &&ch<= 90 )
return ( ch ) ;
else
return ( ch + 32 ) ;
}
In this function different return statements will be executed depending on
whether ch is capital or not.

(g) Whenever the control returns from a function some value is definitely returned. If a
meaningful value is returned then it should be accepted in the calling program by
equating the called function to some variable. For example,
sum = calsum( a, b, c ) ;

(j) If the value of a formal argument is changed in the called function, the corresponding
change
does not take place in the calling function. For example,

main( )
{
int a = 30 ;
fun ( a ) ;
printf( "\n%d", a ) ;
}
fun ( int b )

I B.Tech C StudyMaterial 5 D.Madhu Babu, M.Tech.


{
b = 60 ;
printf( "\n%d", b ) ;
}

The output of the above program would be: 60


30
 Thus, even though the value of bis changed in fun( ), the value of a in main( )
remains unchanged. This means that when values are passed to a called function
the values present in actual arguments are not physically moved to the formal
arguments; just a photocopy of values in actual argument is made into formal
arguments.

Category of functions:

We have some other type of functions where the arguments and return value may be
present or absent. Such functions can be categorized into:

1. Functions with no arguments and no return value.


1. Functions with arguments and no return value.
2. Functions with no arguments but return value.
3. Functions with arguments and return value.

1. Functions with no arguments and no return value:


 Here, no arguments (or parameters) are passed to the called function from the
calling function and, no value is returned to the calling function from called
function.
 Hence, there is no data transfer between the calling function and the called
function. This is depicted in the following figure :
Calling Function Called Function

Void main() No arguments passed Void sum()


{ to called function {
----- ------------
------- ------------
Sum(); C=a+b
--------- ------------
------------
} }
No value is returned
to calling function

Example:
The following program illustrates the function with no arguments and no return value.

# include <stdio.h>
main ()

I B.Tech C StudyMaterial 6 D.Madhu Babu, M.Tech.


{
Void sum();
Clrscr();
Sum();
Getch();
}
void sum() /*no return value */
{
Int a=10,b=20,c;
C = a + b;
printf (“\nThe sum of Two numbers is ….:%d” ,c)
}
Output:

The sum of Two numbers is ….: 30

2.Functions with arguments and no return value:


 Here, arguments (or parameters) are passed to the called function from the
calling function but no value is returned to the calling function from called
function.
 It is one-way data communication between the calling function and the called
function. This is depicted in the following figure :

Calling Function Called Function

Void main() arguments passed to Void sum( int a, int b)


{ called function {
----- ------------
------- ------------
Sum(a,b); C=a+b
--------- ------------
No value is returned ------------
} to calling function }

Example:
The following program illustrates the function with arguments and no return value.
# include <stdio.h>
main ()
{
Int a=10,b=20;
Void sum(int a, int b);
Clrscr();
Sum(a,b);
Getch();
}

void sum(int a , int b) /*no return value */


{
Int c;
C = a + b;

printf (“\nThe sum of Two numbers is ….:%d” ,c)


}
Output:

I B.Tech C StudyMaterial 7 D.Madhu Babu, M.Tech.


The sum of Two numbers is ….: 30

Functions with no arguments and with return value:


 Here, no arguments (or parameters) are passed to the called function from the
calling function but value is returned to the calling function from called function.
 It is also a one-way data communication between the calling function and the
called function. This is depicted in the following figure :

Calling Function Called Function

Void main() Int sum( )


No arguments passed
{ {
to called function
----- ------------
------- ------------
C=Sum( ); C=a+b
--------- ------------
Return ( c )
} value is returned to ------------
calling function }

Example:
The following program illustrates the function with arguments and no return value.
# include <stdio.h>
main ()
{
Int c;
int sum();
Clrscr();
C=Sum();
printf (“\nThe sum of Two numbers is ….:%d” ,c)
Getch();
}

int sum() /* return value */


{
Int a=10,b=20,c;
C = a + b;
Return ( c );

}
Output:
The sum of Two numbers is ….: 30

4.Functions with arguments and with return value:


 Here, arguments (or parameters) are passed to the called function from the
calling function and value is returned to the calling function from called function.
 Hence, there is data transfer between the calling function and the called function.
This is depicted in the following figure :

Calling Function Called Function

Void main() arguments passed to Int sum(int a , int b )


called function {
I B.Tech{ C StudyMaterial 8 D.Madhu Babu, M.Tech.
----- ------------
value is returned to
calling function

Example:
The following program illustrates the function with arguments and no return value.

# include <stdio.h>
main ()
{
Int a=10,b=20,c;
int sum();
Clrscr();
C=Sum(a,b);
printf (“\nThe sum of Two numbers is ….:%d” ,c)
Getch();
}
int sum(int a, int b) /* return value */
{
Int c;
C = a + b;
Return ( c );
}

Output:
The sum of Two numbers is ….: 30

Parameter passing Techniques (ormechanisms):


A method of information interchange between the calling function and called function is
known as parameter passing. There are two methods of parameter passing:

1. Call by Value
2. Call by Address(or Reference)

1.Call by Value:
 The call-by-value method copies the value of an actual argument into the formal
parameter of the function.
 Therefore, changes made by the function to the formal parameters have no effect
on the actual arguments in the calling function.

Example:

# include <stdio.h>

main ()
I B.Tech C StudyMaterial 9 D.Madhu Babu, M.Tech.
{
int a=10, b=20;
void swap (int x, int y); /* function prototype */
printf(“\nBy using Call by Value, Before swapping , values of A and B are :%4d
%4d”,a,b)
swap (a, b); /* values passed */
printf(“\nBy using Call by Value, After swapping , values of A and B are :%4d
%4d”,a,b)
getch();
}

void swap (int a, int b) /* function definition */


{
int temp;

temp = a;
a = b;
b = temp;
}

Output :

By using Call by Value, Before swapping , The values of A and B are …: 10 20

By using Call by Value, After swapping , The values of A and B are ……: 10 20

In the above program, the variables a and b are assigned the values of 10 and 20 in the
main. During the execution of the ‘swap’function , the values of aand b are exchanged,
but the values of the actual arguments a and b in the main function remains the same
as prior to the execution of the function call.

Call by Address(or Reference) :


 The call by Address (or Reference) method copies the address of an argument into
the formal parameter.
 Therefore any changes made to the formal parameters causes change in actual
parameters also .
 Call by Address(or reference) is achieved by passing a pointer as the argument. Of
course, in this case, the parameters must be declared as pointer types.
The following program demonstrates this:

Example:

# include <stdio.h>
Void main ()
{
int a=10, y=20;
void swap (int *x, int *y); /* function prototype */
printf(“\nBy using Call by Address,Beforeswapping,values of A and B are:%4d
%4d”,a,b
I B.Tech C StudyMaterial 10 D.Madhu Babu, M.Tech.
swap (&a, &b); /* addresses passed */
printf(“\nBy using Call by Address, After swapping , The values of A and B are …:
%4d
%4d”,a,b

void swap (int *x, int *y)


{
int temp;

temp = *x;
*x = *y;
*y = temp;
}

Output :

By using Call by Address, Before swapping , The values of A and B are …: 10 20

By using Call by Address, After swapping , The values of A and B are ……: 20 10

In the above program, the variables a and b are assigned the values of 10 and 20 in the
main. The values of a and b in main can be changed during the execution of the
‘swap’function by using their addresses which are copied in formal parameters x and y.
Hence the values of a and b in main are 20 and 10(swapped).

Arrays and Functions:


 Generally, We can pass either its individual elements or an entire array as
an argument to the functions.
 Array elements can be passed to a function by calling the function by
value, or by address(or by reference).
 In the call by value we pass values of array elements to the function,
whereas in the call by address (or by reference) we pass address of the
array to the function.
Passing individual elements of an arryay as an argument (Call-by-
Vallue) :
 An array element used as an argument is treated like any other simple
variable, as shown in the example below:
Example:
I B.Tech C StudyMaterial 11 D.Madhu Babu, M.Tech.
/* Demonstration of call by value */
main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 88, 90 } ;
void display(int m);
printf(“\n Marks…:”);
for ( i = 0 ; i<= 6 ; i++ )
display ( marks[i] ) ;
}

Void display ( int m )


{
printf( "%4d ", m ) ;
}
Output :
Marks…..: 55 65 75 56 78 88 90

Here, we are passing an individual array elements at a time to the function


display( ) and getting it printed in the function display( ). Note that since at a
time only one element is being passed, this element is collected in an ordinary
integer variable m, in the function display( ).

Passing an entire array as an argument (Call-by-Address or Reference):


 When a function requires to manipulate an entire array, it is necessary to pass
the entire array to the function during a single call rather than passing one
element at a time.
 This can be achieved by passing address of an array to the function. An
array name represents the address of the first element in that array.
 So, arrays are passed to functions as pointers (a pointer is a variable, which
holds the address of other variables).
 When a function is called with just the array name, a pointer to the array is
passed.
 In C, an array name without an index is a pointer to the first element.
I B.Tech C StudyMaterial 12 D.Madhu Babu, M.Tech.
 This means that the parameter declaration must be of a compatible pointer
type. There are three ways to declare a parameter , which is to receive an
array pointer :
Example:
 As a sized array:
void display (int marks[10]);

In this case the compiler automatically converts it to a pointer.

 As an unsized array:

void display (int marks[]);

In this case also it converted to a pointer.

 As a pointer:

void display (int *marks);

In this case, the address of an array stored in pointer variable called


marks .

Example:

/* Demonstration of call by adress */


main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 88, 90 } ;
void display(int marks[]);
clrscr();
display ( marks ) ;
getch();
}

Void display ( int marks[] )


{
Int i
printf(“\n Marks…:”);
for ( i = 0 ; i< 6; i++ )
printf( "%4d ", marks[i] ) ;
}
Output :
Marks…..: 55 65 75 56 78 88 90

Important points to be noted while using functions:

I B.Tech C StudyMaterial 13 D.Madhu Babu, M.Tech.


 Any C program contains at least one function.
 If a program contains only one function, it must be main( ).
 If a C program contains more than one function, then one (and only one) of these
functions must be main( ), because program execution always begins with main( ).
 There is no limit on the number of functions that might be present in a C program.
 Each function in a program is called in the sequence specified by the function calls
in main( ).
 After each function has done its thing, control returns to main( ).When main( )
runs out of function calls, the program ends.
 Any function can be called from any other function. Even main( ) can be called
from other functions. For example,
main( )
{
message( ) ;
}
message( )
{
printf( "\nthis is from Message Function" ) ;
main( ) ;
}

 A function can be called any number of times.


The order in which the functions are defined in a program and the order in which
they get called need not necessarily be same. For example,

main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf("\n This from message2 function”);
}
message1( )
{
printf( "\n This from message1 function" ) ;
}

Here, even though message1( ) is getting called before message2( ), still,


message1( ) has been defined after message2( ). However, it is advisable to
define the functions in the same order in which they are called. This makes the
program easier to understand.

 A function can be called from other function, but a function cannot be defined in
another function. Thus, the following program code would be wrong, since
message( ) is being defined inside another function, main( ).

main( )
{
printf( "\nThis is main" ) ;
message( )
{
printf( "\nthis is message function" ) ;
}
}

I B.Tech C StudyMaterial 14 D.Madhu Babu, M.Tech.


Important points to be noted while calling a function:

 Parenthesis are compulsory after the function name.


 The function name in the function call and the function definition must be same.
 The type, number, and sequence of actual and formal arguments must be same.
 A semicolon must be used at the end of the statement when a function is called.
 The number of arguments should be equal to the number of parameters.
 There must be one-to-one mapping between arguments and parameters. i.e. they
should be in the same order and should have same data type.
 Same variables can be used as arguments and parameters.

Nested Functions:
 Calling one function in another function is called nested functions. We have seen
programs using functions called only from the main() function.
 But there are situations, where functions other than main() can call any other
function(s) used in the program.
 This process is referred as nested functions. C permits nesting of functions freely
ie.,, main() can call function1, which calls function2 , which calls function3 and so
on. There is no limit as to how deeply functions can be nested.

Example: the following program illustrates this:

#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function 1”);
func2();
printf (“\n Again inside function 1”);
}

void func2()
{
printf (“\n Inside function 2”);
}

Output:
Inside main function
Inside function 1
Inside function 2
Again inside function 1
Again inside main function

I B.Tech C StudyMaterial 15 D.Madhu Babu, M.Tech.


Uses two functions func1() and func2() other than the main() function. The main()
function calls the function func1() and the function func1() calls the function func2().

Recursion:
 In C, it is possible for the functions to call themselves. When a function call itself is
called Recursion.
 A function is called ‘recursive’ if a statement within the body of a function calls the
same function. Recursion functions must have terminating condition to avoid
infinite loop.
 Recursion function can be used to solve problems where the solution is expressed
in terms of successively applying the same solution to subsets of the problem.

Suppose we want to calculate the factorial value of an integer. As we know, the factorial
of a number is the product of all the integers between 1 and that number. For example,
4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for
factorial. Thus factorial of a number can be expressed in the form of itself. Hence this
can be programmed using recursion.
Example :
main( )
{
int n;
long int f ;
printf( "\nEnter N value ……..: " ) ;
scanf( "%d", &n ) ;
fact = rec_factorial( n ) ;
printf( "Factorial of %4d is …: %4ld",n, f ) ;
getch();
}

Long int rec_factorial( int n )


{
Long int fact ;
if ( n == 1 )
return ( 1 ) ;
else
f = n * rec_factorial( n - 1 ) ;
return ( fact ) ;
}

Output…:

Enter N value ………: 5


Factorial of 5 is…. ..:120

In case the value of n is 5, main( ) would call rec_factorial( ) with 5 as its actual
argument, and rec_factorial( ) will send back the computed value. But before sending the
I B.Tech C StudyMaterial 16 D.Madhu Babu, M.Tech.
computed value, rec_factorial( ) calls rec_factorial( ) and waits for a value to be returned.
These recursive invocations end finally when the last invocation gets an argument value
of 1, which the preceding invocation of rec_factorial( ) now uses to calculate its own fact
value and so on up the ladder. So we might say what happens is,

rec ( 5 ) returns ( 5 times rec ( 4 ),


which returns ( 4 times rec ( 3 ),
which returns ( 3 times rec ( 2 ),
which returns ( 2 times rec ( 1 ),
which returns ( 1 ) ) ) ) )
Recursion may seem strange and complicated at first glance, but it is often the most
direct way to code an algorithm, and once you are familiar with recursion, the clearest
way of doing so.

Storage classes:
 Storage classes are used to define the scope (visibility) and life-time of variables
and functions.
 Every variable and function in C has two attributes: type and storage class.
 There are basically two kinds of locations in a computer where a value of variable
may be kept— Memory and CPU registers.
 The variable’s storage class that determines in which of these two locations the
value is stored.
Moreover, a variable’s storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e.
the default initial value).
(c) What is the scope of the variable; i.e. in which functions the value of the variable
would be
available.
(d) What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:


(1) Automatic storage class (Auto)
(2) Register storage class (Register)
(3) Static storage class (Static)
(4) External storage class (Extern)
1.Automatic storage class (Auto) :
 Automatic variables are declared inside of a function in which they are to be
utilized.

I B.Tech C StudyMaterial 17 D.Madhu Babu, M.Tech.


 Declarations of variables within blocks are known as automatic storage class
variables.
 Automatic variables also referred as local or internal variables of that block or
function.
 Variables declared within function bodies are automatic by default.
 The key-word auto can be used to explicitly specify the storage class.
An example is:
auto int a, b, c;
auto float f;
The features of a variable defined to have an automatic storage class are as under:
Storage − Memory.
Default initial value − An unpredictable value, which is often called a garbage
value.
Scope− Local to the block in which the variable is defined.
Life − Till the control remains within the block in which the variable is defined.
Following program shows how an automatic storage class variable is declared, and the
fact that if the variable is not initialized it contains a garbage value.

main( )
{
auto int i, j=0 ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be... : 1211 0

2. Register storage class (Register) :


 This is like `auto' except that it asks the compiler to store the variable in one of
the CPU's fast internal registers.
 The use of storage class register is an attempt to improve execution speed.
 When speed is a concern, the programmer may choose a few variables that are
most frequently accessed and declare them to be of storage class register.
 The keyword register is used to declare these variables.
Examples:

1) register int x;
2) register int counter;
The declaration register i; is equivalent to register int i;
The features of a variable defined to be of register storage class are as under:
Storage - CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which the variable is defined.
Life - Till the control remains within the block in which the variable is defined.

I B.Tech C StudyMaterial 18 D.Madhu Babu, M.Tech.


A value stored in a CPU register can always be accessed faster than the one that is
stored in memory.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
3 Static Storage Class (static) :
 It allows a local variable to retain its previous value when the block is
reentered.
 This is in contrast to automatic variables, which lose their value upon block exit
and must be reinitialized.
 The static variables hold their values throughout the execution of the program.
 The key-word static is used to declare the static storage class variable.
For example:
Static int x,y;
 A static variable is stored at a fixed memory location in the computer, and is
created and initialized once when the program is first started.
 Such a variable maintains its value between calls to the block (a function, or
compound statement) in which it is defined.
 When a static variable is not initialized, it takes a value of zero.
The features of a variable defined to have a static storage class are as under:
Storage− Memory.
Default initial value − Zero.
Scope− Local to the block in which the variable is defined.
Life − Value of the variable persists between different function calls.
Compare the two programs and their output to understand the difference between the
automatic and static storage classes.
main( ) main( )
{ {
increment( ) ; increment( ) ;
increment( ) ; increment( ) ;
increment( ) ; increment( ) ;
} }
increment( )
{ increment( )
auto int i = 1 ; {
printf ( "%d\n", i ) ; static int i = 1 ;
i=i+1; printf ( "%d\n", i ) ;
} i=i+1;
The output of the above program would be: 1 1 1 }
The output of the above program would be:1 2 3

Static variables are classified into two types:


 Internal static variables
 External static variables

I B.Tech C StudyMaterial 19 D.Madhu Babu, M.Tech.


Internal static variables are declared inside of the functions including the main()
function. They are similar to auto variables except that they remains in existence(alive)
throughout of the program.
External static variables are declared outside of all functions including the main()
function. They are global variables but are declared with the keyword static. The external
static variables cannot be used across multi-file program.

4 External Storage Class:


 The variables that are both alive and active throughout the entire program are
known as external variables.
 One method of transmitting information across blocks and functions is to use
external variables.
 When a variable is declared outside a function, storage is permanently assigned to
it, and its storage class is extern.
 Such a variable is considered to be global to all functions.
 The key-word extern is used to declare the external storage class variables.

For example
extern int i,j;
The features of a variable whose storage class has been defined as external are as
follows:
Storage − Memory.
Default initial value− Zero.
Scope− Global.
Life − As long as the program’s execution doesn’t come to an end.

The following program illustrates this:

# include <stdio.h>

int a = 1, b = 2, c = 3; /* global variable*/


int fun (void); /* function prototype*/
int main (void)
{
printf (“\nSum=%3d\n”, fun ()); /* 12 is printed */
printf (“A=%3d , B=%3d and C =%3d\n”, a, b, c); /* 4 2 3 is printed */
}

int fun (void)


{
int b, c;
a = b = c = 4; /* b and c are local */
return (a + b + c); /* global b, c are masked*/
}

I B.Tech C StudyMaterial 20 D.Madhu Babu, M.Tech.


Output :
Sum= 12
A = 4 , B= 2 and C= 3

 Note that we could have written:

extern int a = 1, b = 2, c = 3;

 Variables defined outside a function have external storage class, even if the
keyword extern is not used. Such variables cannot have auto or register storage
class.

A complete summarized table to represent the lifetime and visibility (scope) of all the
storage class specifier is as below:

Storage class Life time Visibility (Scope)


Local (within
Auto Local
function)
Global (in all
Extern Global
functions)
Static Global Local
Register Local Local

Introduction to Files

 A File is a collection of data stored in the secondary memory.


 So far data was entered into the programs through the keyboard.
 So Files are used for storing information that can be processed by the programs.
 Files are not only used for storing the data, programs are also stored in files.
 In order to use files, we have to learn file input and output operations. That is, how
data is read and how to write into a file

Why files are needed?
 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them
all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
 You can easily move your data from one computer to another without any
changes.

Types of Files
When dealing with files, there are two types of files you should know about:
I B.Tech C StudyMaterial 21 D.Madhu Babu, M.Tech.
1. Text files
2. Binary files

1. Text files
 Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
 When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
 The content of Text file is readable

2. Binary files
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold a higher amount of data, are not readable easily, and provides
better security than text files.

File Operations

In C, you can perform four major operations on files, either text or binary:

1. Creating a new file

2. Opening an existing file

3. Reading from and writing information to a file

4. Closing a file

 You can create, open, read, and write to files by declaring a pointer of type FILE, and
use the fopen() function:

 FILE *fptr
fptr = fopen(filename, mode);

 FILE is basically a data type, and we need to create a pointer variable to work with it
(fptr). For now, this line is not important. It's just something you need when working
with files.
 To open a file, use the fopen() function, which takes two parameters:

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

I B.Tech C StudyMaterial 22 D.Madhu Babu, M.Tech.


w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

 Firstly, It searches the file to be opened.


 Then, it loads the file from the disk and place it into the buffer. The buffer is used
to provide efficiency for the read operations.
 It sets up a character pointer which points to the first character of the file.

Create a File
 To create a file, you can use the w mode inside the fopen() function.
 The w mode is used to write to a file.
 However, if the file does not exist, it will create one for you:

Example

 FILE *fptr;

// Create a file
fptr = fopen("filename.txt", "w");

// Close the file


fclose(fptr);

Opening File: fopen()

 We must open a file before it can be read, write, or update. The fopen() function is
used to open a file.

The syntax of the fopen() is given below.

FILE *fopen( const char * filename, const char * mode );

Example:
FILE *fp ;
I B.Tech C StudyMaterial 23 D.Madhu Babu, M.Tech.
fp = fopen("SampleTextFile.c","r") ;

The fopen() function accepts two parameters:

 The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
 The mode in which the file is to be opened. It is a string.

Reading From a File

The file read operation in C can be performed using functions fscanf() , fgets() and
fgetc.
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return
value is the character read, or in case of any error, it returns EOF.
The following function allows to read a string from a stream −

char *fgets( char *buf, int n, FILE *fp );


The functions fgets() reads up to n-1 characters from the input stream referenced by fp.
It copies the read string into the buffer buf, appending a null character to terminate the
string.

Consider the following example which opens a file in read mode.

#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("SampleTextFile.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}

Writing a File

Following is the simplest function to write individual characters to a stream −

I B.Tech C StudyMaterial 24 D.Madhu Babu, M.Tech.


int fputc( int c, FILE *fp );

 The function fputc() writes the character value of the argument c to the output
stream referenced by fp.
 It returns the written character written on success otherwise EOF if there is an
error.

You can use the following functions to write a null-terminated string to a stream −

int fputs( const char *s, FILE *fp );

 The function fputs() writes the strings to the output stream referenced by fp.
 It returns a non-negative value on success, otherwise EOF is returned in case of
any error.
 You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a
string into a file.

Example
FILE *fp;
// Create a file
fp = fopen("SampleTextFile.txt", "w");
// Close the file
fclose(fp);

Closing the file

 Did you notice the fclose() function in our example above?


 This will close the file when we are done with it.
 It is considered as good practice, because it makes sure that:

 Changes are saved properly


 Other programs can use the file (if you want)
 Clean up unnecessary memory space

The syntax of fclose() function is given below:


int fclose( FILE *fp );
Example:

Fclose(fp);

I B.Tech C StudyMaterial 25 D.Madhu Babu, M.Tech.

You might also like