Unit 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Functions:

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.

Every function in C has the following...

• Function Declaration (Function Prototype)


• Function Definition
• Function Call

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.

Syntax - return_type function_name(parameters_list);

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.

Syntax - return_type function_name(parameters_list)

{
//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);

Calling Function: The function call is known as calling function.

Called Function: The function definition is known as called function.

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:

• Using functions we can implement modular programming.


• Functions make the program more readable and understandable.
• Using functions the program implementation becomes easy.
• Once a function is created it can be used many times (code re-usability).
• Using functions larger programs can be divided into smaller modules.

Types of Functions:

In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...

• System Defined Functions


• User Defined Functions

System Defined Functions:


The C Programming Language provides pre-defined functions to make programming easy.
These pre-defined functions are known as system defined functions. The functions whose
definition is defined by the system are called as system defined functions. The system defined
functions are also called as Library Functions or Standard Functions or Pre- Defined Functions.
The implementation of system defined functions is already defined by the system.

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.

User Defined Functions:

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.

Write a C program to demonstrate the use of functions to add two numbers

#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);
}

int addition(int a, int b) // function definition


{
return a+b ;
}
In the above example program, the function declaration statement "int addition(int,int)" tells
the compiler that there is a function with name addition which takes two integer values as
parameters and returns an integer value. The function call statement takes the execution
control to the additon() definition along with values of num1 and num2. Then function
definition executes the code written inside it and comes back to the function call along with
return value.

The functions are classified as follows...

• Function without Parameters and without Return value


• Function with Parameters and without Return value
• Function without Parameters and with Return value
• Function with Parameters and with Return value

Function without Parameters and without Return value:

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
}

void addition() // function definition


{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}

Function with Parameters and without Return value:

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

called function, and finally comes back to the calling function.

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
}

void addition(int a, int b) // function definition


{
printf("Sum = %d", a+b ) ;
}

Function without Parameters and with Return value:

In this type of functions there is no data transfer from calling-function to called-function


(parameters) but there is data transfer from called function to calling-function (return value).
The execution control jumps from calling-function to called function and executes called
function, and finally comes back to the calling function along with a return value.

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) ;
}

int addition() // function definition


{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}

Function with Parameters and with Return value:

In this type of functions there is data transfer from calling-function to called-function


(parameters) and also from called function to calling-function (return value). The execution
control jumps from calling-function to called function along with parameters and executes
called function, and finally comes back to the calling function along with a return value.

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) ;
}

int addition(int a, int b) // function definition


{
return (a+b) ;
}

Inter Function Communication:

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.

In C, the inter function communication is classified as follows...


• Downward Communication
• Upward Communication
• Bi-directional 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:

In this type of inter-function communication, the data is transferred from calling-function to


called function and also from called function to calling-function. The functions with parameters
and with return value are considered under bi-directional communication. In the case of bi-
directional 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 along with a return value.

Parameter passing mechanisms:

There are 2 ways in which we can pass arguments to the function-

• 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);
}

void swap( int var1, int var2 )


{
int temp ;
temp = var1 ;
var1 = var2 ;
var2 = temp;
printf("\n After swapping: %d, %d", var1, var2);
}

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);
}

void swap( int *var1, int *var2 )


{
int *temp ;
*temp = *var1 ;
*var1 = *var2 ;
*var2 = *temp;
printf("\n After swapping: %d, %d", *var1, *var2);
}

Output:
Enter 2 numbers: 35 45
Before swapping: 35, 45
After swapping: 35, 45

Passing Array to functions:

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.

(i) return_type function(type arrayname[])


Declaring blank subscript notation [] is the widely used technique.

(ii) return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

(iii) return_type function(type *arrayname)

C program to demonstrate passing array as an argument to function

#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();
}

int max(int x[],int k) //function definition


{
int large,i;
large=x[0];
for(i=1;i<k;i++)
{
if(x[i]>large)
large=x[i];
}
return(large);
}

Output:
Enter array size: 6
Enter array elements: 5 8 9 4 6 3
MAXIMUM NUMBER IS 9

Passing Pointer to functions:


Same as call by reference

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.

Write a C program to demonstrate the recursive function

