4.1 Functions: Lecture Notes C Programming For Problem Solving (18CPS23)
4.1 Functions: Lecture Notes C Programming For Problem Solving (18CPS23)
4.1 Functions
A Function is a program segment that is used to compute a value or perform specific and well
defined tasks. They cannot run independently and are always called by the main( ) of the program or
by some other functions.
1) Library or built in functions : These functions are used to perform standard operations and are
available along with the C compiler. They require appropriate header files to be included at the
beginning of the program.
2) User defined functions : These are functions written by the programmer / user to compute a
value or perform specific and well defined tasks. Generally, these are written if library functions are
not available for doing that task.
Ex: Suppose if we want to find square of a number. The library function to do this task is not
available. So, we can write a user defined function square( ), which gives / returns the square of a
number.
1) Reusability and reduction of code size : Functions once written can be reused as a block of
statements to create a new program. Also, they are very much useful when a block of statements
has to be executed repeatedly. Use of functions results in reduced program size and memory
requirement.
2) Modular Programming : When the program size is too large or complex, it can be split into
smaller units called modules. For each module a function can be written making it modular
programming.
3) Improved readability of the program : Programs written using functions follow modular
programming and hence readability of the program is greatly improved.
4) Easier debugging: Modular programming reduces the difficulties during debugging a program and
errors can be easily identified.
5) Build Library : Functions that are used repeatedly can be generalized, tested and kept in a library
for future use. This reduces program development and coding time.
#include<stdio.h>
c = a + b;
Note:
         .......
         .......
         executable statements;
         .......
         .......
         return statement;
}
where,
   − Return type indicates the type of data that the function returns. Void indicates that the
         function does not return anything.
    −    function name is any valid identifier.
    −    Formal parameter list is a comma separated list of variable names and their associated
         types. These parameters receive values from the calling function.
    −    local variable declaration specifies the variables needed by the function.
    −    executable statements performs the actual job of the function
    −    return statement returns the control back to the calling function with the value computed(if
         any).
Example:
c = a+b;
         return c;
}
2) Function Call
    −    A function can be called by specifying the function name followed by a list of actual
         parameters (arguments), if any, enclosed in parenthesis.
The general format is
function name (actual parameter list);
where
    −    function name is the name of the function that is to be executed
     −   actual parameter list is a comma separated list of values without their data types. The list
         will have the actual values passed to the called function and hence named as actual
         parameters or arguments.
Example:
sum = m + n;
         return sum;
}
void main( )
{
       int a,b,c;
Actual parameters can be constants, variables or Formal parameters should be only variables.
expressions                                      Expressions and constants are not allowed.
Actual parameters sends value to the formal Formal parameters receives values from the
parameters                                  actual parameters
Addresses of actual parameters can be sent to If actual parameters sends the address then the
the formal parameters                         formal parameters should be declared as
                                              pointers.
function2( )
        }                                                 }
                               No Return Value                                 No data communication
Example:
#include<stdio.h>
void add( )
{
        int a, b, result;
        printf(“Enter 2 numbers\n”);
        scanf(“%d%d”, &a, &b);
        result = a + b;
        printf(“Result of addition = %d\n”, result);
}
void main( )
{
       add( );
}
Note: When there is nothing to be returned, the return statement is optional, the closing brace of
the function itself signals the end of execution of function returning the control back to the calling
function.
2) Functions with no arguments but a return value
    −   no arguments: indicates that the function does not receive any data or input from the calling
        function.
    −   return value : indicates that the function not sends or outputs one value using the return
        statement to the calling function.
    −   This is depicted in the figure with the arrows indicating the transfer of control
function2( )
        }                                                 return a;
                              Return one value            }
                                                                         One-way data communication
Example:
#include<stdio.h>
int add( )
{
         int a, b, result;
         printf(“Enter 2 numbers\n”);
         scanf(“%d%d”, &a, &b);
         result = a + b;
         return result;
}
void main( )
{
         int c;
         c = add( );
         printf(“Result of addition = %d\n”, c);
}
                               Values of
        function1( )           arguments                  function2( b )
        {                                                 {
function2( a )
        }                                                 }
                                 No Return Value                           One-way data communication
