ICS 103: Computer Programming in C

Handout-09

Topic: Functions with Input Parameters

 

Instructor: M. Waheed Aslam.

 

Objective:

·        To know what is a Function in C language and why we need functions.

·        To know the general form of Function Definition.

·        To know about Function Prototype and its importance.

·        To learn how to write user defined functions with input parameters.

·        To know the use of void in function.

·        To know about actual and formal parameters of a function.

·        To know about different forms of return statement and their uses.

 

What is a function in C Language?

·        Functions are the building blocks of any C program.

·        In fact, a C program is a collection of functions e. g., main ( ), scanf( ), printf( ), sqrt(x), pow(x,y)…… sin(x), cos(x) etc.

·        Functions can be User defined or Standard Functions.

 

Why functions needed?

·        Dividing a large program into functions improves the understanding of the problem.

·        Makes programs easy to correct errors and easy to maintain and update

·        A function can be executed (called) from several locations in a program.

·        It is not necessary to know the internal code of a function in order to be able to use it. For example, we do not know the code for the function printf(), but we know how to use it.

·        Reuse of function subprograms.

 

Function definition (writing the function code):

The general form for function definition is:

 

Text Box: function_return_type  function name  (parameter list separated by commas )

 

Function type: (or function return type) is the type of data item that is returned to the caller, such as int, double, …etc.

 

Function name: (or function identifier) is the name of the function. The same rules for the variable (identifiers) names are applied to function names as well. Functions are identified and are called (referred to) by their names.

 

Parameter (or argument) list: specifies the type of data items passed to the function. The data types are placed between parentheses, and if there is more than one item, they are separated by commas.

 

Function prototype (declaring a function):

Like variables, functions must be declared before they are used. The function prototype serves as a function declaration. The general form for function declarations (i.e., function prototype is):

 

double large(double x1, double x2, char y);


 

For Example:

int sum ( int, int);   declares a function called sum with a parameter list that consists of two int type data items. That is sum() expects two int type data items when it is called, and returns an int type data item to the caller.

 

Note: Specifying a name for each of the items in the parameter list is optional, but highly recommended.

 

e. g.,    int sum (int x, int y);

 

 

Function with Input Arguments (also called Parameters) which can return a single value at a time:

 

·        Till now we were using only one function, the main function in our programs.

·        Programs can also be written where there can be one or more function subprograms other than the main function.

·        The program should always have a main function whether it has function subprograms or not.

·        Without the main function the program will not do anything as the program always starts execution from the main function.

 

Functions can be of the following different types:

·        Functions  returning  no value and accepting no value.

·        Function  returning  no value but accepting  one or more values.

·        Function returning  one value and accepting  one or more values.

 

Let abc be a function name:

 

Then, function abc that does not return any value and does not accept any value can be declared as:

                void abc (void)

 

Function that accepts one or more value and returns no value can be declared as:

                void abc (int x, float y, double d, int a)

 

Function that returns one value and accepts one or more values can be written as:

                int abc (int b, double k, char p)

Here the function is returning an integer value.

 

 

Whereas, the function:      

float abc (int g, char h, double r)

returns a float value.

 

 

·        Input parameters(Arguments) in any function are those arguments which are declared as ordinary variables and which are used to supply some input to function and

·        Output Parameters/Output Arguments in any Function are special variables which are declared as pointers and which are used to carry (return) more than one output from the function .

 

·        Function using only input parameter/argument can return only single value at a time while by using output parameters in any function that function can return more than one value (result) at a time.

 

In this Handout we will study only Function with Input parameter/Argument which can return only single value at a time.

 

 

Let us consider some examples:

 

Example (i):

 /* Function with Input Arguments and a Single Result */

 #include<stdio.h>                         

   return type   function name         formal parameter


void  print_rboxed (double rnum) // User defined function

{

printf("**********************\n");

printf("*                    *\n");

printf("* %7.2f            *\n", rnum);

printf("*                    *\n");

printf("**********************\n");

} // end of print_rboxed  user defined function

 

void main( )  // calling function

{                                       actual parameter


print_rboxed(2.24567); // function call

 

}// end of main

 

Sample output:

 

 

 

 

Example (ii):

 /* Function to find the larger of two numbers */

#include<stdio.h>

 

double bigger(double n1, double n2)  // function definition

{

 

double larger; // variable declaration

 

if(n1>n2)

  larger=n1;

else

  larger=n2;

return (larger);  // returns value of larger to calling plaice in main function

 

} // end of bigger function

 

void main( )

{

 

double number1,number2, max; // variable declaration

printf("Please input two numbers :");

scanf("%lf %lf", &number1, &number2); // input

 

max = bigger(number1, number2); // function call

 

printf("The max of  %lf and %lf is = %lf",number1,number2,max);

 

} // end of calling main function

 

Sample Output:

 

 Example (iii):

 #include<stdio.h>

float mul(x,y) // user defined function mul

