Function
Function
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
USES OF C FUNCTIONS:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever
required.
We can call functions any number of times in a program and from any place in a
program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
1
Components of function program:
There are three components in function program in C. They are,
Function declaration or prototype – This informs compiler about the function name,
function parameters and return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to be executed.
Function prototype: The ANSI C standard introduces function prototypes. Functions should be
declared before they are used. ANSI C provide for new function declaration syntax called
function prototype. Using functions in our program requires declaring the function (function
prototype). Later we can implement the function. The prototype tells the compiler in advance
some characteristics (name of function, return type and parameters) of function. A function
prototype takes the form:
return-type function_name (parameter list)
For example:
int maximum (int, int);
2
float area();a function with return type and no parameter
The first function returns no value, and no arguments, second prototype returns an integer
value and has two arguments of integer type, third prototype returns no value and has three
arguments of integer type, fourth prototype returns a float value and no arguments.
Function definition: The definition of a function is the actual body of the function. It starts with
function header, which is the same as the function prototype but does not end with a
semicolon. The function prototype and the definition must have exactly the same return type,
name and parameter list. If they do not match the compiler will issue error messages during
compilation. A function definition consists of two parts – function header and body of the
function. The function name, return type, and the parameter-list is the header of the function.
The function body is enclosed in curly braces, immediately follows the function header. When a
function is called execution begins at the start of the function body and terminates (returns to
the calling program) when a return statement is encountered or when execution reaches the
closing braces (}). Variable declaration can be made within the body of a function.
The general syntax of the function definition is as follows
return-value-type function-name(parameter-list){
............................../* declaration section*/
...................../* statement sections*/
}
Here the function-name is any valid identifier, return-value-type is data type (int, float or void
etc) of the result and defaults is int use void indicates that the function returns nothing
parameter-list is comma separated list, declares parameter variables.
Consider an example
/* Function definition*/
int maximum (int a, int b )
{
if(a>b)
return a;
else
return b;
}
Function call: When function is called its code gets executed. Call a function by specifying its
name, followed by list of a parameters enclosed in parentheses and separated by commas.
For example, c = maximum (a, b);
There are two ways that arguments can be passed to a function. The first is known as call by
value. This method copies the value of an argument into the formal parameter of the
subroutine. In this case, changes made to the parameters have no effect on the argument. Call
by reference is the second way of passing arguments to a function. In this method, the address
of an argument is copied into the parameter. Inside the function the address is used to access
the actual argument used in the call. This means that changes made to the parameter affect the
argument. Let us combine all these three components function prototype, function call, and
3
function definition constitute a program that finds the maximum of any two numbers using the
function.
Program to find maximum of any two numbers using function.
#include<stdio.h>
int great(int, int); /* a function prototype */
int main()
{
int x, y, z;
printf("\n Enter two different integer values");
scanf("%d%d", &x, &y);
z = great(x,y); /* Function call */
printf("\n The larger value is %d", z);
return 0 ;
}
/* a function definition */
int great (int x, int y)
{
if(x>y)
return x;
else
return y;
}
Actual arguments and Formal arguments :
The calling function sends some values to the called function for communication, these values
are called arguments or parameters. We can pass information to a function by means of the
arguments that we specify when we call a function.
Actual arguments: The arguments which are mentioned in the function call are known as
actual arguments. These arguments are defined in the calling function.
example:
#include <stdio.h>
void sum(int , int , int );
int main() {
int a = 5;
int b=4;
int c =10;
// actual arguments
sum(a, b, c);
return 0; }
4
/* called function */
/* formal arguments*/
void sum(int a, int b, int c)
{ int s;
s = x + y + z;
printf("sum is %d", s); }
Here 3,2*a,a are actual arguments and i,j,k are formal arguments.
Formal arguments: The names of the arguments which are mentioned in the function
definition are called formal arguments. The formal parameters are treated as local variable
within that function and they will take preference over the global variable.
1. Order, number, and type of the actual arguments in the function call must match with
formal arguments of the function.
2. If there is type mismatch between actual and formal arguments then the compiler will
try to convert the type of actual arguments to formal arguments if it is legal, otherwise,
a garbage value will be passed to the formal argument.
3. Changes made in the formal argument do not affect the actual arguments.
Return types: The return keyword is used to return the program control from a function to the
calling function. Functions can return arithmetic values (int, float etc), structures, unions,
pointers or void. If the return type is specified as being void, then no value is returned by the
function. Functions cannot return a function an array.
5
#include<stdio.h>
int add(int,int);
int main()
{
int a, b,c;
printf("enter the value of a and b);
scanf("%d%d", &a,&b);
c = add(a,b);
printf("The sum of two number is %d", c);
return 0;
}
int add(int x, int y)
{
int s;
s= x+y;
return s;
}
Based function return type, the function can be classified into four categories on the basis of
the arguments and return value.
Function with no arguments and no return value.
Function with no arguments and a return value.
Function with arguments and no return value.
Function with arguments and a return value.
1. Function with no arguments and no return value: When a function has no arguments, it
does not receive any data from the calling function. Similarly when it does not return a
value, the calling function does not receive any data from the called function. Thus in such
type of functions, there is no data to transfer between the calling function and the called
function.
Syntax :
6
Example:
#include<stdio.h>
void add (); / * function prototype * /
int main()
{
add (); / * function call * /
return 0;
/ * function definition * /
void add()
{
int a, b, sum;
printf("\n Enter two numbers: ") ;
scanf("%d%d", &a, &d ) ;
sum = a + b ;
printf("\n The sum is %d", sum) ;
}
2. Function with no arguments and a return value: These types of functions do not receive
any arguments but they can return a value. The general structure of the program using this
kind of function is as follows:
Syntax:
int func();
int main()
{
int r;
.......
r = func();
.......
return 0;
}
int func(void)
{
........
........
return (expressions) ;
}
7
Example:
# include<stdio.h>
int add(void);
int main ()
{
int z;
z= add();
printf ("\n The sum is %d\n", z);
return 0;
}
int add(void)
{
int n1, n2, sum;
printf ("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
sum = n1+n2;
return (sum);
}
3. Functions with arguments and no return values
These types of functions have arguments, hence the calling function can send data to the
called function, but the called function does not return any value. The general form of the
program structure using this kingd of function can be written as:
void func (int, int) ;
int main()
{
............
r = func (a,b);
............
return 0;
}
void func( int c, int d)
{
.............
statements
8
.............
}
Example:
#include<stdio.h>
void add(int, int); /*function prototype*/
int main ()
{
int a, b;
printf("\n Enter two numbers:");
scanf ("%d%d", &a,&b);
add(a,b) ;
return 0;
}
/* Function definition */
void add(int x, int y)
{
int sum;
sum = x+y;
printf("\n The sum is %d",sum) ;
}
4. Functions with arguments and return values:
These types of functions have arguments, so the calling function can send data to the called
function, it can also return any values to the calling function using return statement. The
structure of a program using this type of function can be written as follows:
int func(int, int);
int main()
{
int r;
.........
r = func(a,b);
..................
return 0;
}
int function(int a, int b)
{
............
..................
return(expression);}
9
The following program demonstrates the use of function with argument and return value.
Example:
#include<stdio.h>
int add(int, int); /*Function Prototype*/
int main()
{
int a, b, sum;
printf("\n Enter two numbers:");
scanf("%d%d", &a, &b);
sum =add(a,b); /*Function call*/
printf("The sum of two number is \t%d", sum);
}
/*Function definition*/
int add(int x, int y)
{
int sum;
sum = x+y ;
return sum;
}
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
10
Call by value in C
In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the function
call in the call by value method.
In call by value method, we cannot modify the value of the actual parameter by the formal
parameter.
In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Example
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
11
Call by Value Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
return 0;
// The value of actual parameters do not change by changing the formal parameters in call
by value, a = 10, b = 20
}
void swap (int x, int y)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
// Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual
parameter.
The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the
address of the actual parameters, and the modified value gets stored at the same address.
12
Example: Call by reference.
#include <stdio.h>
void swap(int *, int *); //prototype of the function i
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The values of actual parameters do change in call by reference, a = 10, b = 20
return 0;
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
// Formal parameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Difference between call by value and call by reference in c
No. Call by value Call by reference
1 A copy of the value is passed into the An address of value is passed into the function
function
2 Changes made inside the function are Changes made inside the function validate
limited to the function only. The outside of the function also. The values of the
values of the actual parameters do actual parameters do change by changing the
not change by changing the formal formal parameters.
parameters.
3 Actual and formal arguments are Actual and formal arguments are created at the
created at the different memory same memory location
location
13
Passing 1D and 2D array to a function
Like any other variables, we can also pass entire array to a function. An array name can be
named as an argument for the prototype declaration in function header. When we call the
function no need to subscript or square brackets. When we pass array that pass as a call by
reference because the array name is address for that array. When an array is passed, its base
address is passed as call by- value. The array elements themselves are not copied.
The general form of passing array to the function is as follows.
void sum (int[], int); /* Function prototype*/
void addMatrix(int [] [], int, int);
int main()
{
...........
int a[10];
int mat[3][3];
..................
sum(a, 10); /* calling function passing single dimensional array a, and size 10 */
addMatrix(mat, 3, 3);
/* calling function passing two dimensional array mat and 3 rows and 3 columns */
...............
return 0;
}
Example 1: Program to demonstrate the passing structure to the function
#include<stdio.h>
struct student
{
char name[20];
int rollno;
float percent;
}s1;
void display(struct student s1);
void main()
{
printf("Enter the name of student");
scanf("%s", s1.name);
printf("enter the roll number");
scanf("%d", &s1.rollno);
printf("Enter the percent");
scanf("%f", &s1.percent);
14
display(s1);
}
display(struct student s1)
{
printf("The name of student is %s\n ", s1.name);
printf("The roll number is %d\n", s1.rollno);
printf("The percent is %f\n", s1.percent);
}
Example 2: WAP a program to read 20 numbers in an array and find their sum and display using
the function.
#include<stdio.h>
int sum(int a[]); /* function prototype */
int main()
{
int a[20], s, i;
printf("\n Enter 20 elements");
for(i=0;i<20;i++)
scanf("%d", &a[i]);
output(a);
s=sum(a);
printf("\n Sum of array element is :%d\t",s);
return 0;
}
int sum(int a[])
{
int i, add=0;
for(i=0;i<20;i++)
add = add+a[i];
return (add);
}
void output(int a[])
{
int i;
printf("The elements of array are:\n");
for(i=0;i<20;i++)
printf("%d\t", a[i]);
}
15
Example 3: Program to find the minimum value in an array by passing array to function
#include<stdio.h>
#define N 10
int minimum(int[]); /* function prototype */
int main()
{
int scores[10], i, minScore;
printf("\n Enter 10 scores");
for(i=0;i<N;i++)
scanf("%d", &scores[i]);
minScore = minimum(scores); /*passing scores to function */
printf("\n Minimum score is: %d\n", minScore);
return 0;
}
int minimum (int values[]) /* Function definition */
{
int i, minValue, value[10];
minValue= value[0]; 254789631 0
for(i=1;i<N;i++)
if(values[i]<minValue)
minValue= values[i];
return minValue;
}
Passing structure to a function
A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It won’t be available to other functions unless it is passed to those functions by value or by
address (reference).
Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the
functions in a C program.
16
Passing structure to function in c by value
In this type of program, the whole structure is passed to another function by value. It means
the whole structure is passed to another function with all members and their values. So, this
structure can be accessed from called function. This concept is very useful while writing very big
programs in C.
Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Passing structure to function in C by address:
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.
17
Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Recursion in C programming
Recursion is a programming technique that allows the programmer to express operations in
terms of themselves. In C, this takes the form of a function that calls itself. A useful way to
think of recursive functions is to imagine them as a process being performed where one of the
instructions is to "repeat the process". Recursion is the process of repeating items in a self-
similar way. In programming languages, if a program allows you to call a function inside the
same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
18
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function;
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.
A recursive function is one that calls itself directly or indirectly to solve a smaller version of its
task until a final call which does not require a self-call. Thus, the function is called recursive
function if it calls to itself and recursion is a process by which a function call itself repeatedly
until some specified condition will satisfied. This process is used for repetitive computations in
which each action is stated in term of previous result.
Example1: Program to compute the factorial of a number using recursion
#include<stdio.h>
long fact(int);
int main()
{
int a, result;
printf("\n Enter a number :");
scanf("%d", &a);
result =fact(a);
printf("\n The factorial of the %d number is %ld", a, result);
return 0;
}
long fact(int n)
{
if(n==0)
return 1; /*Base case */
else
return (n*fact(n-1));
}
Example 2: Program to add the first n- natural numbers using recursive function
#include<stdio.h>
int add (int);
int main()
{
int num, sum=0;
printf("Enter positive number:");
scanf("%d", &num);
sum = sum +add(num);
19
printf("Sum =%d", sum);
return 0;
}
int add (int num)
{
if(num!=0)
return num + add(num-1);
else
return 0;
}
Example 3: Program to calculate xn using recursive function
#include<stdio.h>
long power(int, int);
int main()
{
int x, n, p;
printf("Enter the value of x and n:");
scanf("%d%d", &x, &n);
p = power(x,n);
printf("Power =%ld", p);
return 0;
}
long power (int x, int n)
{
if(n==0)
return 1;
else
return x *power(x, n-1) ;
}
Macro: A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-
processor, the block of code is communicated to the compiler before entering into the actual coding
(main () function). A macro is defined with the preprocessor directive. A macro is a piece of code in a
program that is replaced by the value of the macro. Macro is defined by #define directive.
Whenever a micro name is encountered by the compiler, it replaces the name with the
definition of the macro. Macro definitions need not be terminated by semi-colon (;). Macro
definition in C is generally can be defined by the programmer by any valid identifier as a macro, even
though it is a C keyword. The preprocessor operator defined cannot be defined as a macro in C
language.
20
Macros in C
Types of macros:
Predefined
Macros
Object like Function like
Macros Macros
Predefined Macros in C
Here is a table that summarizes some of the basic macros used in the C programming language:
1. _DATE_ – Used to represent the current date in MM DD YYYY format.
2. _STDC_ – Used to indicate when the compiler compiles the code successfully by returning
the value 1.
3. _TIME_ – Represent the current time in HH:MM:SS.
4. _LINE_ – Represent the current line number.
5. _FILE_ – Represent the current file name.
Here is a code in C that illustrates the use of macros
#include<stdio.h>
int main()
{
printf("Welcome to macro tutorials!\n");
printf("The current date is: %s\n", __DATE__ );
printf("The current time is: %s\n", __TIME__ );
printf("The total lines in the code is: %d\n", __LINE__ );
printf("The file name is: %s\n", __FILE__ );
printf("STDC would return the value: %d\n", __STDC__ ); // %d is used since it would return an
integer value
return 0;
}
Object-like Macros
It appears to be a symbolic constant. It can be termed as an alternative way to define an
identifier used to represent constant expressions. The simplest example would be:
#define PI 3.14
Example:
#include <stdio.h>
#define PI 3.1415
21
int main()
{
float radius,area;
printf("Please Enter the radius ");
scanf("%f", &radius);
//Here used the value of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
Function-like Macros
It is an expression, used to perform a particular operation. It is an alternative way to define a
function. A simple example would be:
#define SQUARE(x) ((x)*(x))
#define CUBE(x) ((x)*(x)*(x))
#define MAX(a, b) ((a)>(b)?(a):(b))
We can call these macro in our program as
a = PI*SQUARE(radius), which is equivalent to : a = PI*((radius)*(radius));
Example:
#include <stdio.h>
#define SQUARE(x) ((x)*(x))
#define AREA(x,y) ((x)*(y))
#define CUBE(x) ((x)*(x)*(x))
#define MAX(x, y) ((x)>(y)?(x):(y))
#define MIN(x, y) ((x)<(y)?(x):(y))
int main()
{
int x=10, y= 12;
printf("\n The Square of %d is %d", x, SQUARE(x));
printf("\n The cube of %d is %d", x, CUBE(x));
printf("\n The Maximum of %d and %d is %d", x,y, MAX(x,y));
printf("\n The Minimum of %d and %d is %d", x,y, MIN(x,y));
printf("\nThe area is %d", AREA(x,y));
return 0;}
Storage Classes in C
Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility and life-time which help us to trace the existence of a
particular variable during the runtime of a program. C language uses 4 storage classes, namely:
1. auto 2. extern 3. static 4. register:
22
ADVANTAGES OF USING A FUNCTION
Here are several advantages of using functions in your code:
1. Use of functions enhances the readability of a program. A big code is always difficult to
read. Breaking the code in smaller Functions keeps the program organized, easy to
understand and makes it reusable.
2. The C compiler follows top-to-down execution, so the control flow can be easily
managed in case of functions. The control will always come back to the main() function.
3. It reduces the complexity of a program and gives it a modular structure.
4. In case we need to test only a particular part of the program we will have to run the
whole program and figure out the errors which can be quite a complex process. Another
advantage here is that functions can be individually tested which is more convenient
than the above mentioned process.
5. A function can be used to create our own header file which can be used in any number
of programs i.e. the reusability.
23