Module 4 - Part 1 Notes
Module 4 - Part 1 Notes
The concept of top-down design has taught us that it is better not to approach
a problem as a single unit but to break it down into smaller manageable parts called
as modules. Each module can then be approached and solved separately and then
combining all the modules can generate the final solution to the problem.
The programs we wrote till now were small and manageable. Just writing
small programs may not solve most problems; we may have to sometimes write very
large programs. Large programs are difficult to handle and manage. Large programs
can be made manageable by dividing it into smaller sub-programs or modules.
These sub-programs are called as functions.
C also allows users to create their own functions or sub-programs; they are
normally referred to as user defined functions. A user-defined function is a complete
and independent program unit, which can be used (or invoked) by the main program
or by other sub-programs or functions. Sub-programs are written to perform definite
calculations, after performing their task they send back the result to the calling
program or sub-program.
ii. Universal use : Some tasks might be needed in more than one program or a
large group of programmers may need the same task. By writing a function and
making it available to others the duplication of effort can be avoided.
1. The first task of the user is to define the function i.e., to create the
function. A function can be defined either before the main program or
after the main program or in another file.
2. Once the function is created it has to be called. A function can be called
either in the main program, which is also a function or in another function.
Thus there are two functions the calling function and the called function.
3. Whenever a function is called control is transferred from the calling function
to the called function. During this process some data is also transferred from
the calling to the called function.
4. The statements of the called function are now executed one after the
other from the beginning to the end. The working inner details are not
visible or known to the calling function.
5. After performing the required operation the called function finally returns
the required result back to the calling function i.e., control is now
transferred back to the calling function from the called function.
6. The calling function continues its execution.
3. FUNCTION DEFINITION
The return_ type_ specifier identifies the type of value, which will be sent back
after the function has performed its task. The return_ type_ specifier can include the
normal data types such as int, float, char the data type void is used if the function does
not return a value.
ii. Function_name
A single program may have any number of functions included in it. It may be
difficult to identify which function is to be executed if a function does not havea
name to identify it. The Function_name thus helps us to uniquely identify and call
a function.
iii. Argument list with declaration
The argument list identifies the set of values, which are to be passed to the
function from either the main program or a subprogram. Like every variable usedin
a program the argument list should also be declared. The sequence of declarations
should correspond to the data types of the values, which will be passed from the main
program to the function.
Next a function contains a set of executable statements, which will perform the
required task for the user. The last executable statement of the function is the word
return with an expression, which contains the value that has to be sent back to
the main program.
n)
while ( n >0)
The first line starts with the return type specification that identifies the value
that will be returned by the function (in this case int). The return_type_specifier is
followed by the function name and a pair of parentheses enclosing
a formal argument which is declared. The argument specifies variables, which
constitute the input to the function.
The rest of the function is a compound statement that defines the action to
be performed by the function. This is called the body of the function. Within the body
of the function, the variable declarations and statements appear in typical C
programming style. The exception is the return statement, which specifies the value to
be returned to the calling routine. The value returned must be of the type specified in
the header line. The parentheses are not required, but most programmers use them
for clarity.
4. FUNCTION CALL
To execute a function we will have to call the function. A function call establishes
a proper link between the function and the calling program unit. When the function is
called values are passed to the function through the use of actual parameters or
arguments.
Syntax :
All the concepts studied till now are highlighted in the following
programming example.
Program 1 : A C program to find the sum of the digits of a number until the
resulting value is a one digit number.
# include <stdio.h>
int sum_of_digits ( int ); /* Function prototype */
main ( )
{
int num, sum,n;
a number \n
scanf ( &num);
n = num;
while( n >=9 )
{
sum = sum_of_digits ( n);
n = sum;
}
is = %d \ num);
Sum of digits until one digit = %d \ sum);
}
5. RETURN STATEMENT
Syntax :
The first return does not return any value. The return statement simply returns
control to the point from where it was called from, in the calling program. The second
form of return with an expression returns a single value of the expression.
Example 3 :
int sum_of_digits ( int n)
{
int d,s=0;
while ( n >0)
{
d = n % 10;
n = n / 10;
s = s + d;
}
return (s) ;
}
the function sum_of_digits returns the value of s which is the sum of the digits of the
number n. If a function were to find the product of two numbers then its function body
may be as follows.
Example 4 :
int product( int a , int b )
{
int x;
x = a * b;
return ( x );
}
The following few points may be noted with respect to actual and formal arguments:
#include <stdio.h>
int num_digit ( int ); /* Function prototype */
main( )
{
int num, num_dig;
Variables declared inside a block or function are said to belong only to that block
and are referred to as Local variables. Values of local variables are available only in
that block and not outside it.
All the variables to be used within a function block must be defined. The
variables and are defined within the function block of the function( ). They
are termed as local variables. The scope of the local variables is confined only to the
function in which it has been defined. The same variable name may be given in another
function and each variable, will be treated as a different entity.
Variables declared in the declarations before the main function block are called
Global variables. The values of the global variables are available throughout the
program and in every block of the program.
The global variables are defined outside the main function. These variables are
referred to the same data type and the same name throughout the program in both the
calling function and a called function. Whenever some of the variables are treated
as same value in both main and a function, it is advisable to use global variables.
Program 3: A C program to find the largest of two numbers using the global
variable declaration.
#include <stdio.h>
int num1, num2, lar; /* Global declaration */
int largest (void); /* Function prototype */
main( )
{
two numbers
&num1, &num2);
of %d and %d is %d ));
}
/* Function to find the largest of two numbers */
int largest( )
{
lar= (num1>num2) ? num1 : num2;
return(lar);
}
OUTPUT
Enter two numbers 25 37
Largest of 25 and 37 is 37
c. FUNCTION PROTOTYPES
All variables used in a program are declared in the declaration section ofthe
program. This helps in providing a proper memory representation for the variableand
in identifying the operations that can be performed on them. Similarly it may be
necessary to identify the existence of a function with the help of a declaration.
A prototype is used to identify the type of value that will be returned to the
calling subprogram and this helps the compiler to generate the correct code for the
return data and a prototype can also identify the sequence and number of arguments
used by the function. A function prototype may have the following syntax:
Syntax :
1. If the function body appears before the sub program, which calls it.
2. If the function returns a value of the type integer as all functions by
default are assumed to return an integer value.
# include <stdio.h>
void swap_ values ( int, int );
main( )
{
int x = 5 , y = 10;
Values before the function call \
x = % d y = % d \n x, y);
swap_ values ( x, y ); /* Function call */
Values after the function call \
x = % d y = % d \n x, y);
}
void swap_ values ( int a, int b )
{
int t;
t = a;
a = b;
b = t;
Values inside the function after swapping\
x = % d y = % d \n a, b);
}
d. TYPES OF FUNCTIONS
In this type of function the first function calls the second function. However
no arguments are passed to the second function. The second function performs its
calculations but no value is sent back to the first function. The general syntax of such
functions are:
Calling Function Action Called Function
Function1( ) Function2( )
{ {
no arguments
# include <stdio.h>
main ( )
{
Our_address( ); /* calling Our_address( ) function */
}
/* Function to print our address */
Our_address( )
{
printf ( \n H. K. Gundu
printf ( \n N. S.
printf ( \n M.N.
printf \ printf
( \
}
In the above example, there is no data transfer between the calling function
and the called function. When a function has no arguments, it does not receiveany
data from the calling function. Similarly, when it does not return a value, the calling
function does not receive any data from the called function.
In this type of function the first function calls the second function by passing
some arguments or values to the second function. The second function performs its
calculations but no value is sent back to the first function. The general syntaxof
such functions are :
Function1( ) Function2 ( a )
# include <stdio.h>
void char_type (char); /* Function prototype */
main ( )
{
char ch;
printf( a character \
&ch);
char_type ( ch ); /* Function call */
}
OUTPUT
Enter a character
N
N is an upper case alphabet
In the above program, the main program reads the input data from the
terminal and passes it on to the function. The function after checking the type of
character outputs the answer in the function itself.
# include <stdio.h>
void reverse_check ( int ); /* Function prototype */
main ( )
{
int num;
s = 0;
num = n;
while ( n > 0 )
{
r = n % 10;
n = n / 10;
s = s * 10 + r;
}
printf ( Reverse = %d \ s);
if ( s == num)
is a palindrome \
else
%d is not a palindrome \
In the above program, we are calling function i.e., the main program reads
the input data from the terminal and passes it on to the called function. The function
reverses the number and outputs the answer in the function itself.
3. Functions with arguments and return values
In this type of function the first function calls the second function by passing
some arguments or values to the second function. The second function performs its
calculations and returns the answer or a value back to the first function. The general
syntax of such functions are:
Function1( ) Function2 ( a )
return ( e ) ;
Program 8 : A C program to find all prime numbers in the range N and M using
functions.
# include <stdio.h>
# include <math.h>
int is_prime ( int ); /* Function prototype */
main ( )
{
int N, M, i, flag;
the lower limit \n
scanf ( &N);
the upper limit \n
scanf ( &M);
if ( N > M)
Invalid range entered \
else
{
Prime nos between %d and %d are \ N, M)
for ( i = N ; i <= M ; i++ )
{
flag = is_prime( i ); /* Function call */
if ( flag )
printf ( \ i );
}
}
}
/* Function to find whether a number is prime or not */
int is_prime (int n )
{
int i, u, f = 1;
u = (int) sqrt(n);
for ( i = 2 ; i < = u && f ; i++ )
if ( ( n % i ) == 0 ) f =0 ;
return (f);
}
OUTPUT
Enter the lower limit
10
Enter the upper limit
25
prime nos between 10 and 25 are
11 13 17 19 23
In the above program, the function is_prime( ) receives data from the calling
function through arguments and the function returns an answer which indicates
whether the number is prime or not.
Program 9 : A function to find the GCD and LCM of two numbers using functions.
#include <stdio.h>
int GCD( int, int ); /* Function prototype */
main()
{
int a, b, g, l;
the numbers a and b \
&a, &b);
GCD of %d and %d = %d \
LCM of %d and %d = %d \
}
/* Function to find the GCD */
int GCD( int x, int y)
{
while ( x != y )
if ( x > y) x = x - y;
else y = y - x;return(
x );
}
OUTPUT 1
Enter the numbers a and b
25 5
GCD of 25 and 5 = 5
LCM of 25 and 5 = 25
OUTPUT 2
Enter the numbers a and b
7 29
GCD of 7 and 29 = 1
LCM of 7 and 29 = 203
Recursive functions
In many situations it is possible for us to have functions that call itself directly
or indirectly again and again. Such functions are termed as recursive functions and
the process is termed as recursion.
Function1( a )
In general, a recursive function must have two parts: the base case, which
handles a simple input that can be solved without resorting to a recursive call, and the
recursive case which contains one or more recursive calls to the function where the
parameters are in some sense "closer" to the base case than those of the original call.
One very simple example is the mathematical definition of factorial. The
factorial of a number n(written as n!) is n multiplied by n-1, n-2, n-3, and so on.
Some example factorials are
5! = 5 * 4!
=5*4* 3!
=5*4* 3 * 2!
=5*4* 3 * 2 * 1!
=5*4* 3 * 2 * 1 * 0!
= 120
Program 10 : To find the factorial of the given number using recursive function.
#include <stdio.h>
int fact(int ); /* Function prototype */
main( )
{
int n;
else
of %d is = %d \ n, fact( n ));/
}
return( 1 );
else
OUTPUT 2
Enter any nonnegative integer -5
Invalid Input
First, let us define the problem recursively. If we call the sum of the first n
integers Sn, then we have
Si =0 when i = 0 and
= i + Si-1 when i > 0
S5 = 5 + S4
= 5 + 4 + S3
= 5 + 4 + 3 + S2
= 5 + 4 + 3 + 2 + S1
= 5 + 4 + 3 + 2 + 1+ S0
= 5 + 4 + 3 + 2 + 1+ 0
= 15
#include<stdio.h>
int sum( int ); /* Function prototype */
main( )
{
int num;
any number \n
&num);
of %d natural number = %d \ n,sum(num));
}
OUTPUT 2
Enter a number
100
Sum of 100 natural number = 5050
#include <stdio.h>
float power(float , int ); /* Function prototype */
main( )
{
float x;
int n;
Enter x and n values \
&x, &n);
\n%.4f to the power of %d is x, n, power(x,n));
}
/* Function to find the xn */
float power(float a, int b)
{
if( b == 0)
return( 1);
else if(b >0 )
return( a * power ( a, b-1);
else
return ( ( 1/a)* power(a , b+1) );
}
OUTPUT 1
Enter a and b values
23
2.0000 to the power of 3 is = 8.0000
OUTPUT 2
Enter a and b values
2 -3
2.0000 to the power of -3 is =0.1250
OUTPUT 3
Enter a and b values
03
0.0000 to the power of -3 is =0.0000
f3 + f 2 f2 + f 1
f 2 + f1
i.e., f5 = f2 + f 1 + f 2 + f 2 + f 1
= 1 + 0 + 1 + 1 +0
= 3
#include <stdio.h>
int fibo( int );
main( )
{ int i,n;
number of elements in the series \
\nFibonacci numbers\n\
for(i=1;i<=n;i++)
\ /* Function call */
}
/* Function to find fibonacci numbers */
int fibo(int k)
{
if(k ==1)
return(0);
else if(k==2)
return(1);
else
return(fibo(k-1)+fibo(k-2));}
}
NESTING OF FUNCTIONS
Function1 ( a )
We can pass an entire array from one function to another. To pass an entire
array to a function we will have to just pass the name of the array as the actual
argument. When we pass a normal variable other than an array, C makes a copy of
the data and places it in a memory location associated with the receiving variable.
Thus there are two copies of the data, and changing the variable in the receiving
function does not change the original variable.
When you pass an array, we are actually passing the address of the first
location of the array. C does not make a copy of the entire array but merely assigns
the same address area, and thus its data to a second array name. Thus two names
are sharing the same data area. Any changes made inside the called function will
automatically be reflected in the main program or the calling function. The program
below shows how to pass an array as an argument.
Program 15 : To read a set of numbers from the standard input device and to
sort them in ascending order using a function and the technique of selection sort.
#include <stdio.h>
void output(int *, int ); /* Function prototype */
void selection_sort(int *, int ); /* Function prototype */
main( )
{
int a[100];
int i, num;
Array elements \
for(i=0; i<num; i++)
\
output( a, num );
selection_sort(a, num );
\n Sorted array \
output(a, num );
}
/* Function to print array elements */
void output(int b[ ], int n )
{
int i;
for(i=0 ; i<n ; i++)
\
}
/* Function to arrange array elements in ascending order */
void selection_sort(int b[ ], int n)
{
int i, j, min,pos;
The most important function of C is main() function. It is mostly defined with a return type
of int and without parameters :
We can also give command-line arguments in C and C++. Command-line arguments are
given after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{