C Functions | Functions in C | What are Functions in C Programming and Types

A function is a block of codes or a group of statements that together perform a specific task.

Every C program must have at least one function, which is the main() function. We can divide our code into separate functions. A program can have any number of functions. The main() function is the starting point of a program. 


Declaring and Defining Functions:

Function Declaration:

It is necessary to declare a function before its used. It informs the compiler that the function may later be used in the program.

Function declaration is also known as “function prototype”. The function prototype consists of name of the function, parameter list and the type of value returned by the function. The function prototype is always terminated with a semicolon.

The general syntax for function declaration is:

return_type function_name(parameter list);


  • return_type specifies the data type of the value that the function is designed to return. Return type can be of any data type such as int, double, char, short etc. It can be void also, in such case function doesn’t return any value.
  • function_name is an identifier and it specifies the name of the function. The function name must follow the same rules that apply to the variable names.
  • Parameter list contains variables names along with their data types. Parameter list is a comma separated list of variables of a function through which the function may receive data or send data when called from other function.


Example:   int max(int n1,int n2);


Function Definition:

A function must be defined prior to its use in the program. The function definition consists of the body of the function, which is a block of code. The definition provides the actual body of the function. The function body contains a collection of statements which are going to perform the required task. A function body consists of a single or a block of statements.


A function definition has the following form:

 

return_type function_name(parameter list)

{

body of the function

}

When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.



The form of C functions (Structure of a Function):


The general form of any C function looks like this:


return_type function_name (parameter list)

{

local variable declarations;

executable statements           //body of the function                   

return (expression);

}

 

     return_type specifies the data type of the value being returned by the function. Return type can be of any data type such as int, double, char, short etc. A function may or may not return a value. If the function does not return a value, then the return type is void.

     function_name is an identifier and it specifies the name of the function. The function name must follow the same rules as that of variable names.

     Parameter list contains variables names along with their data types. Parameter list is a comma separated list of variables of a function through which the function may receive data or send data when called from other function.

     Local variables are the variables that are declared inside the function. The scope of these variable lies within the function and they are not accessible outside the function.

     The return statement is used to return a value to the calling function.

                                                                                                                                 

     Example of function:

 

int sum (int x, int y)

{

int result;

result= x + y;

return result;

}

     

    

     Advantages of using functions (Benefits of using functions):

By using function large and difficult program can be divided into sub programs and solved. When we want to perform some task repeatedly or some code is to be used more than one at different place in the program, then function avoids this repetition or rewritten over and over.


There are many advantages of using functions in a program they are:

  • A large program becomes difficult to understand. By using function, it becomes easier. Breaking the code in smaller Functions keeps the program organized, easy to understand and makes it reusable.
  • Dividing a large program into various functions makes the program easier to design and debug.
  • Logical clarity of the program is increased hence programming becomes simpler.
  • It reduces the complexity of a program and gives it a modular structure.
  • It makes the program more structured, more readable. Use of functions enhances the readability of a program.
  • The size of the program can be reduced by calling and using functions at appropriate places.
  • It becomes easier to locate and separate a faulty function for further study.
  • By using functions we can avoid rewriting the same block of codes at two or more locations in a program. We can easily call and use functions whenever they are required.

   


Type of Function: Categories of Functions

Functions can be broadly classified into two major categories,

     1. Standard library functions or Built-in Functions

     2. User-defined functions



Standard Library Function:

Standard library functions or simply library functions are built-in functions. There functions are already defined in the C compilers. These are system defined functions. These functions available in C libraries, such as the printf() and the scanf(), clrscr(), getch() etc.

These functions are further categorized and according to that stored in different files known as header files. In order to use library functions we just need to include appropriate header files in our program. Because library functions are defined in header files, so it does not require writing the code of the particular function. Instead it can be called directly in a program whenever it is required. To use these functions we need to import the specific header files.

For exampleprintf() 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>.



User Defined Functions:

User defined functions are defined by the user.  C allows us to create functions according to our need. If there is no appropriate library function for specific requirement, we can create our own function to perform the desired operation. Once a function is defined, we can easily call and use the function whenever it require.

 

The User defined functions are of four types:

  • Function with no arguments and no return value
  • Function with no arguments  and a return value
  • Function with arguments but no return value
  • Function with arguments and with return value

 

Function with no arguments and no return value:

Function with no argument means the called function does not receive any data from calling function and Function with no return value means calling function does not receive any data from the called function. So there is no data transfer between calling and called function.

Such functions can either be used to display information or or they are completely dependent on user inputs.

 