Example:
#include<stdio.h>
void add( int c, int d )
{
        int result;
        result = c + d;
        printf(“Result of addition= %d\n”,result);
}
void main( )
{
       int a, b;
       printf(“Enter 2 numbers\n”);
       scanf(“%d%d”, &a, &b);
       add(a, b);
Note:
1) The values of actual parameters are assigned to the formal parameters on a one to one basis,
starting with the first parameter.
2) Here, only a copy of the values of the actual parameters are passed to the called function. The
manipulation of these inside the function will have no effect on the actual parameters.
                                Values of
         function1( )           arguments                  function2( b )
         {                                                 {
function2( a )
         }                                                  return c;
                                Return one value           }
                                                                            Two-way data communication
Example:
#include<stdio.h>
int add( int c, int d )
{
         int result;
         result = c + d;
         return result;
}
void main( )
{
       int a, b, c;
       printf(“Enter 2 numbers\n”);
       scanf(“%d%d”, &a, &b);
       c = add(a, b);
       printf(“Result of addition = %d\n”, c);
}
Note:
1) The C function returns a value of type int as the default case when no other type is specified
explicitly.
void main( )
{
       int l, b, area;
       printf("Enter the length and breadth of the rectangle\n");
       scanf("%d%d", &l, &b);
       area = area_of_rectangle(l, b);
       printf("area = %d\n", area);
}
void main( )
{
       int a, b, big;
       printf("Enter 2 unequal numbers\n");
       scanf("%d%d", &a, &b);
       big = bigger(a, b);
       printf("big = %d\n", big);
4.6 Implement using functions to check whether the given number is prime and display
appropriate messages. ( No built in math function).       (Lab Program number 7)
#include<stdio.h>
void main( )
{
       int n;
        checkprime( n );
}
Note:
1) A number 'n' cannot be divided by a number which is greater than n/2. For example, consider the
number n = 16, it is not divisible by 9, 10, 11, 12, 13, 14 and 15 which are all greater than 16/2
2) A number 'n' may be divided by some number in the range 2, 3, 4, 5, ......., n/2. For example, 16
can be divided by 2, 4 and 8
Nesting of Functions
    −   C permits nesting of functions. main( ) can call functions1( ), which can call function2( ),
        which can call function3( ) and so on. In principle, there is no limit as to how deeply the
        functions can be nested.