float x,y;

{

float p;

p=x*y;

return(p);

} // end of mul function

 

float division(float number1, float number2) // user defined function division

{

float div;

div=number1/number2;

return div;

} // end of division function

 

void main( ) // calling function

{

float n1, n2, product, d;

printf("Please input value of n1 and n2 : ", &n1, &n2);

scanf("%f %f", &n1, &n2);

 

product = mul(n1, n2); // function call

d = division(n1, n2);  // function call

 

printf("The product of %f and %f is = %f\n", n1, n2, product);

printf("The division of %f and %f is = %f", n1, n2, d);

 

return;

} // end of main

 

Sample Output :

 

Example (iv):

A short function is written below to calculate the net pay of an employee based on values for the wage rate and hours worked. These values are passed as arguments to function called calc_net_pay. The function then computes the net pay and returns the computed value to main.

 

 

#include <stdio.h>

 

float   calc_net_pay (float wage, int hours) ;   /* function prototype. Write this before main always */

 

void main (void)

{

     float   wage, net_pay ;

     int hours ;

 

    printf (“Enter the wage rate and number of hours worked\n”) ;  /* Ask the user to enter input */

    scanf (“%f %d”, &wage, &hours) ;                             /* read input */

    net_pay = calc_net_pay (wage, hours) ;    /* call the function by passing the input variables */

    printf (“The net pay = %8.2f\n”, net_pay) ; /* print the result stored in net_pay returned by  function */

} // end of main

 

float   calc_net_pay (float wage, int hours)  /* function header same as function prototype*/

                                                                    /* given at the start of program */

{

          float   g_pay, f_tax, soc_sec, net_pay ;                  /* function body */

          const float   FED_TAX = 0.28 ;                   /* constant declaration */

          const float   SOC_SEC = 0.055 ;

 

          g_pay = wage * hours ;

          f_tax = FED_TAX * g_pay ;

          soc_sec = SOC_SEC * g_pay ;

          net_pay = g_pay – (f_tax + soc_sec) ;

          return ( net_pay ) ;     /* end of function by returning the result in net_pay */

} // end of main

 

Here:

·        The calc_net_pay function is called from main and it takes two arguments (wage and hours) which are usually the input variables.

·        The name of the function, the number of arguments and the types of arguments should always be same while calling the function and while declaring the function in the header or as prototype.

·        Once the function is called, control is transferred to the function and returns back to the main program with the return statement.

 

In the above program:

·        if the function calc_net_pay does not return any value then it has to print the result inside the function itself.

·        Also while calling the function just call the function along with its arguments without assigning the call to any variable.  This is made clear in the following Example:

 

Example(v):

 

#include <stdio.h>

 

void   calc_net_pay (float wage, int hours) ; /* function prototype. Write this before main always */

 

void main (void)

{

     float   wage, net_pay ;

     int hours ;

 

    printf (“Enter the wage rate and number of hours worked\n”) ;  /* Ask the user to enter input */

    scanf (“%f %d”, &wage, &hours) ;                                /* read input */

    calc_net_pay (wage, hours) ;     /* call the function by passing the input variables */

} // end of main

 

void   calc_net_pay (float wage, int hours)    /* function header same as function prototype*/

                                                                        /*given at the start of program */

{

          float   g_pay, f_tax, soc_sec, net_pay ;                  /* function body */

          const float   FED_TAX = 0.28 ;                   /* constant declaration */

          const float   SOC_SEC = 0.055 ;

 

          g_pay = wage * hours ;

          f_tax = FED_TAX * g_pay ;

          soc_sec = SOC_SEC * g_pay ;

          net_pay = g_pay – (f_tax + soc_sec) ;

          printf (“The net pay = %8.2f\n”, net_pay) ;   /* print the result stored in net_pay */

 

} // end of user defined function  calc_net_pay

 

 

Argument List Correspondence Rules:

·        The number of actual arguments (parameters), the order of actual argument and type of actual arguments used in a call to a function must be the same as the number of formal parameters, the order of formal parameters and type of formal parameters/arguments listed in the function definition.

 

Use of return Statement in Function:

A return statement can take one of the following two form:

 

              return;

                     Or

              return (expression );

 

·        The first, the ‘plain’ return does not return any value, just it returns control to calling function.

e.g.,

          if(error)

               return;

 

·        The second form of return with an expression returns the value of the expression.

e.g.,

           int mul(x,y)

           int x,y;

             {

               int p;

               p=x*y;

               return(p);

              }

     In the above, the last two statements:

p=x*y;

                  return(p);

      can be combined into one statement as follows:

                   return (x*y);

 

Can a function have more than one return Statement?

 

Yes. A function may have more than one return statement. This situation arises when the value returned is based on certain conditions:

e.g.,

                  if(x<=0)

                   return(0);

             else

                   return(1);   

 

Note: All functions by default return int type data. But we can make it any type.