Unit 3-Final Notes
Unit 3-Final Notes
Introduction
Functions are just a block of code defined to perform a particular task. In this
way, if we break a complex program into functions, where each function
performs a much simpler task, the program will become simple to code and will
improve readability. The best thing about functions is that they can be reused
again and again throughout the program, whenever required. This also helps in
reducing repetitive codes in our program. We will see more about the
reusability of functions in C later in this article.
Types of functions
1) Predefined standard library functions
Standard library functions are also known as built-in functions. Functions such
as puts(), gets(), printf(), scanf() etc are standard library functions. These
functions are already defined in header files (files with .h extensions are called
header files such as stdio.h), so we just call them whenever there is a need to
use them.
1. Function declaration
2. Function definition
3. Function call
Function Declaration :
Function declaration means writing a name of a program. It is a compulsory part
for using functions in code. In a function declaration, we just specify the name
of a function that we are going to use in our program like a variable declaration.
We cannot use a function unless it is declared in a program. A function
declaration is also called “Function prototype.”
The function declarations (called prototype) are usually done above the main ()
function and take the general form:
We consider the following program that shows how to declare a cube function
to calculate the cube value of an integer variable
#include <stdio.h>
/*Function declaration*/
int add(int a,b);
int main() {
Keep in mind that a function does not necessarily return a value. In this case,
the keyword void is used.
Function Definition:
Function definition means just writing the body of a function. A body of a
function consists of statements which are going to perform a specific task. A
function body consists of a single or a block of statements. It is also a
mandatory part of a function.
OR
//Some code
return value;
}
Example:
int c;
c=a+b;
return c;
Function call :
A function call means calling a function whenever it is required in a program.
Whenever we call a function, it performs an operation for which it was
designed. A function call is an optional part of a program.
result = add(4,5);
#include <stdio.h>
int main()
int a=10,b=20;
printf("Addition:%d\n",c);
getch();
int c;
c=a+b;
return c;
Output:
Addition:30
Example: Program1
Program 2 :
Example of a function, which takes 2 numbers as input from user, and display
which is the greater number.
#include<stdio.h>
int main()
int i, j;
if(i > j)
else {
Example: Program1
#include<stdio.h>
int main()
int result;
result = greatNum(); // function call
return 0;
int i, j, greaterNum;
if(i > j) {
greaterNum = i;
else
greaterNum = j;
Syntax :
return_type function_name ( data_type argument1, data_type argument2,
... ) // Function Definition
{
// body of Statement ;
}
Example: Program1
//Function Declaration
void add(int,int);
int main()
{
int a,b;
printf("\nEnter The Value of A & B : ")l
scanf("%d%d",&a,&b);
//Function Calling
add(a,b); // Actual Parameters
return 0;
}
//Function Definition
void add(int x,int y) //Formal Parameters
{
int c;
c=x+y;
printf("\nTotal : %d",c);
}
Output
Enter The Value of A & B : 23 34
Total : 57
………………………………………………………………………..
Program 2 :
#include<stdio.h>
int main( )
int i, j;
return 0;
if(x > y)
else {
}
Function with arguments and a return value
Syntax :
return_type function_name ( data_type argument1, data_type argument2,
... ) // Function Definition
{
// body of Statement ;
}
Example: Program1
This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.
#include<stdio.h>
int main()
int i, j, result;
return 0;
if(x > y) {
return x;
else {
return y;
}
………………………………………………………………………….
• Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
• While calling a function, there are two ways in which arguments can be passed
to a function –
1) Call by Value
2) Call by Reference
The parameters passed to function are called actual parameters whereas the
parameters received by function are called formal parameters.
Call by Value in C:
In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in
different memory locations. So any changes made inside functions are not
reflected in actual parameters of caller.
In other words, in this parameter passing method, values of actual parameters
are copied to function's formal parameters, and the parameters are stored in
different memory locations. So any changes made inside functions are not
reflected in actual parameters of the caller.
#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);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
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);
}
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
Call by reference method copies the address of an argument into the formal
parameter. In this method, the address is used to access the actual argument
used in the function call. It means that changes made in the parameter alter the
passing argument.
In this method, the memory allocation is the same as the actual parameters. All
the operations in the function are performed on the value stored at the address of
the actual parameter, and the modified value will be stored at the same address.
Means, both the actual and formal parameters refer to same locations, so any
changes made inside the function are actually reflected in actual parameters of
caller.
Call by reference Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main() 4. {
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
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);
}
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
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output:
1234567890
Advantages of Functions in C
The most important advantage of functions is that they allow code
reusability. We don't need to write the same code, again and again, we
can just declare a function and keep calling it whenever required.
Functions help divide the complete program into parts, where each part
performs a specific task. This makes the code clean and easier to
understand.
Functions help achieve code modularity, which means the entire code is
separated into different blocks, where each is independent of the other
and performs a different task. This helps in the easier implementation and
debugging of the individual blocks.
You can write new code in a function without disturbing or altering the
previously written code in the main program.
Sample Program:
// Displaying output
printf("Arithmetic operations on %d and %d: \n", num1, num2);
printf("Addition: %d\n", addition(num1, num2));
printf("Subtraction: %d\n", subtract(num1, num2));
printf("Multiplication: %d\n", multiply(num1, num2));
printf("Division: %f\n", division(num1, num2));
printf("Modulus: %d\n", mod(num1, num2));
return 0;
}
Output
Enter the first number: 8
Enter the second number: 3
Arithmetic operations on 8 and 3:
Addition: 11
Subtraction: 5
Multiplication: 24
Division: 2.666667
Modulus: 3
………………………………………………………………………….
C - Recursion
int main() {
recursion();
}
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.
Number Factorial
Function in C
writing a C program and you need to perform a same task in that program more than once. In
such case you have two options:
a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to perform that
task.
Types of functions
1) Predefined standard library functions
Standard library functions are also known as built-in functions. Functions such
as puts(), gets(), printf(), scanf() etc are standard library functions. These functions are
already defined in header files
For example, printf() function is defined in <stdio.h> header file so in order to use
the printf() function, we need to include the <stdio.h> header file in our program
using #include <stdio.h>.
The functions that we create in a program are known as user defined functions or in other words
you can say that a function created by user is known as user defined function.
Syntax of a function
return_type function_name (argument list)
{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double, char, void, short etc.
function_name: It can be anything, however it is advised to have a meaningful name for the
functions so that it would be easy to understand the purpose of function just by seeing it’s name.
argument list: Argument list contains variables names along with their data types. These
arguments are kind of inputs for the function. For example – A function which is used to add two
integer variables, will be having two integer argument.
Block of code: Set of C statements, which will be executed whenever a call will be made to the
function.
Function will add the two numbers so it should have some meaningful name like sum, addition,
etc. For example lets take the name addition for this function.
int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
return 0;
}
Example2: Creating a void user defined function that doesn’t return anything
#include <stdio.h>
/* function return type is void and it doesn't have parameters*/
void introduction()
{
printf("Hi\n");
printf("My name is Chaitanya\n");
printf("How are you?");
/* There is no return statement inside this function, since
its
* return type is void
*/
}
int main()
{
/*calling function*/
introduction();
return 0;
}
Example 1
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }
Output:
Hello Javapoint
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Example 1
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Example 1
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
Going to calculate the sum of two numbers:
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
Call by value in C
o 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.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o 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.
o 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:
o #include<stdio.h>
o void change(int num) {
o printf("Before adding value inside function num=%d \n",num);
o num=num+100;
o printf("After adding value inside function num=%d \n", num);
o }
o int main() {
o int x=100;
o printf("Before function call x=%d \n", x);
o change(x);//passing value in function
o printf("After function call x=%d \n", x);
o return 0;
o }
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
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
#include <stdio.h>
printf("%d\n", age1);
printf("%d\n", age2);
int main() {
display(ageArray[1], ageArray[2]);
return 0;
#include <stdio.h>
int main() {
result = calculateSum(num);
return 0;
sum += num[i];
return sum;
}
Pass Multidimensional Arrays to a Function
Example 3: Pass two-dimensional arrays
#include <stdio.h>
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
}
Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
o The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
o 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.
Example:
o #include<stdio.h>
o void change(int *num) {
o printf("Before adding value inside function num=%d \n",*num);
o (*num) += 100;
o printf("After adding value inside function num=%d \n", *num);
o }
o int main() {
o int x=100;
o printf("Before function call x=%d \n", x);
o change(&x);//passing reference in function
o printf("After function call x=%d \n", x);
o return 0;
o }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
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
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to Changes made inside the function validate outside
the function only. The values of the actual of the function also. The values of the actual
parameters do not change by changing the parameters do change by changing the formal
formal parameters. parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location
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.
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
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.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Types of Recursion in C
This section will discuss the different types of recursion in the C programming language.
Recursion is the process in which a function calls itself up to n-number of times. If a
program allows the user to call a function inside the same function recursively, the
procedure is called a recursive call of the function. Furthermore, a recursive function can
call itself directly or indirectly in the same program.
void recursion ()
1. {
2. recursion(); // The recursive function calls itself inside the same function
3. }
4. int main ()
5. {
6. recursion (); // function call
7. }
In the above syntax, the main() function calls the recursion function only once. After
that, the recursion function calls itself up to the defined condition, and if the user
doesn't define the condition, it calls the same function infinite times.
Direct Recursion
When a function calls itself within the same function repeatedly, it is called the direct
recursion.
1. fun()
2. {
3. // write some code
4. fun();
5. // some code
6. }
In the above structure of the direct recursion, the outer fun() function recursively calls
the inner fun() function, and this type of recursion is called the direct recursion.
Program2.c
1. #include<stdio.h>
2. int fibo_num (int i)
3. {
4. // if the num i is equal to 0, return 0;
5. if ( i == 0)
6. {
7. return 0;
8. }
9. if ( i == 1)
10. {
11. return 1;
12. }
13. return fibo_num (i - 1) + fibonacci (i -2);
14. }
15. int main ()
16. {
17. int i;
18. // use for loop to get the first 10 fibonacci series
19. for ( i = 0; i < 10; i++)
20. {
21. printf (" %d \t ", fibo_num (i));
22. }
23. return 0;
24. }
Output
0 1 1 2 3 5 8 13 21 34
Indirect Recursion
When a function is mutually called by another function in a circular manner, the function is called an indirect recursion function.
In this structure, there are four functions, fun1(), fun2(), fun3() and fun4(). When the
fun1() function is executed, it calls the fun2() for its execution. And then, the fun2()
function starts its execution calls the fun3() function. In this way, each function leads to
another function to makes their execution circularly. And this type of approach is called
indirect recursion.
Program3.c
1. #include <stdio.h>
2. // declaration of the odd and even() function
3. void odd(); // Add 1 when the function is odd()
4. void even(); // Subtract 1 when the function is even
5. int num = 1; // global variable
6. void odd ()
7. {
8. // if statement check and execute the block till n is less than equal to 10
9. if (num <= 10)
10. {
11. printf (" %d ", num + 1); // print a number by adding 1
12. num++; // increment by 1
13. even(); // invoke the even function
14. }
15. return;
16. }
17. void even ()
18. {
19. // if block check the condition that n is less than equal to 10
20. if ( num <= 10)
21. {
22. printf (" %d ", num - 1); // print a number by subtracting 1
23. num++;
24. odd(); // call the odd() function
25. }
26. return;
27. }
28. int main ()
29. {
30. odd(); // main call the odd() function at once
31. return 0;
32. }
Output
2 1 4 3 6 5 8 7 10 9
Tail Recursion
A recursive function is called the tail-recursive if the function makes recursive calling
itself, and that recursive call is the last statement executes by the function. After that,
there is no function or statement is left to call the recursive function.
Program4.c
1. #include <stdio.h>
2. // function definition
3. void fun1( int num)
4. {
5. // if block check the condition
6. if (num == 0)
7. return;
8. else
9. printf ("\n Number is: %d", num); // print the number
10. return fun1 (num - 1); // recursive call at the end in the fun() function
11. }
12. int main ()
13. {
14. fun1(7); // pass 7 as integer argument
15. return 0;
16. }
Output
A function is called the non-tail or head recursive if a function makes a recursive call
itself, the recursive call will be the first statement in the function. It means there should
be no statement or operation is called before the recursive calls. Furthermore, the head
recursive does not perform any operation at the time of recursive calling. Instead, all
operations are done at the return time.
Program5.c
1. #include <stdio.h>
2. void head_fun (int num)
3. {
4. if ( num > 0 )
5. {
6. // Here the head_fun() is the first statement to be called
7. head_fun (num -1);
8. printf (" %d", num);
9. }
10. }
11. int main ()
12. {
13. int a = 5;
14. printf (" Use of Non-Tail/Head Recursive function \n");
15. head_fun (a); // function calling
16. return 0;
17. }
Output
A function is called the linear recursive if the function makes a single call to itself at each
time the function runs and grows linearly in proportion to the size of the problem.
Program6.c
1. #include <stdio.h>
2. #define NUM 7
3. int rec_num( int *arr, int n)
4. {
5. if (n == 1)
6. {
7. return arr[0];
8. }
9. return Max_num (rec_num (arr, n-1), arr[n-1]);
10. }
11. // get the maximum number
12. int Max_num (int n, int m)
13. {
14. if (n > m)
15. return n;
16. return m;
17. }
18. int main ()
19. {
20. // declare and initialize an array
21. int arr[NUM] = { 4, 8, 23, 19, 5, 35, 2};
22. int max = rec_num(arr, NUM); // call function
23. printf (" The maximum number is: %d\n", max); // print the largest number
24. }
Output
Tree Recursion
A function is called the tree recursion, in which the function makes more than one call to
itself within the recursive function.
Let's write a program to demonstrate the tree recursion in C programming language.
Program7.c
1. #include <stdio.h>
2. // It is called multiple times inside the fibo_num function
3. int fibo_num (int num)
4. {
5. if (num <= 1)
6. return num;
7. return fibo_num (num - 1 ) + fibo_num(num - 2);
8. }
9. void main()
10. {
11. int num = 7;
12. printf (" Use of Tree Recursion: \n");
13. // print the number
14. printf (" The Fibonacci number is: %d", fibo_num(7));
15. }
Output