Unit 4
Unit 4
(Unit-4)
K. Subhashini Spurjeon
Department of Information Technology, BIT, Durg
FUNCTIONS
1. Monolithic Programming indicates the program which contains a single function for the
large program.
2. Modular programming help the programmer to divide the whole program into different
modules and each module is separately developed and tested. Then the linker will link all
these modules to form the complete program.
3. On the other hand monolithic programming will not divide the program and it is a single
thread of execution. When the program size increases it leads inconvenience and difficult to
maintain.
Disadvantages of monolithic programming: 1. Difficult to check error on large
programs. 2. Difficult to maintain. 3. Code can be specific to a particular problem. i.e. it can
not be reused.
Advantage of modular programming: 1. Modular program are easier to code and debug.
2. Reduces the programming size. 3. Code can be reused in other programs. 4. Problem can be
isolated to specific module so easier to find the error and correct it.
FUNCTION:
A function is a group or block of statements that together perform a task. These groups have
been given a name which is kown as function's name. Function allows you to break your
program down into manageable pieces and reuse your code. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
function Syntax :
OR
return_type function_name
(type1 type2);
3.Calling function need information about called function .If called function is place before
calling function then the declaration is not needed.
Function Definition:
1. It consists of actual code of a function . It is
made-up of two parts
b)Function coding
Syntax:
{
local variable;
statements ;
return
(expression);
}
2. Function definition can be placed any where in the program but generally placed after the
main function .
3. Local variable declared inside the function is local to that function. It cannot be used
anywhere in the program and its existence is only within the function.
5. Return type denote the type of value that function will return and return type is
optional if omitted it is assumed to be integer by default.
The C standard library is a standardized collection of header files and library routines used to
implement common operations, such as input/output and character string handling. e.g. to
write/display the output on standard output stream we use printf() and to read/take the input
from standard input stream we use scanf() function.
1. Function makes the lengthy and complex program easy and in short forms. It means
large program can be sub-divided into self-contained and convenient small modules
having unique name.
2. The length of source program can be reduced by using function by using it at
different places in the program according to the user's requirement.
3. By using function, memory space can be properly utilized. Also less
memory is required to run program if function is used.
4. They also allow more than one person to work on one program.
5. Function increases the execution speed of the program and makes the
programming simple.
8. Debugging (removing error) becomes very easier and fast using the function
sub-programming.
11. User can build a customized library of different functions used in daily routine having
specific goal and link with the main program similar to the library functions.
<complex.
2 A set of functions for manipulating complex numbers.
h>
floating-point library.
These limits specify that a variable cannot store any value beyond these
limits, for example-
4 <limits.h>
The math.h header defines various mathematical functions and one macro.
5 <math.h>
All the Functions
in this library take double as an argument and return double as the result.
The stdio.h header defines three variable types, several macros, and
various
6 <stdio.h>
Category of functions:
We have some other type of functions where the arguments and return value may be present or
absent. Such functions can be categorized into:
Here, the called functions does not receive any data from the calling function and, it
does not return any data back to the calling function. Hence, there is no data transfer
between the calling function and the called function.
Example:
This program illustrates the function with no arguments and no return value.
# include <stdio.h>
main ()
{
read_name ();
}
void read_name () /*no return value */
{
char name [10];
printf (“Enter your name: ”);
scanf (“%s”, name);
printf (“\nYour name is %s: ”, name);
}
Output:
Here, the called function receives the data from the calling function. The arguments
and parameters should match in number, data type and order. But, the called function
does not return and value back to the calling function. Instead, it prints the data in its
scope only. It is one-way data communication between the calling function and the
called function.
Example:
This program illustrates the function with arguments but has no return value.
#include <stdio.h>
main()
{
int x, y;
printf (“Enter the values of x and y: ”);
scanf (“%d %d”, &x, &y);
maximum (x, y);
}
Output:
Here, the called function does not receive any data from the calling function. It
manages with its local data to carry out the specified task. However, after the specified
processing the called function returns the computed data to the calling function. It is
also a one-way data communication between the calling function and the called
function.
Example:
This program illustrates the function with no arguments but has a return value.
#include <stdio.h>
main ()
{
float sum;
sum = total();
printf (“Sum = %f\n”, sum);
}
float total ()
{
float x, y;
x = 20.0;
y = 10.0;
return (x + y);
}
Output:
Sum = 30.000000
When a function has arguments it receives data from the calling function and does
some process and then returns the result to the called function. In this way the main()
function will have control over the function.
Example:
/* program to find the sum of first N natural numbers */
#include <stdio.h>
int sum (int x); /* function prototype*/
void main ()
{
int n;
printf (“Enter the limit: ”);
scanf (“%d”, &n);
printf (“sum of first %d natural numbers is: %d”, n, sum(n));
}
int sum(int x)
{
int i, result = 0
for (i=1; i <= x; i++)
result += i;
return (result);
}
Output:
The main() is the calling function which calls the function sum(). The function sum()
receives a single argument. Note that the called function (i.e., sum ()) receives its data
from the calling function (i.e., main()). The return statement is employed in this
function to return the sum of the n natural numbers entered from the standard input
device and the result is displayed from the main() function to the standard output
device. Note that int is used before the function name sum() instead of void since it
returns the value of type int to the called function.
● The function name in the function call and the function definition must be
same.
● The type, number, and sequence of actual and formal arguments must be
same.
Nested Functions:
We have seen programs using functions called only from the main() function. But there
are situations, where functions other than main() can call any other function(s) used in
the program. This process is referred as nested functions.
Example:
#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function 1”);
func2();
printf (“\n Again inside function 1”);
}
void func2()
{
printf (“\n Inside function 2”);
}
Output:
Uses two functions func1() and func2() other than the main() function. The main() function
calls the function func1() and the function func1() calls the function func2().
Local and Global Variables:
Both the calling function and called function are using their own variables. The
existence of these variables is restricted to the calling function or to the called
functions. This is known as scope of the variables. Based on this scope the variables
can be classified into:
Variables whose existence is known only to the main program or functions are called
local variables. On the other hand, variables whose existence is known to both main()
as well as other functions are called global variables. Local variables are declared within
the main program or a function. But, the global variables are declared outside the
main() and other functions.
The following program illustrates the concept of local and global variables:
Example:
#include <stdio.h>
int i = 10; /* global variable declaration */
main()
{
int j; /* local variable declaration */
printf (“i = %d\n”, i);
j = value (i);
printf (“j = %d\n”, j);
}
int value (int i) /* function to compute value */
{
int k; /* local variable declaration */
k = i +10
return (k);
}
Output:
i = 10
j = 20
Actual Arguments:
1. Arguments which are mentioned in the function in the function call are known as calling
function.
2. These are the values which are actual arguments called to the function.
It can be written as constant , function expression on any function call which return a value .
Formal Arguments:
1. Arguments which are mentioned in function definition are called dummy or formal
argument.
2. These arguments are used to just hold the value that is sent by calling function.
3. Formal arguments are like other local variables of the function which are created when
function call starts and destroyed when end function.
a) Formal arguments are declared within the ( ) where as local variables are
declared at beginning.
b) Formal arguments are automatically initialized when a value of actual argument
is passed.
c) Where other local variables are assigned variable through the statement inside
the function body.
Note: Order, number and type of actual argument in the function call should be matched with the
order , number and type of formal arguments in the function definition .
1.Call by value
2.Call by reference
Call by Value:
The call-by-value method copies the value of an argument into the formal parameter of the
function. Therefore, changes made by the function to the parameters have no effect on the
variables used to call it.
Example:
# include <stdio.h>
void swap (int x, int y); /* function prototype */
main ()
{
int x, y;
x = 10;
y = 20;
swap (x, y); /* values passed */
}
temp = a;
a = b;
b = temp;
printf (“%d %d\n”, a, b);
}
Call by Reference:
The call by reference method copies the address of an argument into the formal
parameter. Inside the function, this address is used to access the argument used in the
call. In this way, changes made to the parameter affect the variable used in the call to
the function.
Example:
# include <stdio.h>
void swap (int *x, int *y); /* function prototype */
main ()
{
int x, y; x = 10;
y = 20;
swap (&x, &y); /* addresses passed */
printf (“%d %d\n”, x, y);
}
temp = *a;
*a = *b;
*b = temp;
}
PASSING ARRAYS TO FUNCTIONS
One-Dimensional Arrays
If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similarly, you can pass multi-dimensional arrays as formal parameters.
Way-1
Way-2
Way-3
In the above example, we have passed the address of each array element one by one using a for
loop in C. However you can also pass an entire array to a function like this:
RECURSION
Recursion is a process in which a problem is defined in terms of itself. In ‘C’ it is possible to call a
function from itself. Functions that call themselves are known as recursive functions, i.e. a
statement within the body of a function calls the same function. Recursion is often termed as
‘Circular Definition’. Thus recursion is the process of defining something in terms of itself. To
implement recursion technique in programming, a function should be capable of calling itself.
Example:
Here the function fun1() is calling itself inside its own function body, so fun1() is a recursive
function. When main() calls fun1(), the code of fun1() will be executed and since there is a call to
fun1() insidefun1(), again fun1() will be executed. It looks like the above program will run up to
infinite times but generally a terminating condition is written inside the recursive functions which
end this recursion. The following program (which is used to print all the numbers starting from the
given number to 1 with successive decrement by 1) illustrates this:
(i). Identify the Non-Recursive part(base case) of the problem and its solution(Part of
the problem whose solution can be achieved without recursion).
(ii). Identify the Recursive part(general case) of the problem(Part of the problem where
recursive call will be made).
Identification of Non-Recursive part of the problem is mandatory because without it the function
will keep on calling itself resulting in infinite recursion.
How control flows in successive recursive calls?
Consider the following program which uses recursive function to compute the factorial of a
number.
In the above program if the value entered by the user is 1 i.e.n=1, then the value of n is copied into
m. Since the value of m is 1 the condition ‘if(m==1)’ is satisfied and hence 1 is returned through
return statement i.e. factorial of 1 is 1.
When the number entered is 2 i.e. n=2, the value of n is copied into m. Then in function fact(), the
condition ‘if(m==1)’ fails so we encounter the statement a=m*fact(m-1); and here we meet
recursion. Since the value of m is 2 the expression (m*fact(m-1)) is evaluated to (2*fact(1)) and the
result is stored in a(factorial of a). Since value returned by fact(1) is 1 so the above expression
reduced to (2*1) or simply 2. Thus the expression m*fact(m-1) is evaluated to 2 and stored in a and
returned to main(). Where it will print ‘Factorial of 2 is 2’.
In the above program if n=4 then main() will call fact(4) and fact(4) will send back the computed
value i.e. f to main(). But before sending back to main() fact(4) will call fact(4-1) i.e. fact(3) and
wait for a value to be returned by fact(3). Similarly fact(3) will call fact(2) and so on. This series of
calls continues until m becomes 1 and fact(1) is called, which returns a value which is so called as
termination condition. So we can now say what happened for n=4 is as follows
All recursive functions work in two phases- winding phase and unwinding phase.
Winding phase starts when the recursive function is called for the first time, and ends when the
termination condition becomes true in a call i.e. no more recursive call is required. In this phase a
function calls itself and no return statements are executed.
After winding phase unwinding phase starts and all the recursive function calls start returning in
reverse order till the first instance of function returns. In this phase the control returns through each
instance of the function.
We came to know that recursive calls execute like normal function calls, so there is no extra
technique to implement recursion. All function calls(Whether Recursive or Non-Recursive) are
implemented through run time stack. Stack is a Last In First Out(LIFO) data structure. This means
that the last item to be stored on the stack(PUSH Operation) is the first one which will be
deleted(POP Operation) from the stack. Stack stores Activation Record(AR) of function during run
time. Here we will take the example of function fact() in the previous recursive program to find
factorial of a number.
Now will see how the run time stack changes during the evaluation of factorial of 3.
The following steps will reveal how the above stack contents were expressed:
First main() is called, so PUSH AR of main() into the stack. Then main() calls fact(3) so PUSH AR
of fact(3). Now fact(3) calls fact(2) so PUSH AR of fact(2) into the stack. Likewise PUSH AR of
fact(1). After the above when fact(1) is completed, POP AR of fact(1), Similarly after completion
of a specific function POP its corresponding AR. So when main() is completed POP AR of main().
Now stack is empty.
In the winding phase the stack content increases as new Activation Records(AR) are created and
pushed into the stack for each invocation of the function. In the unwinding phase the Activation
Records are popped from the stack in LIFO order till the original call returns.
Examples of Recursion
Q1. Write a program using recursion to find the summation of numbers from 1 to n.
Ans: We can say ‘sum of numbers from 1 to n can be represented as sum of numbers from 1 to n- 1
plus n’ i.e.
= n+ n-1 + n-2 + +1
#include<stdio.h>
void main()
int n,k;
printf(“Enter a number”);
scanf(“%d”,&n);
k=sum(n);
}
int sum(int a)
int s;
if(a==1)
return (a);
else
s;
Output:
Enter a number 5
15
Q2. Write a program using recursion to find power of a number i.e. nm.
Ans: We can write,
nm = n*nm-1
=n*n*nm-2
#include<stdio.h>
int power(int,int);
void main()
int n,m,k;
scanf(“%d%d”,&n,&m);
k=power(n,m);
if(y==0)
{
return 1;
else
{
return(x*power(x,y-1));
Output:
Enter the value of n and m
3
5
The value of nm for n=3 and m=5 is 243
Ans: The GCD or HCF (Highest Common Factor) of two integers is the greatest integer that
divides both the integers with remainder equals to zero. This can be illustrated by Euclid’s
remainder Algorithm which states that GCD of two numbers say x and y i.e.
GCD(x, y) = x if y is 0
#include<stdio.h>
int GCD(int,int);
void main()
{
int a,b,gcd;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
gcd=GCD(a,b);
printf(“GCD of %d and %d is %d”,a,b,gcd);
}
int GCD(int x, int y)
{
if(y==0)
return x;
else
return GCD(y,x%y);
}
Output:
Enter two numbers 21
35
GCD of 21 and 35 is 7
Ans: Fibonacci series is a sequence of integers in which the first two integers are 1 and from third
integer onwards each integer is the sum of previous two integers of the sequence i.e.
}
void main()
{
int term,i;
clrscr();
Output:
Enter the number of terms of Fibonacci Series which is going to be printed 6
1 1 2 3 5 8 13 Ackermann Function
Last Updated : 11 Jun, 2021
Ackermann Function
In computability theory, the Ackermann function, named after Wilhelm Ackermann, is one of
the simplest and earliest-discovered examples of a total computable function that is not
primitive recursive. All primitive recursive functions are total and computable, but the
Ackermann function illustrates that not all total computable functions are primitive recursive.
It’s a function with two arguments each of which can be assigned any non-negative integer.
Ackermann function is defined as:
Solve A(1, 2)?
Answer:
Given problem is A(1, 2)
Here m = 1, n = 2 e.g m > 0 and n > 0
Hence applying third condition of Ackermann function
A(1, 2) = A(0, A(1, 1)) ———- (1)
Now, Let’s find A(1, 1) by applying third condition of Ackermann function
A(1, 1) = A(0, A(1, 0)) ———- (2)
Now, Let’s find A(1, 0) by applying second condition of Ackermann function
A(1, 0) = A(0, 1) ———- (3)
Now, Let’s find A(0, 1) by applying first condition of Ackermann function
A(0, 1) = 1 + 1 = 2
Now put this value in equation 3
Hence A(1, 0) = 2
Now put this value in equation 2
A(1, 1) = A(0, 2) ———- (4)
Now, Let’s find A(0, 2) by applying first condition of Ackermann function
A(0, 2) = 2 + 1 = 3
Now put this value in equation 4
Hence A(1, 1) = 3
Now put this value in equation 1
A(1, 2) = A(0, 3) ———- (5)
Now, Let’s find A(0, 3) by applying first condition of Ackermann function
A(0, 3) = 3 + 1 = 4
Now put this value in equation 5
Hence A(1, 2) = 4
So, A (1, 2) = 4