Example: Write a C program to check whether a given number is positive or negative, if it is
positive then check whether it is odd or even.
#include<stdio.h>
void checkpositive(int n)
{
        if(n>0)
        {
                printf("Number is positive\n");
                checkoddeven(n)
        }
        else
        {
                printf("Number is negative\n");
        }
}
void checkoddeven(int n)
{
        if(n%2==0)
        {
                 printf("Number is Even\n");
        }
        else
        {
                 printf("Number is Odd\n");
        }
}
void main()
{
        int n;
        printf("Enter a non zero number\n");
        scanf("%d",&n);
        checkpositive(n);
}
Note: Nesting does not mean defining one function within another, this is not permitted in C.
void main( )
{
       int a[10], n;
read( a, n);
         write( a, n);
}
Note: In read / write function, name of the array can be changed, example in read x[ ] and write y[ ].
1) Write a ‘C’ program to find biggest element in an array of ‘n’ integers using functions
#include<stdio.h>
         max = a[0];
         for( i = 1; i < n ; i + + )
         {
                   if(a[i] > max)
                   {
                              max = a[i]
                   }
         }
         printf(“biggest element = %d\n”, max );
}
void main( )
{
       int n, i, a[20];
         bigger( a, n);
}
        for( i = 0; i < n ; i + + )
        {
                 if(key = = a[i])
                 {
                         return i + 1;
                 }
        }
        return -1;
}
void main( )
{
        if(pos = = -1)
        {
                printf(“UNSUCCESSFUL SEARCH\n” );
        }
        else
        {
                printf(“SUCCESSFUL SEARCH\n” );
                printf(“Element found at %d location\n”, pos );
        }
}
        low = 0;
        high = n-1;
        while( low < = high )
        {
                mid = (low + high) / 2;
                if(key = = a[mid])
                {
                        return mid + 1;
                }
                if(key < a[mid])
                        high = mid – 1;
                if(key > a[mid])
                        low = mid +1;
        }
        return -1;
}
void main( )
{
      int n, i, a[20], key, pos ;
      printf(“Enter the number of elements\n”);
      scanf(“%d”, &n);
      printf(“Enter the elements\n”);
      for( i = 0; i < n ; i + + )
      {
                scanf(“%d”, &a[i] );
      }
        if(pos = = -1)
        {
                printf(“UNSUCCESSFUL SEARCH\n” );
        }
        else
        {
                printf(“SUCCESSFUL SEARCH\n” );
                printf(“Element found at %d location\n”, pos );
        }
}
#include<stdio.h>
void main( )
{
      int n, i, a[100];
bubblesort( a, n);
#include<stdio.h>
void main( )
{
      int n, i, a[100];
      printf("Enter the value for n:\n");
      scanf("%d",&n);
      printf("Enter the array elements\n");
      for(i=0;i<n;i++)
      {
                scanf("%d",&a[i]);
      }
      printf("The array elements before sorting are\n");
      for(i=0;i<n;i++)
      {
                printf("%d\n",a[i]);
      }
selectionsort( a, n);
    −   The function must be called by passing only the name of the array
    −   In the function definition, the formal parameter must be an 2D array type (write 2 sets of
        brackets)
    −   The size of the second dimension must be specified.
    −   The function prototype must show that the argument is a 2D array.
void main( )
{
      int a[10][10], m, n;
read( a, m, n);
        write( a, m, n);
}
void multiply(int a[ ] [10], int b[ ][10], int c[ ][10], int m, int n, int q)
{
      int i, j, k;
        for( i = 0; i < m ; i + + )
        {
                 for( j = 0; j < q ; j + + )
                 {
                          c[i][j] = 0;
                       for(k = 0; k < n ; k + + )
                       {
                               c[i][j] = c[i][j] + a[i][k] * b[k][j];
                       }
                }
       }
}
void main( )
{
      int m, n, p, q, a[10] [10], b[10][10], c[10][10];
       if(n!=p)
       {
               printf("Multiplication is not possible\n");
               exit(0);
       }
multiply( a, b, c, m, n, q);
4.12 Recursion
It is a process in which an object is defined in terms of simpler case of itself.
Direct Recursion
A function which calls itself repeatedly is called recursive function.
Ex:      a ( formal parameters)
         {
                 ---------
                 ---------
                 a (arguments);
                 ---------
         }
Note: The important requirements or constraints that every recursive function should satisfy
are
       Every time a function is called, it should be nearer to the solution.
       There should be at least one statement to terminate recursion.
The recursive function calls are initially pushed on to the stack until the terminating condition
is met. After encountering the terminating condition the recursive functions are popped from
the stack and executed.
Indirect Recursion
A recursive function need not call itself directly. Rather, it may contain a call to another
function which eventually calls the first function and both are termed recursive.
Ex:      a ( formal parameters)                        b ( formal parameters)
         {                                             {
                 ---------                                     ---------
                 ---------                                     ----------
                 b (arguments);                                a (arguments);
                 ---------                                     ---------
         }                                             }
Here function ‘a’ calls ‘b’, which may in turn call ‘a’, which may again call ‘b’. Thus both ‘a’
and ‘b’ are recursive, since they indirectly call on themselves.
However the fact that they are recursive is not evident from examining the body of either of
the routines individually.
4.13: Examples
1) Factorial Function
Given a positive integer ‘n’, n! is defined as the product of all integers between ‘n’ and 1. The
exclamation mark (!) is often used to denote the factorial function.
Ex: 5! = 5x4x3x2x1
    3! = 3x2x1
    0! = 1
The recursive definition to find the factorial of ‘n’
                 1         if (n  0)
fact(n) =                             
          n * fact (n  1) otherwise 
Ex: To compute 4!
                     4!=4x3!
                                   3!=3x2!
                                               2!=2x1!
                                                           1!=1x0!
                                                                       0!=1
                                                           1!=1x1=1
                                               2!=2x1=2
                                   3!=3x2=6
                     4!=4x6=24
void main( )
{
      int n, result;
      printf(“enter the value of n\n”);
      scanf(“%d”, &n);
      result = fact(n);
      printf(“factorial of %d = %d\n”, n, result);
}
Module 4                  Prof. C K Marigowda & Prof. Arun K H                                 2
                                     Dept. of ISE, AIT
Lecture Notes                              C Programming for Problem Solving [18CPS23]
2) Fibonacci Sequence
The Fibonacci sequence is the sequence of integers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …….
The first two numbers 0 and 1 are the initial values. The nth Fibonacci number is the sum of
the two immediate preceding elements.
The recursive definition to find the nth Fibonacci number is given by
                     0            if (n  1) 
                                              
Fib(n) =             1            if (n  2)
          Fib(n  1)  Fib(n  2) otherwise 
                                              
The recursive tree for fib(5) is as shown below
}
void main( )
{
      int m, n, result;
      printf(“enter the values of m and n\n”);
      scanf(“%d%d”, &m,&n);
      result = GCD(m,n);
      printf(“GCD of %d and %d = %d\n”, m, n, result);
}
Module 4                Prof. C K Marigowda & Prof. Arun K H                          4
                                     Dept. of ISE, AIT
Lecture Notes                                     C Programming for Problem Solving [18CPS23]
void main( )
{
      int n, r, result;
      printf(“enter the values of n and r\n”);
      scanf(“%d%d”, &n,&r);
      result = fact(n) / fact(n-r) * fact(r);
Module 4                     Prof. C K Marigowda & Prof. Arun K H                          5
                                        Dept. of ISE, AIT
Lecture Notes                             C Programming for Problem Solving [18CPS23]
#include<stdio.h>
int binarytodecimal(int n)
{
        if(n = = 0)
                return 0;
        else
                return( n%10 + binarytodecimal (n/10) * 2 );
}
void main( )
{
      int decnum, binnum;
Example:
n = 1001
btod(0) = return 0
C supports 4 types of storage class specifiers extern, static, register and auto
The storage class specifiers tells the compiler how to store the subsequent variables, like
    −   where the variable should be stored
    −   what will be the default initial value
    −   the scope : determines over what region of the program a variable is actually
        available for use.
    −   life time : refers to the period during which a variable retains a given value during the
        execution of a program.
    −   visibility : refers to the accessibility of a variable from the memory.
Apart from their data type, all variable also have a storage class. There are 4 storage classes
1) automatic or local or internal
2) global or external
3) static
4) register variables
1) Automatic Variables
    −   They are created (memory is allocated) each time the function is called and destroyed
        automatically when the function is exited.
        storage : RAM
        default initial value : garbage value
        scope : local to the function in which it is defined
        life time : till the control remains within the function
    −   Since they are private or local to the function in which they are declared, they are also
        called as internal or local variables.
    −   It is possible to declare and use the same variable name in different functions of the
        same program.
Example:
void main( )
{
        int num;               // the keyword auto is optional
        auto float x;
}
2) Global Variables
    −   They are created (memory is allocated) when the program execution starts i.e. only
        once and destroyed when the program terminates.
        storage : RAM
        default initial value : zero
        scope : global
        life time : till the program execution does not come to an end
    −   Since they are global, these variables can be accessed by any of the functions in the
        program and are generally declared outside the functions (usually in the beginning)
Example:
int num;
float x = 3.5;
void main( )
{
        ........
}
function1( )
{
        ........
}
function2( )
{
        ........
}
num and x are available for use in all the three functions
Note 1
If a local variable and a global variable have the same name, the local variable will have
precedence over the global one in the function where it is declared.
Output
x = 10
x = 20
x=1
x = 30
Note 2
The global variable is available only from the point of declaration to the end of program.
Example:
void main( )
{
      y = y + 10;
      printf("y = %d\n", y);
      function1( );
}
function1( )
{
       y = y + 20;
       printf("y = %d\n", y);
}
void main( )
{
        extern int y;
// Informs the compiler that y is an integer data type defined somewhere else in the program
        y = y + 10;
        printf("y = %d\n", y);
        function1( );
}
function1( )
{
       y = y + 20;
       printf("y = %d\n", y);
}
Output
y = 10
y = 30
3) Static Variables
     −   They are permanent variables and maintain their values between function calls i.e. the
         value of these variables persists until the end of the program
         storage : RAM
         default initial value : zero
         scope : local to the function in which it is defined
         life time : till the program execution does not come to an end
It has the features of both local and global variables. Like a local variable the static variables
cannot be accessed outside the function in which it is defined and like a global variable
memory for a static variable is allocated only once when the function is called and the
memory is deallocated only when the program terminates.
Note: A static variable stores the information even after the control comes out of the fucntion.
Example:
Ordinary variable                                  Static variable
#include<stdio.h>                                  #include<stdio.h>
Output Output
11                                                 12
11                                                 13
11                                                 14
4) Register Variables
    −    This specifier tells the compiler to keep the value of the variable in a register of the
         CPU rather than in memory (where normal variables are stored)
         storage : CPU register
         default initial value : garbage value
         scope : local to the function in which it is defined
         life time : till the control remains within that function
Example:
void main( )
{
      register int i;