Unit 5
Unit 5
Unit 5
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main().
When we write a program to solve a larger problem, we divide that larger problem into smaller
sub problems and are solved individually to make the program easier. In C, this concept is
implemented using functions. Functions are used to divide a larger program into smaller sub
programs such that the program becomes easy to understand and easy to implement.
Function Declaration:
The function declaration tells the compiler about function name, the data type of the return
value and parameters. The function declaration is also called a function prototype. The function
declaration is performed before the main function or inside the main function or any other
function.
In the above syntax, return_type specifies the data type of the value which is sent as a return
value from the function definition.
The function_name is a user-defined name used to identify the function uniquely in the
program.
The parameters_list is the data values that are sent to the function definition.
Function Definition:
The function definition provides the actual code of that function. The function definition is also
known as the body of the function. The actual task of the function is implemented in the
function definition i.e., the actual instructions to be performed by a function are written in
function definition. The actual instructions of a function are written inside the braces "{ }". The
function definition is performed before the main function or after the main function.
{
//statements
Function Call:
The function call tells the compiler when to execute the function definition. When a function
call is executed, the execution control jumps to the function definition where the actual code
gets executed and returns to the same functions call once the execution completes. The
function call is performed inside the main function or any other function or inside the function
itself.
Syntax - function_name(parameters);
Actual arguments: The arguments of calling function are called actual arguments.
Formal arguments: The arguments of called function are called formal arguments.
Advantages of functions:
Types of Functions:
In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...
In C, all the system defined functions are defined inside the header files like stdio.h, conio.h,
math.h, string.h etc., For example, the funtions printf() and scanf() are defined in the header file
called stdio.h.
Whenever we use system defined functions in the program, we must include the respective
header file using #include statement. For example, if we use a system defined function sqrt() in
the program, we must include the header file called math.h because the function sqrt() is
defined in math.h.
In C programming language, users can also create their own functions. The functions that are
created by users are called as user defined functions. For example, the function main is
implemented by user so it is called as user defined function.
In C every user defined function must be declared and implemented. Whenever we make
function call the function definition gets executed. For example, consider the following program
in which we create a function called addition with two parameters and a return value.
#include<stdio.h>
int addition(int,int) ; // function declaration
void main()
{
int num1, num2, result ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
}
In this type of functions there is no data transfer between calling function and called function.
Simply the execution control jumps from calling function to called function and executes called
function, and finally comes back to the calling function.
Write a C program to demonstrate the function without Parameters and without Return
value
#include<stdio.h>
void addition() ; // function declaration
void main()
{
addition() ; // function call
}
In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling-function (return
value). The execution control jumps from calling-function to called function along with the
parameters and executes
Write a C program to demonstrate the function with Parameters and without Return value
#include<stdio.h>
void addition(int, int) ; // function declaration
void main()
{
int num1, num2 ;
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
}
Write a C program to demonstrate the function without Parameters and with Return value
#include<stdio.h>
int addition() ; // function declaration
void main()
{
int result ;
result = addition() ; // function call
printf("Sum = %d", result) ;
}
Write a C program to demonstrate the function with Parameters and with Return value
#include<stdio.h>
int addition(int, int) ; // function declaration
void main()
{
int num1, num2, result ;
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
}
When a function gets executed in the program, the execution control is transferred from calling
a function to called function and executes function definition, and finally comes back to the
calling function. In this process, both calling and called functions have to communicate with
each other to exchange information. The process of exchanging information between calling
and called functions is called inter-function communication.
Downward Communication:
In this type of inter function communication, the data is transferred from calling function to
called function but not from called function to calling function. The functions with parameters
and without return value are considered under downward communication. In the case of
downward communication, the execution control jumps from calling function to called function
along with parameters and executes the function definition, and finally comes back to the
calling function without any return value.
Upward Communication:
In this type of inter-function communication, the data is transferred from called function to
calling-function but not from calling-function to called-function. The functions without
parameters and with return value are considered under upward communication. In the case of
upward communication, the execution control jumps from calling-function to called-function
without parameters and executes the function definition, and finally comes back to the calling
function along with a return value.
Bi Directional Communication:
• Call by value
• Call by reference
Call by value:
In this type, the value of actual arguments is passed to the formal arguments and operation is
done on the formal arguments. Any change made in the formal arguments does not affect the
actual arguments because formal arguments are the photocopy of actual arguments. Hence,
when a function is called by call by value method, it does not affect the actual contents of the
arguments. Changes made in the formal arguments are local to the block of called function.
Once control returns back to the calling function, changes made vanish.
#include <stdio.h>
void swap( int, int);
int main( )
{
int num1, num2;
printf(“\n Enter 2 numbers”);
scanf(“%d %d”, &num1,&num2);
printf("Before swapping: %d, %d", num1, num2);
/*calling swap function*/
swap(num1, num2);
}
Output:
Enter 2 numbers: 35 45
Before swapping: 35, 45
After swapping: 35, 45
Call by reference:
In this type, instead of passing values, addresses (references) are passed. Function operates on
addresses rather than values. Here, the formal arguments are pointers to the actual arguments.
The formal arguments point to the actual argument. Hence, changes made in the argument are
permanent.
#include <stdio.h>
void swap( int *, int *);
int main( )
{
int num1, num2;
printf(“\n Enter 2 numbers”);
scanf(“%d %d”, &num1,&num2);
printf("Before swapping: %d, %d", num1, num2);
/*calling swap function*/
swap(&num1, &num2);
}
Output:
Enter 2 numbers: 35 45
Before swapping: 35, 45
After swapping: 35, 45
In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.
The array_name contains the address of the first element. Here, we must notice that we need
to pass only the name of the array in the function which is intended to accept an array. The
array defined as the formal parameter will automatically refer to the array specified by the
array name defined as an actual parameter.
There are 3 ways to declare the function which is intended to receive an array as an argument.
#include <stdio.h>
#include <conio.h>
Int max(int [],int); //function declaration
void main()
{
int a[10],n,m,i;
printf(“\n Enter array size”);
scanf(“%d”,&n);
printf(“\n Enter array elements”);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);
m=max(a,n); //function call
printf("\nMAXIMUM NUMBER IS %d",m);
getch();
}
Output:
Enter array size: 6
Enter array elements: 5 8 9 4 6 3
MAXIMUM NUMBER IS 9
Recursive Functions in C:
A function called by itself is called recursive function. The recursion can be used either directly
or indirectly. The recursive functions should be used very carefully because, when a function
called by itself it enters into the infinite loop. And when a function enters into the infinite loop,
the function execution never gets completed. We should define the condition to exit from the
function call so that the recursive function gets terminated. To stop the recursive function, it is
necessary to specify a proper terminating statement such as exit or return or if condition.
When a function is called by itself, the first call remains under execution till the last call gets
invoked. Every time when a function call is invoked, the function returns the execution control
to the previous function call.
#include<stdio.h>
int factorial( int ) ; //function declaration
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ; //function call
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
Explanation:
In the above program, factorial() is a recursive function. The entered number is passed to
function factorial(). When factorial() is executed, it is repeatedly invoked by itself. Every time
the function is invoked, the value of f is reduced by one and multiplication is carried out. The
multiplication of these numbers is carried out and returns to main function.
Towers of Hanoi:
There are N disk of decreasing sizes mounted on one needle. Two more needles are also
required to stack the entire disks in the decreasing order. The use of third needle is for
impermanent storage. While mounting the disk, following rules should be followed:
• At a time only one disk may be moved.
• The disk may be moved from any needle to another needle.
• No larger disk may be placed on the smaller one.
File is a collection of data that stored on secondary memory like hard disk of a computer.
Generally, a file is used to store user data in a computer. In other words, computer stores the
data using files.
• 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 amount 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:
C programming language supports two types of files and they are as follows...
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and
symbols is called text file (or) ASCII file.
Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files.
Operations on files:
In the above syntax, the file is a data structure which is defined in the standard library.
• If the file is not present on the system, then it is created and then opened.
• If a file is already present on the system, then it is directly opened using this function.
• fp is a file pointer which points to the type file.
In C programming language, different modes are available to open a file and they are shown in
the following table.
5 w+ Opens a text file in both reading and writing mode. It set the
6 a+ Opens a text file in both reading and writing mode. The reading
Note - The above modes are used with text files only. If we want to work with binary files we
use
The reading from a file operation is performed using the following pre-defined file handling
methods.
1. getc()
2. getw()
3. fscanf()
4. fgets()
5. fread()
getc( *file_pointer ) - This function is used to read a character from specified file which is
opened in reading mode. It reads from the current position of the cursor. After reading the
character the cursor will be at next character.
Output
getw( *file_pointer ) - This function is used to read an integer value form the specified file
which is opened in reading mode. If the data in file is set of characters then it reads ASCII values
of those characters.
#include<stdio.h>
int main()
{
FILE *fp;
int i,j;
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j);
//65+97= 162
fclose(fp);
return 0;
}
Output
#include<stdio.h>
int main()
{
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
fp = fopen ("file.txt", "w+");
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to beginning of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
return 0;
}
Output
fgets( variableName, numberOfCharacters, *file_pointer ) - This function is used for reading
a set of characters from a file which is opened in reading mode starting from the current cursor
position. The fgets() function reading terminates with reading NULL character.
#include<stdio.h>
int main()
{
FILE *fp;
char *str;
fp = fopen ("file.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
return 0;
}
Output
The writing into a file operation is performed using the following pre-defined file handling
methods.
1. putc()
2. putw()
3. fprintf()
4. fputs()
5. fwrite()
putc( char, *file_pointer ) - This function is used to write/insert a character to the specified
file when the file is opened in writing mode.
putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the
specified file when the file is opened in writing mode.
#include<stdio.h>
int main()
{
FILE *fp;
int i;
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
return 0;
}
Output
fprintf( *file_pointer, "text" ) - This function is used to writes/inserts multiple lines of text
with mixed data types (char, int, float, double) into specified file which is opened in writing
mode.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
getch();
return 0;
}
Output
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL)
{
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
fputs( "string", *file_pointer ) - TThis method is used to insert string data into specified file
is used to insert specified number of characters into a binary file which is opened in writing
mode.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "Welcome to C Language";
clrscr();
fp = fopen("MySample.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();
return 0;
}
Output
Closing a file
fclose( *f_ptr )
The method fclose() returns '0'on success of file close otherwise it returns EOF (End Of File).
Cursor Positioning Functions in Files
C programming language provides various pre-defined methods to set the cursor position in
files.
1. ftell()
2. rewind()
3. fseek()
ftell( *file_pointer ) - This function returns the current position of the cursor in the file.
#include<stdio.h>
int main()
{
FILE *fp;
int position;
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
return 0;
}
Output
rewind( *file_pointer ) - This function is used reset the cursor position to the beginning of
the file.
#include<stdio.h>
int main()
{
FILE *fp;
int position;
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output