#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;
}

int factorial( int n ) //function definition


{
if( n == 0)
return 1 ;
else
return n * factorial( n-1) ; // recursive function call
}

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.

Case 1: Move 1 disk from source to destination needle.

Case 2: Move 1 disk from source to auxiliary needle.

Move 1 disk from source to destination needle.

Move 1 disk from auxiliary to destination needle.

Case 3: Move 2 disks from source to auxiliary needle.


Move 1 disk from source to destination needle.

Move 2 disks from auxiliary to destination needle.

General Case: Move n-1 disks from source to auxiliary needle.

Best Case: Move 1 disk from source to destination needle.

General Case: Move n-1 disks from auxiliary to destination needle.


Files:

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.

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 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 Files (or) ASCII Files


• Binary Files

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:

The following are the operations performed on files in c programming language

• Creating (or) Opening a file


• Reading data from a file
• Writing data into a file
• Closing a file

Creating (or) Opening a file:


To create a new file or open an existing file, we need to create a file pointer of FILE type.
Whenever you want to work with a file, the first step is to create a file. A file is nothing but
space in a memory where data is stored.

Syntax: FILE *fp;

fp = fopen ("file_name", "mode");

In the above syntax, the file is a data structure which is defined in the standard library.

fopen is a standard function which is used to open a file.

• 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.

S. No. Mode Description

1 r Opens a text file in reading mode.

2 w Opens a text file in writing mode.

3 a Opens a text file in append mode.

4 r+ Opens a text file in both reading and writing mode.

5 w+ Opens a text file in both reading and writing mode. It set the

cursor position to the beginning of the file if it exists.

6 a+ Opens a text file in both reading and writing mode. The reading

operation is performed from beginning and writing operation is


performed at the end of the file.

Note - The above modes are used with text files only. If we want to work with binary files we
use

rb, wb, ab, rb+, wb+ and ab+.

File management functions:


Function Purpose

fopen () Creating a file or opening an existing file

fclose () Closing a file

fprintf () Writing a block of data to a file

fscanf () Reading a block data from a file

getc () Reads a single character from a file

putc () Writes a single character to a file

getw () Reads an integer from a file

putw () Writing an integer to a file

fseek () Sets the position of a file pointer to a specified location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

Reading from a file:

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.

Write a C Program to illustrate getc()


#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
return 0;
}

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.

Write a C Program to illustrate getw()

#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

fscanf( *file_pointer, typeSpecifier, &variableName ) - This function is used to read multiple


datatype values from specified file which is opened in reading mode.

Write a Program to illustrate fscanf()

#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.

Write a program to illustrate fgets()

#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

fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer ) – This function is


used to read specific number of sequence of characters from the specified file which is opened
in reading mode.

Write a Program to illustrate fread()


#include<stdio.h>
int main()
{
FILE *fp;
char *str;
fp = fopen ("file.txt", "r");
fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;
printf("str = %s", str);
fclose(fp);
return 0;
}
Output

Writing into a file:

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.

Write a Program to illustrate putc()


#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
}
Output

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.

Write a Program to illustrate putw()

#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.

Write a Program to illustrate "fprintf()"

#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

Write a C program to write some text to a text file


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

Write a C program to read some text from a text file

#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

which is opened in writing mode.

Write a Program to illustrate fputs()


#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
Output

fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer ) - This function

is used to insert specified number of characters into a binary file which is opened in writing

mode.

Write a Program to illustrate fwrite() in C.

#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

Closing a file is performed using a pre-defined method fclose().

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.

The following are the methods available in c, to position cursor in a file.

1. ftell()

2. rewind()

3. fseek()

ftell( *file_pointer ) - This function returns the current position of the cursor in the file.

Write a Program to illustrate ftell()

#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.

Write a Program to illustrate rewind()

#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;
}

fseek( *file_pointer, numberOfCharacters, fromPosition ) - This function is used to set the


cursor position to the specific position. Using this function we can set the cursor position from
three different position they are as follows.

from beginning of the file (indicated with 0)

from current cursor position (indicated with 1)

from ending of the file (indicated with 2)

Write a Program to illustrate fseek()

#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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy