• Loading
    • Concept Of Functions In C

      Introduction


      A function is a self-contained block of statements that perform a specific task of some kind. Every C program can be thought of as a collection of these functions. Once a function has been written to play a particular role, it can be called upon repeatedly throughout the program.

      Functions help us to split up a long program into named section so that the section can be reused throughout the program.

      Every C program consists of one or more functions. One of these functions must be called as main(). Execution will always starts from main().

      Advantages Of Function (Modules)



      • Function can be accessed repeatedly from several different places within a program.
      • Function can be accessed repeatedly with different values of parameters within a program.
      • Functions avoid the redundant programming of the same instructions.
      • Logical clarity increases by breaking the program into several concise functions.
      • Program can be divided into small modules (functions) which makes easier to understand and debug.
      • Using functions it becomes easier to write programs and keep track of what they are doing.


      Types Of Functions



      Generally functions can be divided into two broad categories:

      • System defined functions.
      • User defined functions.


      System Defined Functions


      The functions available in the standard C library are called system defined functions. These system defined functions can be accessed through the header file. For example, if you want to use printf() or scanf() functions you have to include <stdio.h> header file in your program. In C, there are many system defined functions available in different header files depending on category. For example, all standard input/output functions are available in <stdio.h>, mathematical functions are in <math.h>, console related functions are in <conio.h>. Whenever you want to use any system defined function in your program include the corresponding header file before main(), for e.g., to find the square root of any integer, the function is sqrt() available in header file <math.h>.

      User Defined Functions

      When system defined functions does not satisfies your requirement, i.e., programmer wants to perform some task and no standard function is available to perform that task then the programmer can write the function of its own known as user defined function Writing our own function makes it necessary to tell compiler the name of function, number and type of information pass to the function i.e., parameters or arguments and type of information return from the function. Functions are identified by name and can return a single value.

      Defining A Function



      If you want to use user defined function, you must let the compiler know about it. You can do this by writing something called function definition. A function cannot be called without its definition.


      The function can be defined as
      return-type function-name(parameters or arguments)
      {
      function body;
      }


      Here, return-type specifies the type of information return from the function. If the return from the function is of type float, then the return-type will be float. There can be a single return from the function through return statement.

      Function-name specifies the name of user defined function. The rules for naming the function is same as naming the variable. A function has to be given an appropriate name, which should specify the purpose of the function.

      Parameters or arguments are the information need to pass to the user defined function before executing it. For example, in the system defined function printf(“Welcome”), string ‘Welcome’ is passed to the function as an parameter, the printf() function then prints the string on the screen. Parameter is a way of passing information to the function, the function can process these information.

      The beginning and end of function are marked by opening brace ( { ) and closing brace ( } ). The statements between the { and } is the function body. Here we can use all type of statements which are allowed in main() function.

      Function Call


      Every C program starts with main(). From the main() function other functions either system defined and user defined functions are called. To call a function, refer the function name with parameters. For example, to call system defined function printf(), we refer the function name printf and in parenthesis we pass in double quotes string as a parameter to the function. There is no need to define standard functions before call, but user defined function must be defined before calling it. When a function is call, the main() function temporarily leaves the function and control moves to function to execute the function body. Once the function complete its execution, the program control reverts back to main().

      function_name()
      {
      statement(s);
      }
      main()
      {
      function_name();
      }


      The code shown above actually consists of two functions function_name() and main(). Program execution always starts with main() function. Inside the main() function program statement function_name() indicates that the function function_name() is to be called for execution. The called function must be defined before calling it.

      Code:
      /* Program using function */
      #include<stdio.h>
      main()
      {
                int length, width;
                line();        // Function call
                printf("Enter Length:");
                scanf("%d",&length);
                line(); 
                printf("Enter Width:");
                scanf("%d",&width);
                line();
                printf("Area : %d\n",length*width);
                line();
      }
      line()  //Function definition
      {
               printf("---------------------------\n");
      }
      Output:

      ---------------------------
      Enter Length:4
      ---------------------------
      Enter Width:5
      ---------------------------
      Area : 20
      ---------------------------

      In the above program, a user defined function line() is used. ‘line()’ statement calls the function. The control moves from the main() to the function() where it prints a line, the control moves back to main. The program shows that line() function is called for four times.

      In a single program we can have multiple functions. The following program demonstrates the use of two functions in a single program.

      Code:
      /* Program using functions */
      #include<stdio.h>
      main()
      {
              int length, width;
              line();
              printf("Enter Length:");
              scanf("%d",&length);
              line();
              printf("Enter Width:");
              scanf("%d",&width);
              line();
              printf("Area : %d\n",length*width);
              line();
              bye();
      }
      line()
      {
             printf("---------------------------\n");
      }
      bye()
      {
              printf(“Demonstration of functions\n”);
              printf(“Bye, See you again”)
      }
      
      Output:
      
      ---------------------------
      Enter Length:4
      ---------------------------
      Enter Width:5
      ---------------------------
      Area : 20
      ---------------------------
      Demonstration of functions
      Bye, See you again.
      In the above program, two functions line() and bye() are used. The line() is called four times in the program which will draw the line, and the bye() function is called at the end which will display the message on the screen.

      Scope Of A Variable


      Scope is that area or part of the program within which it is recognized or within which it is accessible i.e., in which part of the program a variable is active. A significant aspect of program design is deciding the scope of the variables.

      The scope of variables can be either of two types:

      • Global variable.
      • Local variable.


      Global Variables

      Many times the user wants to access the variable at any part of the program, then it is necessary to use global variable. Global variables are accessible throughout the program i.e., their scope is throughout the entire program, they are created when a program starts execution and are destroyed when a program complete its execution. They are declared above the main() function. Any changes that made to the value of the global variable is reflected in all the functions where it is used irrespective of, in which function the change takes place.
      Code:
      /* Program using global variable */
      #include<stdio.h>
      int gvar;
      main()
      {
               gvar = 5;
               printf(“\ngvar = %d”,gvar);
               inc();
               inc();
               dec();
               dec();
      }
      inc()
      {
               gvar++;
               printf(“\n on incrementing gvar = %d\n”,gvar);
      }
      dec()
      {
               gvar--;
               printf(“\n on decrementing gvar = %d \n”, gvar);
      }
      Output:

      gvar = 5
      on incrementing gvar = 6
      on incrementing gvar = 7
      on decrementing gvar = 6
      on decrementing gvar = 5

      In the above program, global variable ‘gvar’ is declared above main(). Two functions inc() and dec() are defined in the program. Since, ‘gvar’ is a global variable it can be accessible in all the three functions main(), inc() and dec().

      Code:
      /* Program for use of global variable */
      #include<stdio.h>
      int gvar;
      main()
      {
              int i;
              gvar = 5;
              for (i = 5;i > 0; i--)
             {
                      printf("%5d\n",gvar);
                      dec();
             }
      }
      dec()
      {
             gvar--;
      }
      Output:

      5
      4
      3
      2
      1

      Code:
      /* Program for use of global variables*/
      #include<stdio.h>
      int  length,width,area;
      main()
      {
              printf(“Enter the length of rectangle\n”);
              scanf(“%d”,&length);
              printf(“Enter the width of rectangle\n”);
              scanf(“%d”,&width);
              calc_area();
              printf(“Area is %d\n”,area);
      }
      calc_area()
      {
      area=length*width;
      }
      Output:

      Enter the length of rectangle
      5
      Enter the width of rectangle
      10
      Area is 50

      Local Variables

      The variables declared within particular function are local variables to the function in which they are declared. They are not accessible outside the function i.e., scope of the local variable is local to the function in which they are defined.

      Local variables are created when the function is entered and are destroyed when the function is completed or terminated.

      Code:
      /* Program using Local Variables */
      #include<stdio.h>
      main()
      {
               int lvar = 4;
               funct1();
               printf("Lvar = %d\n",lvar);
      }
      funct1()
      {
               int lvar = 10;
               funct2();
               printf("Lvar = %d\n",lvar);
      }
      funct2()
      {
               int lvar = 15;
               printf("Lvar = %d\n",lvar);
      }
      Output:

      Lvar = 15
      Lvar = 10
      Lvar = 4

      In the above program, local variable ‘lvar’ is declared in main(), funct1() and funct2() means, it is possible to have several local variables in different functions with the same names. From main(), function funct1() is called, from function funct1(), function funct2() is called. After executing funct2() the control will comes back to funct1() and after executing funct1() control comes back to main().

      Arguments Or Parameters


      Functions can communicate with each other, means the calling function can pass the information to the called function. Information is pass to function through arguments or parameters. A calling function can send a package of values for the called function to operate on or to control how the function is to operate. When the calling function sends the information to the called function it is called as argument or parameter passing.

      Code:
      /* Program using parameters */
      #include<stdio.h>
      main()
      {
               int num=50;
                 clrscr();
                 printf("Passing a constant integer");
                 display(50);
                 printf("\nPassing content of variable");
               display(num);
                 printf("\nPassing the value of an expression");
               display(num*5-3);
      }
      display(int val)
      {
               printf(" %d", val);
      }
      Output:

      Passing a constant integer 50
      Passing content of variable 50
      Passing the value of an expression 247

      In the above program, integer variable ‘num’ is declared and initialize to ‘50’. First time the function display() is called by passing constant 50 as an argument. In the second call to the function content of the variable ‘num’ is passed to the function as an argument. In the last call to the function expression ‘num*5-3’ is passed as an argument to the function. The display() function will receive these values and store in its local variable ‘val’ and displays the content of ‘val’ using printf() function. All the values pass to the function are of type integer, hence the receiving parameter must also be of type integer.

      Code:
      /* Demonstrates argument passing */
      #include<stdio.h>
      main()
      {
                int num;
                printf(“Enter any number: ”);
                scanf(“%d”,&num);
                square(num);
      }
      square(int n)
      {
                int sq;
                sq = n*n;
                printf(“Square of %d is %d\n”, n, sq);
      }
      Output:

      Enter any number: 10
      Square of 10 is 100

      Actual And Formal Arguments


      Actual Arguments: When a calling function passes the information to the called function, the information is known as actual arguments or parameters. Actual argument or parameters are pass from the calling function to the called function.

      Formal Arguments: Actual arguments from the calling functions are received in the formal arguments of the called function. Formal arguments are the parameters declared in the brackets in the function definition after the function name.

      The data type of the formal arguments should be same as that of actual arguments and they should also be in the same manner as in the function declaration.

      The formal arguments allow information to be transferred from the calling portion of the program to the called program. They are called as formal arguments. The corresponding argument in the function reference are called actual arguments.

      Following are the points must be considered during argument passing.

      • The number of actual and formal arguments must be same.
      • Data type of actual and formal arguments must be same.
      • Sequence of actual and formal arguments must be same.


      The following program explains argument passing.
      Code:
      /*Program converts lower case character to upper case character using user defined
      function called lower_upper()*/
      # include<stdio.h>
      main()
      {
               char lower;
               printf(“Enter a lower case character: ”);
               scanf(“%c”,&lower); // actual argument
               lower_upper(lower); 
      }
                     
      lower_upper(char c1)    //formal argument
      {
      char upper;
      upper=(c1 >= ‘a’ && c1 <= ‘z’ ) ? (‘A’ + c1 – ‘a’) : c1;
      printf(“Upper case character is %c”,upper);
      }
      Output:

      Enter a lower case character: g
      Upper case character is G

      In the above program, ‘lower’ is character variable. The function call lower_upper(lower) pass the variable lower as an actual argument, the variable ‘lower’ is then received in the character variable ‘c1’ as the formal argument of the function lower_upper().

      Passing More Than One Arguments


      More than one value can be passed to a function as an argument but the number and type of actual arguments must be equal to number and type of formal arguments and they should also be in the same sequence.

      Code:
      /* Program to pass more than one argument */
      #include<stdio.h>
      main()
      {
               int num1,num2;
               printf(“Enter two numbers\n”);
               scanf(“%d%d”,&num1,&num2);
               largest(num1,num2);
      }
      largest(int n1 ,int n2)
      {
               if(n1 > n2)
                        printf(“%d is largest\n”, n1);
               else
                        printf(“%d is largest\n”, n2);
      }
      Output:

      Enter two numbers
      50 10
      50 is largest

      Returning A Value From A Function



      Through parameters values are passed to the function, function may perform operation on those values and may give the processed value to the calling function using return statement. There is two way communication, calling function gives the values to the called function through arguments and the called function in return may give a value to the calling function.

      There is always a single value return from the function.
      Code:
      /* Program for integer return from the function */
      #include<stdio.h>
      main()
      {
                int num1,num2,prod;
                printf(“Enter two integers\n”);
                scanf(“%d%d”,&num1,&num2);
                prod=product(num1,num2);
                printf(“%d * %d = %d\n”,num1,num2,prod);
      }
      product(int n1,int n2)
      {
                return(n1 * n2);
      }
      Output:-

      Enter two integers
      5 20
      5 * 20 = 100

      Function Prototype(Function Declaration)


      Whenever a function is call, the compiler will assume that this function would return a value of the type int. If we want a function should return a value other than an int, then it is necessary to explicitly mention so in the calling function as well as in the called function.

      Return from the function is always through return statement. If the return from the function is of type integer there is no need to declare the function. Functions are to be declared if the return from the function is other than integer. Following is the function prototype:

      return_type function_name(argument_list);


      Here, return_type specifies the type of data return from the function, function_name specifies the name of the function and argument_list specifies the type of arguments to be pass.
      Code:
      /*Return from the function other than integer*/
      #include<stdio.h>
      main()
      {
               float square(float);       /* Function Declaration */
               float a,b;
               printf(“Enter any number\n”);
               scanf(“%f”,&a);
               b=square(a);
               printf(“Square of  %.2f is %.2f \n”,a,b);
      }
      float square(float x)
      {
                float y;
                y=x*x;
                return(y);
      }
      Output:

      Enter any number
      5
      Square of 5.00 is 25.00

      In the above program, function declaration specifies the return from the function is of type float and the argument pass is of type float.

      Note: when the functions are declared the return type is specified in both function declaration and function definition, but not in function call.

      Code:
      /* Program to demonstrates returning the value from the function */
      #include<stdio.h>
      float pdstokg(float);
      main()
      {
               float pds;
               clrscr();
               printf("Enter your weight in pounds:");
               scanf("%f",&pds);
               printf("Your weight is kilogram is %f ",pdstokg(pds));
      }
      float pdstokg(float pounds)
      {
               return 0.453592 * pounds;
      }
      Output:

      Enter your weight in pounds: 70
      Your weight is kilogram is 31.751440

      Code:
      /* Program to find factorial of a given number using function */
      #include<stdio.h>
      long factorial(int n);
      main()
      {
               long int fact;
               int num;
               clrscr();
               printf("Enter any positive integer:");
               scanf("%d",&num);
               fact = factorial(num);
               printf("Factorial of %d is %ld",num,fact);
      }
      long factorial(int n)
      {
               long f=1;
               while(n > 1)
              {
                        f=f * n;
                        n--;
              }
              return (f);
      }
      Output:-

      Enter any positive integer:5
      Factorial of 5 is 120

      Code:
      /* Program to reverse an integer and find sum of its digits */
      #include<stdio.h>
      main()
      {
                int num,sum;
                clrscr();
                printf("Enter an integer: ");
                scanf("%d",&num);
                sum=sumint(num);
                printf("\nThe sum of the digits is %d\n",sum);
      }
      sumint(int n)
      {
            int right_digit,sum=0;
            printf("%d in reverse order is: ",n);
            do
            {
                        right_digit = n % 10;
                        printf("%d",right_digit);
                        sum = sum + right_digit;
                        n = n / 10;
             }
             while(n > 0);
             return (sum);
      }
      Output:-

      Enter an integer: 12345
      12345 in reverse order is: 54321
      The sum of the digits is 15

      Recursion


      Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computation in which each action is stated in terms of a previous result.

      In order to solve a problem recursively, two conditions must be satisfied.
      • There must be some criteria, called base criteria, to stop the recursion.
      • Each time the function call itself, it must be closer to the base criteria.


      Code:
      /* Program to calculate the factorial of an integer using recursion */
      #include<stdio.h>
      main()
      {
                int n,fact;
                printf(“Enter an interger\n”);
                scanf(“%d”,&n);
                fact=factorial(n);
                printf(“Factorial of %d is %d\n”,n,fact);
      }
      factorial( int m)
      {
               if(m<=1)
                         return(1);
               else
               return(m*factorial(m-1));
      }
      Output:

      Enter an integer
      5
      Factorial of 5 is 120

      In the above program, the return statement gives back the result to the main program for every integer up to the required number. The factorial of a particular number is find out by multiplying that number with the factorial of the previous number. For example,

      factorial(5) = 5*factorial(4) → 120
      factorial(4) = 4*factorial(3) → 24
      factorial(3) = 3*factorial(2) → 6
      factorial(2) = 2*factorial(1) → 2
      factorial(1) = 1

      Code:
      /* Program to find power using recursion */
      #include<stdio.h>
      main()
      {
               int num,exp,ans;
               clrscr();
               printf("Enter an integer: ");
               scanf("%d",&num);
               printf("Enter raised to power: ");
               scanf("%d",&exp);
               ans = power(num,exp); 
               printf("%d raised to %d is %d\n",num,exp,ans);
      }
      power( int n, int x)
      {
                int pow = 0;
                if(x == 0)
                         pow=1;
                else
                pow = n*power(n,x-1);
                return (pow);
      }
      Output:

      Enter an integer: 2
      Enter raised to power: 5
      2 raised to 5 is 32



    Disclaimer: Users of techforum4u.com are responsible for ensuring that any material they post (article, blog posts, images or other mulitimedia content) does not violate or infringe upon the copyright, patent, trademark, or any personal or proprietary rights of any third party, and is posted with the permission of the owner of such rights.Anyone who violates these rules may have their access privileges removed without warning.