Unit 6 Function
Unit 6 Function
Unit 6 Function
Function
THEORY
6.1 Definition
6.2 Function types (library, and user defined function)
6.3 Programming examples of simple user defined function.
6.4 Function call by Value and Call By Reference
6.5 Return type and Non return type functions
6.6 Function prototyping
6.7 Passing arguments to functions
PRACTICAL
1. Program to display “Welcome to My School” using function
2. Program to find the summation of two variables using function
3. Program to find the largest and smallest numbers using functions
4. Program to find the factorial of any integer variable using recursion
5. WAP to call function by Value and Call by Reference
C Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the set of
programming statements enclosed by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection of functions creates a program. The
function is also known as procedure or subroutine in other programming languages.
Advantage of functions in C
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C program.
Function Aspects
1. Function declaration A function must be declared globally in a c program to tell the compiler about the function
name, function parameters, and return type.
2. Function call Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in the
function declaration.
3. Function definition It contains the actual statements which are to be executed. It is the most important aspect
to which the control comes when the function is called. Here, we must notice that only one value can be
returned from the function.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(),
puts(), ceil(), floor() 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.
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place called the library. Such
functions are used to perform some specific operations. For example, printf is a library function used to print on the
console. The library functions are created by the designers of compilers. All C standard library functions are defined
inside the different header files saved with the extension .h. We need to include these header files in our program to
make use of the library functions defined in such header files. For example, To use the library functions such as
printf/scanf we need to include stdio.h in our program which is a header file that contains all the library functions
regarding standard input/output.
The list of mostly used header files is given in the following table.
4 stdlib.h This header file contains all the general library functions
like malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.
Function Declaration
General syntax for function declaration is,
returntype
function name
parameter list
terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any operation and is expected to provide with
some result at the end, in such cases, a return statement is added at the end of function body. Return type specifies
the type of value(int, float, char, double) that function is expected to return to the program which called the
function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function name is any valid C identifier
and therefore must follow the same naming rules like other variables in C language.
parameter list
The parameter list declares the type and number of arguments that the function expects when it is called. Also, the
parameters in the parameter list receives the argument values when the function is called. They are often referred
as formal parameters.
Let's write a simple program with a main() function, and a user defined function to multiply two numbers, which will
be called from the main() function.
#include<stdio.h>
int i, j, result;
return 0;
The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function header and
the statement(s) within curly braces is called function body.
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header, unlike while
declaring the function or calling the function.
functionbody
The function body contains the declarations and the statements(algorithm) necessary for performing the required
task. The body is enclosed within curly braces { ... } and consists of three parts.
a return statement to return the result evaluated by the function(if return type is void, then no return
statement is required).
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.
It is possible to have a function with parameters but no return type. It is not necessary, that if a function accepts
parameter(s), it must return a result too.
While declaring the function, we have declared two parameters a and b of type int. Therefore, while calling that
function, we need to pass two arguments; else we will get compilation error. And the two arguments passed should
be received in the function definition, which means that the function header in the function definition should have
the two parameters to hold the argument values. These received arguments are also known as formal parameters.
The name of the variables while declaring, calling and defining a function can be different.
Below, we will discuss about all these types, along with program examples.
Below is an example of a function, which takes 2 numbers as input from user, and display which is the greater
number.
int main() {
return 0; else
} {
void greatNum() // function definition printf("The greater number is: %d", j);
{ }
int i, j; }
We have modified the above example to make the function greatNum() return the number which is greater amongst
the 2 input numbers.
#include<stdio.h>
int main()
int result;
return 0;
int i, j, greaterNum;
if(i > j) {
greaterNum = i;
else {
greaterNum = j;
return greaterNum;
This time, we have modified the above example to make the function greatNum() take two int values as arguments,
but it will not be returning anything.
#include<stdio.h>
int main()
int i, j;
return 0;
if(x > y) {
else {
#include<stdio.h>
int main()
int i, j;
return 0;
if(x > y) {
}
else {
#include<stdio.h>
int main()
int i, j, result;
return 0;
if(x > y) {
return x;
else {
return y;
What is Recursion?
Recursion is a special way of nesting functions, where a function calls itself inside it. We must have certain conditions
in the function to break out of the recursion, otherwise recursion will occur infinite times.
function1()
// function1 body
function1();
// function1 body
#include<stdio.h>
void main()
int a, b;
printf("Enter a number...");
scanf("%d", &a);
printf("%d", b);
int r = 1;
if(x == 1)
return 1;
else
return r;
void recurse()
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the
recursive call, and other doesn't.
#include <stdio.h>
int main() {
scanf("%d", &number);
result = sum(number);
return 0;
int sum(int n) {
if (n != 0)
return n + sum(n-1);
else
return n;
Output
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to the sum() function. This
process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed returning the sum of integers ultimately to
the main() function.
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of
recursion. Recursion code is shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of
similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem
that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved
by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
#include <stdio.h>
int main()
int n,f;
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
int fact(int n)
if (n==0)
return 0;
else if ( n == 1)
return 1;
}
else
return n*fact(n-1);
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure given below:
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in
the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned
from the function.
The case at which the function doesn't recur is called the base case whereas the instances where the function keeps
calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this
format.
if (test_for_base)
return some_value;
else if (test_for_another_base)
return some_another_value;
else
// Statements;
recursive call;
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
#include<stdio.h>
int fibonacci(int);
void main ()
int n,f;
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
if (n==0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
Output
144
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 can not 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.
Let's try to understand the concept of call by value in c language by the example given below:
#include<stdio.h>
num=num+100;
int main() {
int x=100;
return 0;
Output
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.
#include<stdio.h>
(*num) += 100;
int main() {
int x=100;
return 0;
Output
3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location
That being said, recursion is an important concept. It is frequently used in data structure and algorithms. For
example, it is common to use recursion in problems such as tree traversal.
Practical
Example 1
#include<stdio.h>
void printName();
void main ()
printf("Hello ");
printName();
void printName()
printf("Javatpoint");
Output
Hello Javatpoint
Example 2
#include<stdio.h>
void sum();
void main()
sum();
void sum()
int a,b;
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
Output
24
The sum is 34
int sum();
void main()
int result;
result = sum();
printf("%d",result);
int sum()
int a,b;
scanf("%d %d",&a,&b);
return a+b;
Output
24
The sum is 34
int sum();
void main()
int square()
float side;
scanf("%f",&side);
Output
void main()
int a,b,c,d,e;
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
Output
20
30
40
50
int even_odd(int);
void main()
int n,flag=0;
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
else
int even_odd(int n)
if(n%2 == 0)
{
return 1;
else
return 0;
Output
Going to check whether a number is even or odd
Exercises
Short questions: