Functions in C

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. or

A Function is a name, self-contained block of statements that perform a specific task and may return a value to the program.

  • You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
  • A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
  • The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.
  • A function can also be referred as a method or a sub-routine or a procedure, etc.





Defining a Function:

The general form of a function definition in C programming language is as follows:

return_type function_name( parameter list ) {

 body of the function

 }


Advantages of Functions : 


1. It represents a small & specific task 

  •  Which makes program easier to understand , implement and maintain. 

2. It reduce length of program and thus saves Memory. 

  •  The function is written once in a program, but used many times which reduces the length of the program and saves the MEMORY. 

3. It increase reusability and reliability of program. 

  •  Function written in one program can be used also in other program. This increase not only the reusability of program but also increase reliability as function is already tested when developed first time. 

4. Dividing a program in to functions brings the preciseness in to design. 

  •  It make program more understable.

Types of functions in C:

  1. PRE-DEFINED
  2. USER-DEFINED

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


Examples:
 

  • Printf()
  • Scanf()
  • Getchar()
  • Sin()
  • Sqrt() 
  • Pow()

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.

Now we will learn how to create user defined functions and how to use them in C Programming


Syntax of a function


  • Return_type: Return type can be of any data type such as int, double, char, void, short etc. Don’t worry you will understand these terms better once you go through the examples below.
  • 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


Categories of Functions 

  • Depending upon number of arguments receives and the type of value it returns. 
 Categories of Function 

1. Function with no arguments and no return values 
2. Function with arguments but no return values 
3. Function with arguments and one return values 
4. Function with no arguments but return values 
5. Function that returns multiple values

Function Arguments


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.


Function Declarations


  • A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
  • A function declaration has the following parts −

            return_type function_name( parameter list );

  • For the above defined function max(), the function declaration is as follows −

            int max(int num1, int num2);

  • Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −

            int max(int, int);

  • Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.


Calling a Function


  • While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
  • When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
  • To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.

Parameter Passing 


 There are two ways to pass arguments(data or value) to a function.

  •  Pass argument by value
           (call by value). 
  •  Pass arguments by address or by pointer
          (call by reference) 

• Original value is not modified in call by value but it is modified in call by reference.

1. Call by Value 

  • The contents of the actual parameters get copied into the corresponding formal parameters. 
  • In call by value, original value is not modified. 
  • In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().
  • Let's try to understand the concept of call by value in c language by the example given below: 


          #include<stdio.h>
          #include <conio.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;
           clrscr(); 
           printf("Before function call x=%d \n", x); change(x);
           //passing value in function 
           printf("After function call x=%d \n", x);
          getch();
          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


2. Call by reference 

  •  In this method, the contents of the arguments in the calling function get changed. 
  •  Instead of passing the value of a variable, we can pass the memory address of the variable to the function. This is called as call by reference. 
  • Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.
  •  Let's try to understand the concept of call by reference in c language by the example given below:


 #include 
#include 
   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; 
   clrscr();
   printf("Before function call x=%d \n", x); 
   change(&x);
  //passing reference in function 
    printf("After function call x=%d \n", x);
    getch(); 
    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

Recursion

• Recursion is a process by which function calls it self repeatedly, until some specified condition has been satisfied. 
Syntax 
return type function_name()
 {……….. ………… function_name(….);
       …………. } 


 WAP to find factorial of given number using recursion

 #include 
 #include 
   int factorial (int n)
    {
    if ( n < 0)
       return -1;  /*Wrong value*/
    if (n == 0) 
       return 1; /*Terminating condition*/ 
       return (n * factorial (n -1)); 
   } 
      void main()
   { 
      int fact=0; 
      clrscr();
      fact=factorial(5);
      printf("\n factorial of 5 is %d",fact); 
      getch();
      }
   
   Output: 

   factorial of 5 is 120

 Advantages of Recursion : 

1. It solve problem in easier way than using iterative loops 
    Ex. tower of honoi 
2. It reduce Size of code.
 3. Complex program can be easily written using recursion.

Disadvantage of Recursion : 

1. To many recursive function may cause confusion in the code. 
2. Recursive solution is logical and it is difficult to debug and understand. 
3. It makes program execution slower. 
4. In recursive function if statement is compulsory to return outside from the function. otherwise it executes infinite times.

 Macro Function

 • In C macro can be defined using #define .
 • A simple example of a macro function with arguments is


Post a Comment

0 Comments