Output:


In the above program, sum(); function calculates sum and no arguments are passed to this function. The return type of this function is void, hence return nothing.

 

Functions with no arguments and a return value:

Function with no arguments means called function does not receive any data from calling function and function with a return value means one result will be sent back to the caller from the function.

Such functions are used to perform specific operations and return their value.



Output:


In the above program, function sum does not take any arguments and has a return value as an integer type. It takes a and b as inputs from the user and returns them.


Function with arguments but no return value:

Here function will accept data from the calling function as there are arguments, however, since there is no return type nothing will be returned to the calling program. So it’s a one-way type communication.

Such functions are used to display or perform some operations on given arguments.




Output:


In the above program, the integer value entered by the user in a and b variable is passed to the function sum(); .The called function has void as a return type as a result, it does not return value.

This program calculates the sum of two numbers and prints the result.


Function with arguments and with return value:

Function with arguments and with return value means both the calling function and called function will receive data from each other. It’s like a bi-directional communication.

These functions are used to perform specific operations on the given arguments and return their values to the user.




Output:





In the above program, function sum takes two arguments as a and b, and has a return value as an integer type. The main function takes input a and b from the user and calls the sum function to perform a specific operation on the given arguments and returns the value.


Return Statement:

The return statement terminates the execution of a function and returns control to the calling function. The function ends when return statement is encountered.

When program execution reaches return statement, the program control is immediately transferred back to the calling function. A return statement can return a value to the calling function. A value returning function should include a return statement, containing an expression.

 

The general form of return statement is:

return expression;      

or     

return (expression);


Example:

return a;

return (a+b);

return 0;

The value of expression becomes the return value of the function. The type of value, returned from the function and the return type specified in the function prototype and function definition must match. For example, an int function can’t return a float value.

If a function does not return a value, the return type in the function definition and declaration is specified as void. A function can return only one value. 



Calling a Function or Function call:

A function call means calling a function whenever it is required in a program. Whenever we call a function, it performs the defined task.

Once a function has been defined, it can be called as many times as we require. A function can be called by, any other function by its name. Function can be called from anywhere in the program. To call a function, we need to pass the required arguments along with the function name.

 

The syntax of a function call is as follows:

function_name(argument_list);

function_name must match exactly the name of the function in the function prototype. The number of arguments and their types  in a function call must exactly match the parameters specified in  the function prototype.

 

Example: sum(a,b);

When a program calls a function, the program control is transferred from the calling function to the called function. The called function performs the defined task and after finishing the task it returns the program control back to the calling function. Any function that is called by another function is known as a called function. A function that calls another function is known as calling function.


Types of Function Calls:

While calling a function, there are two ways in which actual parameter or arguments can be passed to a function.

  • Call by value
  • Call by reference


Call by Value:

When a function is called by value, a copy of the actual parameter is created and sent to the formal parameter of the called function. The called function uses only the copy of the actual parameter. Therefore, the value of the actual parameter cannot be altered by the called function. Any changes made inside called function are not reflected in actual parameters of the calling function.


Note:

  • The parameter that appears in function calls is known as actual parameter.
  • The parameter that appears in function definition is known as formal parameter.

 


Programming Example:




Output:




In the above program, copy of the parameters x and y is sent to the function swap() and hence output will be the original x and y values and not the swapped values. In order to change the value of the parameters x and y, the function has to be called by reference.


Call by Reference:

When a function is called by reference, the address of the actual parameters is sent to the formal parameter of called functions. If we make any change in the formal parameters, it shows the effect in the value of the actual parameter.

When parameters are passed to a function, the parameters are passed by value. That is a copy of the actual parameter is sent to the called function. Therefore, called function cannot change the value of the actual parameter of the calling function. But, there might be some cases where we need to change the values of actual parameter in the calling function.

In order to enable the called function to change the variable of the calling function, the address of the actual parameter must be passed. When a parameter is passed by reference, we are not passing copy of its value, but we are passing the parameter itself to the called function. Any changes made inside the called functions are actually reflected in actual parameters of the calling function. The called function can alter the value of the actual parameters.

 

Programming Example:




Output:



Difference between Call by Value and Call by Reference:


Parameter

Call By Value

Call By Reference

Definition

While calling a function, when you pass values by copying variables, it is known as “Call By Values.”

While calling a function, instead of copying the values of variables, the address of the variables is used it is known as “Call By References.

Arguments

In this method, a copy of the variable is passed.

In this method, a variable itself is passed.

Effect

