0% found this document useful (0 votes)
8 views

Unit 3-Final Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 3-Final Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Functions

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.

Why We Need Functions in C?


Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any
program rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are
easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by
function calls.

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.

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>.

2) User Defined functions


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.

C programming functions are divided into three activities such as,

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:

return_data_type function_name (data_type arguments);

 The return_data_type: is the data type of the value function returned


back to the calling statement.
 The function_name: is followed by parentheses
 Arguments names with their data type declarations optionally are placed
inside the parentheses.

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);

/*End of Function declaration*/

int main() {

Keep in mind that a function does not necessarily return a value. In this case,
the keyword void is used.

For example, the output_message function declaration indicates that the


function does not return a value: void output_message();

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.

The syntax for defining a function in C is

return_type function_name( parameter list )

body of the function

OR

return_type function_name (parameter_data_type p1,


parameter_data_type p2, …..)

//Some code

return value;

}
Example:

int add(int a,int b) //function body

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);

Here, is the complete code:

Program to add two numbers using function.

#include <stdio.h>

int add(int a, int b); //function declaration

int main()

int a=10,b=20;

int c=add(10,20); //function call

printf("Addition:%d\n",c);

getch();

int add(int a,int b) //function body or Function Definition


{

int c;

c=a+b;

return c;

Output:

Addition:30

Type of User-defined Functions in C


There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value


2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
Below, we will discuss about all these types, along with program examples.

Function with no arguments and no return value


Such functions can either be used to display information or they are completely
dependent on user inputs.
Syntax:
return_type function_name ( parameter1, parameter2, ... )
{
// body of Statement ;
}

Example: Program1

//No Return Without Argument Function in C


#include<stdio.h>
void add(); //Function Declaration
int main()
{
add(); //Function Calling
return 0;
}
//Function Definition
void add()
{
int a,b,c;
printf("\nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);
}
Output
Enter The Value of A & B : 12 34
Total : 46
…………………………………………………………

Program 2 :

Example of a function, which takes 2 numbers as input from user, and display
which is the greater number.

#include<stdio.h>

void greatNum(); // function declaration

int main()

greatNum(); // function call


return 0;

void greatNum() // function definition

int i, j;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

if(i > j)

printf("The greater number is: %d", i);

else {

printf("The greater number is: %d", j);

Function with no arguments and a return value


Syntax :
return_type function_name ( ) // Function Definition
{
// body of Statement ;
return value;
}

Example: Program1

//Return Without Argument Function in C


#include<stdio.h>
int add();
int main()
{
int a;
a=add();
printf("\nTotal : %d",a);
return 0;
}
int add()
{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
return a+b;
}
Output
Enter The Value of A & B : 6
45
Total : 51
…………………………………………………………………….
Program 2 :
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 greatNum(); // function declaration

int main()

int result;
result = greatNum(); // function call

printf("The greater number is: %d", result);

return 0;

int greatNum() // function definition

int i, j, greaterNum;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

if(i > j) {

greaterNum = i;

else

greaterNum = j;

return greaterNum; // returning the result

Function with arguments and no return value


We are using the same function as example again and again, to demonstrate that
to solve a problem there can be many different ways.

Syntax :
return_type function_name ( data_type argument1, data_type argument2,
... ) // Function Definition
{
// body of Statement ;
}

Example: Program1

//No Return With Argument Function in C


#include<stdio.h>

//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 :

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>

void greatNum(int a, int b); // function declaration

int main( )

int i, j;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

greatNum(i, j); // function call

return 0;

void greatNum(int x, int y) // function definition

if(x > y)

printf("The greater number is: %d", x);

else {

printf("The greater number is: %d", y);

}
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

/Return With Argument Function in C


#include<stdio.h>
int add(int,int);
int main()
{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
a=add(a,b);
printf("\nTotal : %d",a);
return 0;
}
int add(int x,int y)
{
return x+y;
}
Output
Enter The Value of A & B : 2 9
Total : 11
Example: Program 2:

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 greatNum(int a, int b); // function declaration

int main()

int i, j, result;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

result = greatNum(i, j); // function call

printf("The greater number is: %d", result);

return 0;

int greatNum(int x, int y) // function definition

if(x > y) {

return x;

else {

return y;

}
………………………………………………………………………….

Passing Parameters to Functions or Function Arguments


Passing parameters to functions is a fundamental concept in programming that
allows us to pass data to a function for processing. Parameters are variables that
are defined within the parentheses of a function and used to store values that can
be passed in when the function is called. These values can be of any data type,
including strings, numbers, or even other objects. Once the values are passed in
as arguments, the function can then use them to perform a specific operation or
set of operations.

• If a function is to use arguments, it must declare variables that accept the


values of the arguments. These variables are called the formal parameters of the
function.

• 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

Call by Value and Call by Reference

Functions can be invoked in two ways: Call by Value or Call by


Reference. These two ways are generally differentiated by the type of
values passed to them as parameters.

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.

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);
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

Call By Value Call By Reference


While calling a function, instead of
While calling a function, we pass
values of variables to it. Such passing the values of variables, we pass
functions are known as “Call By address of variables(location of
variables) to the function known as
Values”.
“Call By References.
In this method, the value of each In this method, the address of actual
variable in calling function is copied variables in the calling function are
into corresponding dummy variables copied into the dummy variables of the
of the called function. called function.
With this method, the changes made With this method, using addresses we
to the dummy variables in the called would have an access to the actual
function have no effect on the values variables and hence we would be able to
of actual variables in the calling manipulate them.
function.
A copy of the value is passed An address of value is passed into the
function
into the function
Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory location
location

Passing array to function using call by reference


When we pass the address of an array while calling a function then this is called
function call by reference. When we pass an address as an argument, the
function declaration should have a pointer as a parameter to receive the passed
address.

#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:

C Program to Perform Arithmetic Operations Using


Functions
// C Program to Perform Arithmetic Operations Using Functions
#include <stdio.h>

// Declaring addition function


int addition(int a, int b){
int sum = a + b;
return sum;
}

// Declaring subtraction function


int subtract(int a, int b){
int difference = a - b;
return difference;
}

// Declaring multiplication function


int multiply(int a, int b){
int multiply = a * b;
return multiply;
}

// Declaring division function


float division(float a, float b){
float divide = a / b;
return divide;
}

// Declaring modulus function


float mod(int a, int b){
int rem = a % b;
return rem;
}
int main(){
int num1, num2;

// Asking for input


printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);

// 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

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();
}
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

A function is a block of statements that performs a specific task.

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>.

2) User Defined functions

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.

return_type addition(argument list)


This function addition adds two integer variables, which means I need two integer variable as
input, lets provide two integer parameters in the function signature. The function signature
would be –

return_type addition(int num1, int num2)


The result of the sum of two integers would be integer only. Hence function should return an
integer value – It would be integer –

int addition(int num1, int num2);

How to call a function in C?

Creating a user defined function addition()


#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
/* Arguments are used here*/
sum = num1+num2;

/* Function return type is integer so we are returning


* an integer value, the sum of the passed numbers.
*/
return sum;
}

int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);

