Unit 6 Function

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Unit: 6

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

There are the following advantages of C functions.

 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

There are three aspects of a C function.

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.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);


2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list)


{function body;}

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.

S Header file Description


N

1 stdio.h This is a standard input/output header file. It contains all


the library functions regarding standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(),


puts(),etc.

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 functionName(type1 parameter1, type2 parameter2,...);


Like any variable or an array, a function must also be declared before its used. Function declaration informs the
compiler about the function name, parameters is accept, and its return type. The actual body of the function can be
defined separately. It's also called as Function Prototyping. Function declaration consists of 4 parts.

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

Time for an Example

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


int main()

int i, j, result;

printf("Please enter 2 numbers you want to multiply...");

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

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

printf("The result of multiplication is: %d", result);

return 0;

int multiply(int a, int b)

return (a*b); // function defintion, this can be done in one line

Function definition Syntax


Just like in the example above, the general syntax of function definition is,

returntype functionName(type1 parameter1, type2 parameter2,...)

// function body goes here

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.

 local variable declaration(if required).

 function statements to perform the task inside the function.

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

Passing Arguments to a function


Arguments are the values specified during the function call, for which the formal parameters are declared while
defining the function.

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.

Returning a value from function


A function may or may not return a result. But if it does, we must use the return statement to output the
result. return statement also ends the function execution, hence it must be the last statement of any function. If you
write any statement after the return statement, it won't be executed.
The datatype of the value returned using the return statement should be same as the return type mentioned at
function declaration and definition. If any of it mismatches, you will get compilation error.

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.

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

#include<stdio.h> scanf("%d%d", &i, &j);

void greatNum(); // function declaration if(i > j)

int main() {

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

greatNum(); // function call }

return 0; else

} {

void greatNum() // function definition printf("The greater number is: %d", j);

{ }

int i, j; }

printf("Enter 2 numbers that you want to


compare...");
Exercises:

1. Write a program to check enter two numbers whether number is smaller.


2. Write a program to check whether input number is positive or negative.
3. Write a program to check enter number is even or odd.
4. Write a program to input three numbers and check whether number is middle number.

Function with no arguments and a return value

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;

// returning the result

return greaterNum;

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.

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

#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


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;

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

Example: Factorial of a number using Recursion

#include<stdio.h>

int factorial(int x); //declaring the function

void main()

int a, b;

printf("Enter a number...");

scanf("%d", &a);

b = factorial(a); //calling the function named factorial

printf("%d", b);

int factorial(int x) //defining the function

int r = 1;

if(x == 1)

return 1;

else

r = x*factorial(x-1); //recursion, since the function calls itself

return r;

How recursion works?

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();
... .. ...

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the
recursive call, and other doesn't.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>

int sum(int n);

int main() {

int number, result;

printf("Enter a positive integer: ");

scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);

return 0;

int sum(int n) {

if (n != 0)

// sum() function calls itself

return n + sum(n-1);

else

return n;

Output

Enter a positive integer:3


sum = 6

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.

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

#include <stdio.h>

int fact (int);

int main()

int n,f;

printf("Enter the number whose factorial you want to calculate?");

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.

Pseudocode for writing any recursive function is given below.

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;

printf("Enter the value of n?");

scanf("%d",&n);

f = fibonacci(n);

printf("%d",f);

int fibonacci (int n)

if (n==0)

return 0;

else if (n == 1)

return 1;

else

return fibonacci(n-1)+fibonacci(n-2);

Output

Enter the value of n?12

144

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.
Let's understand call by value and call by reference in c language one by one.

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>

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

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.

Consider the following example for the call by reference.

#include<stdio.h>

void change(int *num) {

printf("Before adding value inside function num=%d \n",*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 reference 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=200

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 An address of value is passed into


the function the function

2 Changes made inside the Changes made inside the function


function is limited to the function validate outside of the function also.
only. The values of the actual The values of the actual parameters
parameters do not change by do change by changing the formal
changing the formal parameters. parameters.

3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location

Advantages and Disadvantages of Recursion


Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is usually much
slower.

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

printf("\nGoing to calculate the sum of two numbers:");

sum();

void sum()

int a,b;

printf("\nEnter two numbers");

scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);

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


#include<stdio.h>

int sum();

void main()

int result;

printf("\nGoing to calculate the sum of two numbers:");

result = sum();

printf("%d",result);

int sum()

int a,b;

printf("\nEnter two numbers");

scanf("%d %d",&a,&b);

return a+b;

Output

Going to calculate the sum of two numbers:

Enter two numbers 10

24

The sum is 34

Example 2: program to calculate the area of the square


#include<stdio.h>

int sum();

void main()

printf("Going to calculate the area of the square\n");

float area = square();

printf("The area of the square: %f\n",area);

int square()

float side;

printf("Enter the length of the side in meters: ");

scanf("%f",&side);

return side * side;

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

Program to calculate the average of five numbers.


#include<stdio.h>

void average(int, int, int, int, int);

void main()

int a,b,c,d,e;

printf("\nGoing to calculate the average of five numbers:");

printf("\nEnter five numbers:");

scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);

average(a,b,c,d,e);

void average(int a, int b, int c, int d, int e)

float avg;

avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);

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

Program to check whether a number is even or odd


#include<stdio.h>

int even_odd(int);

void main()

int n,flag=0;

printf("\nGoing to check whether a number is even or odd");

printf("\nEnter the number: ");

scanf("%d",&n);

flag = even_odd(n);

if(flag == 0)

printf("\nThe number is odd");

else

printf("\nThe number is even");

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

Enter the number: 100

The number is even

Exercises

Very short questions:

1. What is function in C language?


2. Write one benefits of using function.
3. What is main() function?
4. What are the main components of functions?
5. How can you write function declare? Write its
syntax.
6. What is argument in function?
7. What are two main types of parameters in C
language?
8. What is return statement in C?
9. Write the syntax of return statement.
10. List the types of functions.
11. What are the different types of user defined
functions?
12. What is recursion in function?
13. What are the method of calling function?
14. What is call by value in function?
15. What is call by reference in functions?

Short questions:

1. What are the main components of function?


Write syntax of each.
2. Write two different between call by value and
call by reference.
3. Write any two advantages of using function.
4. What is user defined function? Write down
any two examples.
5. List out any four features of function in C.

You might also like