Changes made in a copy of variable never modify the value of variable outside the function.

Change in the variable also affects the value of the variable outside the function.

Alteration of value

It does not allow you to make any changes in the actual variables.

It Allows you to make changes in the values of variables by using function calls.

Value modification

Here the original value is not modified.

Here the original value is modified.

Memory Location

Here actual and formal arguments will be created in different memory location

Here actual and formal arguments will be created in the same memory location

Safety

Actual arguments remain
safe as they cannot be modified
accidentally.

Actual arguments are not safe. They can be
accidentally modified, so you need to handle arguments operations carefully.

Default

Default in many programming
languages like C++, PHP, Visual Basic NET, and C#.

It is supported by most
programming languages like JAVA, but not as default.

 


Advantages of using Call by Value method in C:

Pros/Benefits of a Call by Value in C:

  • The method doesn’t change the original variable, so it is preserving data.
  • Whenever a function is called it, never affect the actual contents of the actual arguments.
  • Value of actual arguments passed to the formal arguments, so any changes made in the formal argument does not affect the real cases.

 

Advantages of using Call by Reference method:

Pros/benefits of using Call by Reference method:

  • The function can change the value of the argument, which is quite useful.
  • It does not create duplicate data for holding only one value which helps you to save memory space.
  • In this method, there is no copy of the argument made. Therefore it is processed very fast.
  • Helps you to avoid changes done by mistake
  • A person reading the code never knows that the value can be modified in the function.



Recursion:

In C, it is possible for the function to call itself. The function which calls itself is known as recursive function.

Recursion is the process by which a function calls itself. The recursion continues until some specified condition is true.

Recursion means “defining a problem in terms of itself”. In other words recursion is the process of defining something in terms of itself.

The recursion process will go in an infinite loop, until some condition is met. In order to prevent it from going into an infinite loop, we need to use of if..else statement or define proper exit condition in the recursive function.

With the help of recursion, we can solve many complex mathematical problems, such as calculating the factorial of a number and generating Fibonacci series etc.


Programming example:


 /*Calculate factorial of a number using recursion*/ 

#include<stdio.h>

#include<conio.h>

long int fact(int n);

int main( )

{

 int num,f;

 printf(“\n Enter a number: ”);

 scanf(“%d”,&num);

 f=fact(num);

 printf(“\nFactorial of %d is :%ld”,num,f);

 getch();

 return 0;

}

long int fact(int n)

    {

        if (n<=1)

            return (1);

        else

            return (n*fact(n-1)) ;

    }

 

Output: 

Enter a number: 4

Factorial of 4 is: 24

The function fact calls itself repeatedly with n-1 and terminate when the variable becomes 1.



Advantages/Disadvantages of Recursion:


Advantages of Recursion (Benefits of Recursion):

  • Recursion makes code easier to write
  • Recursion can reduce time complexity.
  • Recursion adds clarity and reduces the time needed to write and debug code.
  • Reduce unnecessary calling of function.
  • Extremely useful when applying the same solution.
  • Recursion reduce the length of code.
  • It is very useful in solving the data structure problem.
  • Stacks evolutions and infix, prefix, postfix evaluations etc.

 

Disadvantages of Recursion:

  • Recursive functions are generally slower than non-recursive function.
  • It may require a lot of memory space to hold intermediate results on the system stacks.
  • Difficult to analyze code:
  • It is not more efficient in terms of space and time complexity.
  • The computer may run out of memory if the recursive calls are not properly checked.



Recursive Function:

A recursive function calls itself.  In C, it is possible for the function to call itself. The function which calls itself is known as recursive function. A recursive function is a function in code that refers to itself for execution. The condition that is applied in any recursive function is known as a base condition. A base condition is a must in every recursive function otherwise it will continue to execute like an infinite loop.

A recursive function has two different parts:

 

1.   Base case

2.   Recursive case

 

The base case is used to terminate the task of recurring. If base case is not defined, then the function will recur infinite number of times (Theoretically).

Recursive case simplifies a bigger problem into a number of simpler sub-problems and then calls them.

 

 Working principle:

  • A recursive function is called by some external code.
  • If the base condition is met then the program gives meaningful output and exits.
  • Otherwise, the function does some required processing and then calls itself to continue recursion.

 

Simple examples of a recursive function include the factorial, where an integer is multiplied by itself while being incrementally lowered.


// This function calculates the factorial of a positive number recursively.

int fact(int n)

{

if(n<=1)

return 1;    //base case

else

return n*fact(n-1);    //recursive case

}


Post a Comment

0 Comments