/* Calling the function here, the function return type


* is integer so we need an integer variable to hold the
* returned value of this function.
*/
int res = addition(var1, var2);
printf("Output: %d",res);

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;
}

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value

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

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

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

Example 2: program to calculate the area of the square

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

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value

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:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.

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

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value

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

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30
Example 2: Program to check whether a number is even or odd

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 and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value and call by
reference.

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

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do n
ot change by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 1
0
18. }

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

Pass arrays to a function in C


Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a function.
Example 1: Pass Individual Array Elements

#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;

Example 2: Pass Arrays to Functions


// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>

float calculateSum(float num[]);

int main() {

float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()

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;

}
Pass Multidimensional Arrays to a Function
Example 3: Pass two-dimensional arrays

#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]);

// pass multi-dimensional array to a function

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]);

}
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

Call by reference Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
8. swap(&a,&b);
9. 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
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b =
10
18. }

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 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.

In the following example, recursion is used to calculate the factorial of a number.


1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(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 n*fact(n-1);
24. }
25. }

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.

Pseudocode for writing any recursive function is given below.

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.

Syntax of the Recursion function

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.

Different types of the recursion


1. Direct Recursion
2. Indirect Recursion
3. Tail Recursion
4. No Tail/ Head Recursion
5. Linear recursion
6. Tree Recursion

Direct Recursion

When a function calls itself within the same function repeatedly, it is called the direct
recursion.

Structure of 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.

Let's write a program to demonstrate the direct recursion in C programming language.

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.

Structure of the indirect recursion


1. fun1()
2. {
3. // write some code
4. fun2()
5. }
6. fun2()
7. {
8. // write some code
9. fun3()
10. // write some code
11. }
12. fun3()
13. {
14. // write some code
15. fun1()
16. }

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.

Let's write a program to demonstrate the indirect recursion in C programming language.

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.

Let's write a program to demonstrate the tail recursion in C programming language.

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

Non-Tail / Head Recursion

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.

Let's write a program to demonstrate the Head/Non-Tail recursion in C programming


language.

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

Use of Non-Tail/Head Recursive function


1 2 3 4 5
Linear Recursion

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.

Let's write a program to demonstrate the linear Recursion in C programming language.

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

The maximum number is: 35

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

Use of Tree Recursion:


The Fibonacci number is: 13

You might also like