CP Unit-5 Notes
CP Unit-5 Notes
Introduction to Functions:
Definition: A Function is a group of statements that can perform any particular task.
Advantages of Functions
There are several advantages in using functions. They are discussed below.
1. When developing even a program, it is very difficult, to write the entire program as a single large main function.
The task to be performed is normally divided into several independent subtasks, thereby reducing the overall
complexity.
2. Writing a program in single large function i.e in main(),Such programs are very difficult to test, debug and
maintain. The task to be performed is normally divided into several independent subtasks, thereby it is easy to read,
test, debug and maintain.
3. Functions help avoid duplication of effort and code in programs. During the development of a program, the same
or similar activity may be required to be performed more than once. The use of functions in such situations avoids
duplication of effort and code in programs i.e code can be reused.
4. This reduces the size of the source program as well as the executable program, thus reducing program
development and maintenance cost.
5. Functions enable us to hide the implementation details of a program, e. g., we have used library functions such as
sqrt, log, sin, etc. without ever knowing how they are implemented.
6. The functions developed for one program can be used, if required, in another program with little or no
modification. This further reduces program development time and cost
Every function in C has the following...
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.
Parameters – is the information passed to a function. In function declaration only data types of variables
passed to a function must be used.
Example:
int addition (int , int) ;
here the function returns an integer value so return tyoe of the function is int.
Function Definition:
It contains the actual statements which are to be executed. The function definition is also known as the body
of the function. The actual task of the function is implemented in the function definition.
The function definition can be placed after main( ) function and its function declaration must be done before
main( ).
If function definition is placed before main( ) then no need to declare the function .
Syntax:
returnType functionName( parametersList )
{
Body of 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.
Parameters – is the information passed to a function. In function definition variables passed must be
declared with its datatypes..
Function definition is
int addition (int a , int b)
{
return (a+b);
}
The no: of parameters or arguments and function name, return type in function declaration and function
definition must match otherwise compiler will generate error.
Function Call:
To execute the function definition a function must be called. When a function call is executed, the execution
control jumps to the function definition where the actual code gets executed.
Syntax: function without returning value
functionName( parameters );
here parameters are variables separated by comma
Syntax: function with returning value
Or return (expression)
Types of functions:
1. Standard functions or predefined functions and
2. Userdefined functions
Standard Functions in C
The standard functions are built-in functions. In C programming language, the standard functions are declared
in header files and defined in .dll files. In simple words, the standard functions can be defined as "the readymade
functions defined by the system to make coding more easy". The standard functions are also called as library
functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file using #include statement.
For example, the function printf() is defined in header file stdio.h (Standard Input Output header file). When we
use printf() in our program, we must include stdio.h header file using #include<stdio.h> statement.
C Programming Language provides the following header files with standard functions.
Header File Purpose Example Functions
time.h Provides functions to perform operations on time and date time(), localtime()
ctype.h Provides functions to perform - testing and mapping of character data values isalpha(), islower()
setjmp.h Provides functions that are used in function calls setjump(), longjump()
signal.h Provides functions to handle signals during program execution signal(), raise()
assert.h Provides Macro that is used to verify assumptions made by the program assert()
locale.h Defines the location specific settings such as date formats and currency setlocale()
symbols
stdarg.h Used to get the arguments in a function if the arguments are not specified by va_start(), va_end(),
the function va_arg()
The functions that are created by the user in a program are known as user defined functions.
Syntax:
returnType functionName( parametersList ) ;
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.
Parameters – is the information passed to a function. In function declaration only data types of variables
passed to a function must be used.
Example:
int addition (int , int) ;
here the function returns an integer value so return tyoe of the function is int.
Function Definition:
It contains the actual statements which are to be executed. The function definition is also known as the body
of the function. The actual task of the function is implemented in the function definition.
The function definition can be placed after main( ) function and its function declaration must be done before
main( ).
If function definition is placed before main( ) then no need to declare the function .
Syntax:
returnType functionName( parametersList )
{
Body of 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.
Parameters – is the information passed to a function. In function definition variables passed must be
declared with its datatypes..
Function Body − The function body set of statements placed inside ‟ { }‟
Example:
Function declaration is
int addition(int , int) ;
Function definition is
int addition (int a , int b)
{
return (a+b);
}
The no: of parameters or arguments and function name, return type in function declaration and function
definition must match otherwise compiler will generate error.
Function Call:
To execute the function definition a function must be called. When a function call is executed, the execution
control jumps to the function definition where the actual code gets executed.
Syntax: function without returning value
functionName( parameters );
here parameters are variables separated by comma
Syntax: function with returning value
C program to perform addition operation on two integers using User defined functions:
#include<stdio.h>
int addition ( int , int); // function declaration
void main()
{
int a, b, c;
printf(“Enter any two numbers\n ”);
scanf(“%d%d”, &a, &b);
c = addition(a, b); // function call
printf(“the result is %d\n”, c);
}
int addition(int x, int y) // function definition
{
return (x + y);
}
Output:
Enter any two numbers
2 3
the result is 5
Important terms in functions
1. Calling Function: It is used to initiate the function execution. The function call present inside main() or in
any other function is called calling function.
2. Called Function: It is nothing but the function definition. It decides what is to be done by the function on
a function call.
3. Actual parameters: Parameters inside the calling function are called actual parameters.
4. Formal parameters: Parameters inside the called function are called formal parameters.
For example, consider the following program...
#include<stdio.h>
int addition(int, int) ;
void main()
{
int a=10, b=20, result ;
result = addition(a, b) ; calling function
2) 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.
For example, consider the following program...
#include<stdio.h>
int addition() ;
void main()
{
int result ;
result = addition() ; // calling function
printf("Sum = %d", result) ;
}
int addition() // called function
{
int a=10, a=30 ;
return (a+b) ;
}
Output:
Sum=30
In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called function. The changes made on the formal parameters
does not effect the values of actual parameters. That means, after the execution control comes back to the calling
function, the actual parameter values remains same.
c program to swap two integer variables using function (call by value method)
#include<stdio.h>
void swap( int, int);
void main( )
{
int a , b;
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
printf(“before swapping a= %d \t b=%d\n” , a, b);
swap( a, b);
printf(“after swapping a= %d \t b=%d\n” , a, b);
}
void swap( int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter a and b values
10 20
before swapping a= 10 b=20
After swapping a= 10 b=20
To pass a single-dimension array as an argument in a function definition. There are three ways :
In the above program user pressed chatacter L (no need to press enter key to terminate) , getch() function will
not show L during inputting.
2) getche(): It is same as getch() function but it will display input character. get stands for input, ch
stands for character, e stands for echo(display). This function will not require enter key to terminate.
Syntax: char a = getch();
Here variable a contains character entered by user.
Program to read and display single character using getche()
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getche();
printf("The character is : %c\n",a);
}
Output:
Enter character
L
The character is : L
In the above program user pressed chatacter L (no need to press enter key to terminate) , getche() function
will not show L during inputting but it shows input character L after user screen is displayed.
3)getchar():Used to input single character .It will terminate by enter key after inputting a single
character. getchar() is a standard function and is present in <stdio.h>
Syntax: char a = getchar();
Here variable a contains character entered by user.
Program to read and display single character using getchar()
#include<stdio.h>
void main()
{
char a;
printf("Enter character\n ");
a = getchar();
printf("The character is : %c\n",a);
}
Output:
Enter character
L
The character is : L
File:
Generally, a file is used to store user data in a computer. In other words, computer stores the data using files.
we can define a file as follows.
File is a collection of data that stored on secondary memory like harddisk of a computer.
C programming language supports two types of files and they are as follows...
Example:
FILE * fp;
fp = fopen("file1.txt","r");
The above example code creates a new file called file1.txt if it does not exists otherwise it is opened
in reading mode.
When the reading or writing of a file is finished, the file should be closed properly using fclose() function.
The fclose() function does the following tasks:
Flushes any unwritten data from memory.
Discards any unread buffered input.
Frees any automatically allocated buffer
Finally, close the file
Syntax:
fclose( *fp )
Here this function closes the file which is pointed by file pointer fp
3) Reading from a file:The reading from a file operation is performed using the following pre-defined file handling
methods.
a.getc():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
Syntax:
getc( *filepointer )
Example:
FILE *fp;
fp = fopen("MySample.txt","r");
Char ch;
ch=getc(fp);
Here the variable ch contains the first character of the file "MySample.txt" which is pointed by file
pointer fp. To read entire contents in the file then while loop is used.
C program to demonstrate getc() function:
#include<stdio.h> MySample.txt
void main()
{ Welcome
FILE *fp;
char ch;
fp = fopen("MySample.txt","r");
if(fp==NULL)
printf("error to open file\n");
while((ch=getc(fp))!=EOF)
{
printf("%c", ch);
}
fclose(fp);
}
Output:
Welcome
b.getw():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.
Syntax:
getw( *filepointer )
Example:
FILE *fp;
fp = fopen("MySample.txt","r");
Char ch;
ch=getw(fp);
Here the variable ch contains the first character of the file "MySample.txt" which is pointed by file
pointer fp. To read entire contents in the file then while loop is used.
c.fscanf():This function is used to read multiple datatype values from specified file which is opened in reading mode.
Syntax:
fscanf(fp, typeSpecifier, &variableName )
Here fp is a file pointer
Example:
FILE *fp; file.txt
fp = fopen("file.txt","r")
fscanf(fp,”%s%s%d”,s1,s2,&y); Welcome to 2020
here s1 and s2 are character variables and
y is integer variable
the above function reads the contents of
file pointed by file pointer fp and stores them in specified variable i.e s1 contains welcome ,s2 contains
to and y contains 2020
C program to demonstrate fscanf() function:
#include<stdio.h>
void main()
{
char s1[10], s2[10]; file.txt
int y;
Welcome to 2020
FILE * fp;
fp = fopen ("file.txt", "r");
if(fp==NULL)
printf("error to open file\n");
fscanf (fp, "%s %s %d", s1, s2, &y);
printf("Read String1 - %s\n", s1 );
printf("Read String2 - %s\n", s2 );
printf("Read Integer - %d", y );
fclose(fp);
}
Output:
Read String1 - Welcome
Read String2 - to
Read Integer - 2020
d.fgets(): This method 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.
Syntax:
fgets( str, n, fp)
Here str is a character array variable, fp is a file pointer , n is no:of characters to be read
Example:
FILE *fp; file.txt
fp = fopen("file.txt","r"); Welcome to 2020
fgets( str, 8, fp);
here str is a character variable which contains 1st 7 characters(i.e n-1 characters) of file,txt
o/p: welcome
#include<stdio.h> file.txt
void main()
Welcome to 2020
{
FILE *fp;
char str[20];
fp = fopen ("file.txt", "r");
if(fp==NULL)
printf("error to open file\n");
fgets(str,16,fp);
printf("%s", str);
fclose(fp);
}
Output:
Welcome to 2020
e.fread():This function is used to read specific number of sequence of characters from the specified file which is
opened in reading mode.
Syntax:
fread( str, sizeof(char), n, fp)
Here str is a character array variable, fp is a file pointer , n is no:of characters to be read
Example:
FILE *fp; file.txt
fp = fopen("file.txt","r");
fread( str, 7, fp); Welcome to 2020
here str is a character variable which contains 1st 7 characters of file,txt
o/p: welcome
4. Writing data into a file: The writing into a file operation is performed using the following pre-defined file
handling methods.
a) putc():This function is used to write/insert a character to the specified file when the file is opened in writing mode.
Syntax:
putc(character,fp)
Here character is letter which is to be inserted into file and fp is the filepointer
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
putc(„A‟, fp ); A
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“file.txt","w");
if(fp==NULL)
printf("error to open file\n");
putc(„A‟, fp );
fclose(fp);
}
output: file.txt
b)putw() - This function is used to writes/inserts an integer value to the specified file when the file is opened in
writing mode.
Syntax:
putw(integervalue,fp)
Here integervalue is a digit which is to be inserted into file and fp is the filepointer
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
putw(20, fp ); 20
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“file.txt","w");
if(fp==NULL)
printf("error to open file\n");
putw(20, fp );
fclose(fp);
}
output: file.txt
20
c)fprintf() - 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.
Syntax:
fprintf (fp ,”text”)
Here fp is the filepointer and text is a string which is to be inserted into file
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fprintf (fp ,” Welcome to 2020”); Welcome to 2020
Welcome to 2020
d) fputs( ) - This method is used to insert string data into specified file which is opened in writing mode.
Syntax:
fputs( "string", fp )
Here fp is the filepointer and string which is to be inserted into file
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fputs(fp ,” Welcome to 2020”); Welcome to 2020
Welcome to 2020
e)fwrite() - This function is used to insert specified number of characters into a binary file which is opened in writing
mode.
Syntax:
fwrite( “StringData”, sizeof(char), N , fp)
Here fp is the filepointer
StringData is string which is to be inserted into file
N is no:of characters to be nserted
Example:
FILE *fp; file.txt output: file.txt
fp = fopen("file.txt","w");
fwrite( “Welcome to 2020”, sizeof(char), 15 , fp) Welcome to 2020
Welcome to 2020
Text versus Binary Streams: Difference between text file and binary file
Text file is human readable because everything is stored in terms of text. In binary file everything is written in
terms of 0 and 1, therefore binary file is not human readable.
A newline(\n) character is converted into the carriage return-linefeed combination before being written to the
disk. In binary file, these conversions will not take place.
In text file, a special character(newline), whose ASCII value is 26, is inserted after the last character in the file
to mark the end of file. There is no such special character present in the binary mode files to mark the end of
file.
In text file, the text and characters are stored one character per byte. For example, the integer value 1245 will
occupy 2 bytes in memory but it will occupy 5 bytes in text file. In binary file, the integer value 1245 will
occupy 2 bytes in memory as well as in file.
Recursion
Examples:
Factorial( n ) = 1 if n equals to 0
#include<stdio.h>
int factorial( int );
int main( )
{
int fact, n;
printf(“Enter any positive integer\n ”);
scanf(“%d”, &n);
fact = factorial( n );
printf(“Factorial of is %d”, fact);
return 0;
}
int factorial( int n )
{
int f;
if( n = = 0)
return 1;
else
f = n * factorial( n-1 );
return f;
}
Output:
Enter any positive integer
3
Factorial of is 6
#include <stdio.h>
int gcd(int , int);
int main()
{
int n1, n2,result;
printf("Enter two positive integers\n");
scanf("%d%d", &n1, &n2);
result = gcd(n1 , n2);
printf("G.C.D is %d\n", result);
return 0;
}
int gcd(int n1 , int n2)
{
if (n2 == 0)
return n1;
else
return gcd( n2, n1 % n2);
}
Output:
Enter two positive integers
36 24
G.C.D is 12