Unit Iv
Unit Iv
Functions: Basics - definition - Elements of User defined Functions - return statement, Function types,
Parameter Passing Techniques, Function returning more values - Passing Array to Functions - Recursion -
Storage classes.
INTRODUCTION TO FUNCTIONS
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. Functions are used to perform certain actions, and they are
important for reusing code: Define the code once, and use it many times.
A function is a set of instruction that perform a specified task. The function is represented
using braces “( )”.
Example:
sqrt( ), add( ), strlen( ) etc.,
TYPES OF FUNCTIONS
There are two types of functions in C Language. They are
a. Pre-defined functions
b. User Defined functions
Pre-defined functions
The pre-defined function is defined previously in C Library. User cannot understand
internal working of predefined functions. User cannot change or modify predefined function.
Example:
sqrt( )
clrscr( )
strcmp( )
strlen( ) etc.,
#include<stdio.h>
#include<conio.h>
#include<math.h>
main ( ){
int x,y;
clrscr ( );
printf ("enter a positive number");
scanf (" %d", &x)
y = sqrt(x);
printf("squareroot = %d", y);
getch();
}
Output:
Enter a positive number 25
Squareroot = 5
User-defined functions
The user-defined functions are defined by the user according to the requirement. User can
understand internal working of user defined function. The user can change or modify user
defined functions according to their need.
Example:
add( )
subtract( )
swap( )
square( )
insert( ) etc.,
#include<stdio.h>
#include<conio.h>
void add(int,int); //function declaration
void main()
{
int a,b;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
add(a,b); //Function call
getch();
}
void add(int x,int y) //Function Definition
{
int c;
c=x+y;
printf("\nSum=%d",c);
}
Output
Enter 2 numbers: 5 6
Sum = 11
2. Write a C program to add 2-numbers using function (with return values)
#include<stdio.h>
#include<conio.h>
int add(int,int); //function declaration
void main()
{
int a,b,c;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
c=add(a,b); //Function call
printf("\nSum=%d",c);
getch();
}
int add(int x,int y) //Function definition
{
int z;
z=x+y;
return(z);
}
Output
Enter 2 numbers: 5 6
Sum = 11
1. Function Declaration
The functions are declared before they defined or called. The declaration indicates varies
types like void, int, float, char.
Syntax
function_type function_name(parameter_lists);
Here,Function_type It specifies return type of the function
void When the function does not return any values, it is declared as void.
int When the function returns an integer value, it is declared as int.
float When the function returns a floating point value, it is declared as float.
char When the function returns a character, it is declared as char.
Function_name It specifies name of the function. It should follow the rules of an
identifier.
Parameter_list It specifies data type of parameters passed through the function
Terminating Symbol (;) Function declaration should terminate with semicolon.
Example
void add(int,int);
int add(int,int);
2. Function Call
Calling or invoking the function where it is required. The function is called by specifying
the name and its parameter. Function call is of two types.
a. Call by value
b. Call by reference
Call by value
When a function is called using value of its argument is called as Call by Value. When a
function is called, its argument passes a value to the function.
Syntax
function_name(actual_parameter1, actual_parameter2... actual_parametern);
Here,
Function_name It specifies name of the function. It should be same as function name
used in function declaration. Mismatch of function name will cause error.
Actual Parameter_list It includes variables of the value to be passed from main function
to the called function.
Example
add(a,b);
area(radius);
swap(a,b);
#include<stdio.h>
#include<conio.h>
void swap(int,int); //Function declaration
void main()
{
int a,b;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\nValue before swapping");
printf("\na=%d\nb=%d",a,b);
swap(a,b); //Function call i.e., Call by value
getch();
}
void swap(int a,int b) //Function definition
{
int t;
t=a;
a=b;
b=t;
printf("\nValue after swapping");
printf("\na=%d\nb=%d",a,b);}
Output
Enter 2 numbers: 5 6
Value before swapping
a=5
b=6
Value after swapping
a=6
b=5
Call by reference
When a function is called using address of its argument is called as Call by Reference.
When a function is called, argument passes its address to the function.
Syntax
function_name(&actual_parameter1, &actual_parameter2... &actual_parametern);
Here,
Function_name It specifies name of the function. It should be same as function name
used in function declaration. Mismatch of function name will cause error.
Actual Parameter_list It includes address of variables whose value is to be passed from
main function to the called function.
Example
add(&a,&b);
area(&radius);
swap(&a,&b);
#include<stdio.h>
#include<conio.h>
void swap(int*,int*); //Function declaration
void main()
{
int a,b;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\nValue before swapping");
printf("\na=%d\nb=%d",a,b);
swap(&a,&b); //Function call i.e., Call by reference
getch();
}
void swap(int *a,int *b) //Function definition
{
int *t;
*t=*a;
*a=*b;
*b=*t;
printf("\nValue after swapping");
printf("\na=%d\nb=%d",*a,*b);
}
Output
Enter 2 numbers: 5 6
Value before swapping
a=5
b=6
Value after swapping
a=6
b=5
3. Function Definition
Function definition is an independent module which contains the working or set of
instructions of the function. Function definition consists of two main parts.
A. Function header.
B. Function body.
Syntax
function_type function_name(parameter_list) //Function header
{
Local variable declaration;
Body of function; //Function Body
Return statement(Optional);
}
A. Function header
Function header is contain various components stated below,
i. Function_type
It specifies the type of the function based on its return value.
void When the function does not return any values, it is declared as void.
int When the function returns an integer value, it is declared as int.
float When the function returns a floating point value, it is declared as float.
ii. Function_name
It specifies the name of the function. Function name should be a valid identifier. It should
start with alphabet. There should not be white space in function name. Special symbol
underscore (_) only can be used in function name.
iii. Parameter List
Parameters are also called as arguments. The parameters are separated by comma (,)
operator. There are two types of parameters.
a. Actual Parameter
Parameters transferred from the main program to the function definition. Parameters used
within main function are called as Actual parameter.
b. Formal Parameter
Parameters used outside the main function is called are Formal parameter. It is used
within the function definition. Parameters transferred from the function to the main program.
a. Pass by value
b. Pass by reference
Pass by value
When a function is called using value of its argument is called as Pass by Value. When a
function is called, its argument passes a value to the function. It is also called as call by value.
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.
Syntax
function_name(actual_parameter1, actual_parameter2... actual_parametern);
Here,
Function_name It specifies name of the function. It should be same as function name
used in function declaration. Mismatch of function name will cause error.
Actual Parameter_list It includes variables of the value to be passed from main function
to the called function.
Example
add(a,b);
area(radius);
swap(a,b);
Pass by reference
When a function is called using address of its argument is called as Pass by Reference.
When a function is called, argument passes its address to the function. It is also called as Call by
Reference. In Call by Reference parameter passing method, the memory location address of the
actual parameters is copied to formal parameters. This address is used to access the memory
locations of the actual parameters in called function. In this method of parameter passing, the
formal parameters must be pointer variables.
That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters (pointers).
Whenever we use these formal parameters in called function, they directly access the memory
locations of actual parameters. So the changes made on the formal parameters effects the
values of actual parameters.
Syntax
function_name(&actual_parameter1, &actual_parameter2... &actual_parametern);
Here,
Function_name It specifies name of the function. It should be same as function name
used in function declaration. Mismatch of function name will cause error.
Actual Parameter_list It includes address of variables whose value is to be passed from
main function to the called function.
Example
add(&a,&b);
area(&radius);
swap(&a,&b);
Example Program
Swapping of two numbers and changing the value of a variable using pass by reference
#include<stdio.h>
#include<conio.h>
void swap(int*,int*); //Function declaration
void main()
{
int a,b;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\nValue before swapping");
printf("\na=%d\nb=%d",a,b);
swap(&a,&b); //Function call i.e., Call by reference
getch();
}
void swap(int *a,int *b) //Function definition
{
int *t;
*t=*a;
*a=*b;
*b=*t;
printf("\nValue after swapping");
printf("\na=%d\nb=%d",*a,*b);
}
Output
Enter 2 numbers: 5 6
Value before swapping
a=5 b=6
Value after swapping
a=6 b=5
1. By using pointers.
2. By using structures.
3. By using Arrays.
#include <stdio.h>
void compare(int a, int b, int* add_great, int* add_small)
{
if (a > b) {
*add_great = a;
*add_small = b;
}
else {
*add_great = b;
*add_small = a;
}
}
int main()
{
int great, small, x, y;
printf("Enter two numbers: \n");
scanf("%d%d", &x, &y);
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Output:
8
4
Here, we have passed array parameters to the display() function in the same way we pass
variables to a function.
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
However, notice the use of [] in the function definition.
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers: Displaying:
2 2
3 3
4 4
5 5
Notice the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays
with more than 2 dimensions as a function argument.
When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.
For example,
Program
1. Write a C program to find the factorial of given number using recursion
Factorial of 5 5 * 4 * 3 * 2 * 1 = 120
Recursion can be applied by the following logic
fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1
Substitute the values of function from bottom to top to obtain fact(5) = 120.
#include<stdio.h>
int fact(int); //Function declaration
void main()
{
int n;
clrscr();
printf("Enter number: ");
scanf("%d",&n);
printf("Factorial of %d = %d",n,fact(n)); //Function Call
getch();
}
int fact(int n) //Function definition
{
if(n!=1)
n=n*fact(n-1); //Recursive function call
return n;
}
Output
Enter number: 5
Factorial of 5 is 120
2. Write a C program to find the sum of n-natural numbers using recursive function
#include<stdio.h>
int sum(int); //Function Declaration
void main()
{
int n;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Sum = %d",sum(n)); //Function Call
getch();
}
int sum(int n) //Function Definition
{
if(n!=0)
n=n+sum(n-1); //Recursive function call
return n;
}
Output
Enter a positive number: 5
Sum=15
STORAGE CLASSES
Storage classes are used to define the scope and lifetime of a variable. There are four
main storage classes used in C language.
i. Auto ii. Static
iii. Register iv. extern
i. Auto
Auto is a default storage class of a variable. The scope of automatic variable is valid only
within the specified block. The value is allocated automatically when the block starts and
automatically freed when the block is exit.
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=5;
clrscr();
printf("\nValue of i is %d",i);
if(i==5)
{
auto i=3; //Value of ‘i’ will be 3 only within this if
block
printf("\nValue of i is %d",i);
}
printf("\nValue of i is %d",i); //here value of ‘i’ will be 5
getch();
}
Output
Value of i is 5
Value of i is 3
Value of i is 5
ii. static
The value of static variable persists/remains until the end of the program. It can be
declared using the keyword static.
Example program1
#include<stdio.h>
#include<conio.h>
void increment(void);
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
void increment()
{
static int i=1; /*This initialize remains until the end of the program. i.e.,
Initialized only once */
printf("%d\n",i);
i=i+1;
}
Output
1
2
3
Example program2
#include<stdio.h>
#include<conio.h>
void increment(void);
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
void increment()
{
int i=1; /*This initialize each time compiler executes this line. i.e.,
Initialized each time function is called */
printf("%d\n",i);
i=i+1;
}
Output
1
1
1
iii. register
Register is used to define local variable that should be stored in an internal register
instead of in main memory. Here that variable has maximum size equal to the size of an internal
register.
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
register int a=200;
clrscr();
printf("\nValue of a is %d",a);
getch();
}
Output
Value of a is 200
iv. extern
External variables are declared outside the function body. If user declare external variable
in the program, there is no need to pass these variables to another function. The compiler does
not allocate memory for these variables. It is already allocated for it in another module where it
is declared as a global variable.
Example program
#include<stdio.h>
#include<conio.h>
int i=100;
void fun1(void);
void fun2(void);
void main()
{
clrscr();
fun1();
fun2();
printf("\nValue of i in main function is %d",i);
getch();
}
void fun1()
{
int i=200;
printf("\nValue of i in function1 is %d",i);
}
void fun2()
{
printf("\nValue of i in function2 is %d",i);
}
Output
Value of i in function1 is 200
Value of i in function2 is 100
Value of i in main function is 100
Function Prototypes
Function prototype tells compiler about number of parameters function takes, data-
types of parameters and return type of function. By using this information, compiler cross
checks function parameters and their data-type with function definition and function call. If we
ignore function prototype, program may compile with warning, and may work properly. Based
on return type and its parameter function may be classified into four types or categories. They
are,
Function with no argument and no return value.
Function with argument and no return value.
Function with no argument and with return value.
Function with argument and return value.
1 Function with no argument and no return value.
This type of function has no arguments which are to be passed to the called function and also
has no return value. In such situation,
Will be performed in “called function” itself. Here there is no transfer of values between the
“calling function” and “called function”.
Syntax for function declaration of above type
void function_name(void);
Example for function declaration of above type
void sum(void);
Program
#include<stdio.h>
#include<conio.h>
void sum(void); //Function declaration
void main()
{
sum(); //Function call without arguments
}
void sum() //Function Definition with no return value
{
int a,b,c;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
c=a+b;
printf("Sum=%d",c);
getch();
}
Output
Enter 2 numbers: 2 3
Sum = 5
A function has arguments which are to be passed to the “called function”. Here input
value is read in “calling function” (i.e., Main function) and it is passed to the “called function”.
A function has no return value, in this category obtained result is displayed in “called function”
itself.
Syntax for function declaration of above type
void function_name(data type of parameter list);
void sum(int,int);
Program
#include<stdio.h>
#include<conio.h>
void sum(int,int); //Function Declaration
void main()
{
int a,b;
clrscr();
printf("\nEnter two values:");
scanf("%d%d",&a,&b);
sum(a,b); //Function Call with arguments
getch();
}
void sum(int a,int b) //Function Definition with no return value
{
int c;
c=a+b;
printf("Sum=%d",c);
}
Output
Enter 2 numbers: 4 3
Sum = 7
A function has no arguments; in this category “called function” read data from input
terminal but it has return value. Hence result will be displayed in “calling function” which is
return by the “called function”.
Syntax for function declaration of above type
data_type function_name(void);
Example for function declaration of above type
int sum(void); //Returns an integer value
Program
#include<stdio.h>
#include<conio.h>
int sum(void); //Function declaration
void main()
{
int c;
clrscr();
c=sum(); //Function Call with no arguments passed inside it
printf("\nSum=%d",c);
getch();
}
int sum() //Function definition with return value
{
int a,b,c;
printf("\nEnter two values:");
scanf("%d%d",&a,&b);
c=a+b;
return(c);
}
Output
Enter 2 numbers: 4 7
Sum = 11
A function with arguments in which “calling function” read data from input terminal and pass
it to the “called function”. Process is carried out in the “called function” and returns the result
back to the main function. In this category,
Getting input value&
Displaying the result
#include<stdio.h>
#include<conio.h>
int sum(int,int); //Function declaration
void main()
{
int a,b,c;
clrscr();
printf("\nEnter two values:");
scanf("%d%d",&a,&b);
c=sum(a,b); //Function Call with parameters
printf("\nSum=%d",c);
getch();
}
int sum(int a,int b) //Function Definition with return values
{
int c;
c=a+b;
return(c);
}
Output
Enter 2 numbers: 4 7
Sum = 11