Chapter 6
Chapter 6
Chapter 6
A function is a group of statements that together perform a task. Every computer program has at
least one function, which is main() and all the most trivial programs can define additional
function.
Execution of program will always begin by carrying out the instructions in main. Additional
function will be sub routine to main. Functions are used to encapsulate a set of operations and
return information to the main program or calling routine. Encapsulation is information or data
hiding. Once a function is written, we need only be concerned with what the function does. That
is , what data it requires and what outputs it produces. The details, "how" the function works,
need not be known. The use of function provides several benefits. First, it makes programs
significantly easier to understand and maintain. The main program can consist of series of
function calls rather than countless lines of code. The second benefit is that well written function
may be reused in multiple programs. The C standard library is an example of reuse of function.
The third benefit of using function is that different programmers working on one large project
can divide the workload by writing different function. Fourth, programs that use function are
easier to design, program, debug and maintain.
Example : In this program function main() calls a function named add(). Function main() passes
two arguments and the function add() returns the sum of passed numbers to function main()
using return statements.
Algorithm
Step 1 : Start
Step 2 : Declare local variables a, b, sum and function add().
Step 3 : Read values of a , b.
Step 4 : Call function add() with arguments a and b.
sum <- add(a, b)
Step 5 : Print sum
Step 6 : End
Flowchart of calling function is as follows. In this example main()is the calling function
Program
#include<stdio.h>
#include<conio.h>
float add(int, float); /* function delaration */
void main() /* function prototype */
{
int a;
float b, sum;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
sum = add(a, b); /* function call giving arguments a and b, where a and b are actual */
/*arguments (parameters) */
printf("\nThe sum = %f", sum);
getch();
}
float add( int p, float q) /* function definition starts from this line, this first line is function */
/* declaration, where p and q are formal arguments (parameters) */
{
float s;
s=p+q;
return s;
}
Passing arguments
Providing values to the formal arguments of called function through the actual arguments of the
calling function is called passing arguments.
(Note : The function which calls other function is called calling function and the function which
is called by other function is called the called function. In above example add function is called
function and main function is calling function.)
Return statements
A function may or may not send back ay value to the calling function. If it does, it is through
return statements. While it is possible to pass to the called function any number of arguments but
the called function can only return on value per call, at the most. The return statements can take
one of the following :
return; or return (expression);
Plain return does not return any value, acts as closing brace of the function
When return is encountered, the control is immediately passed back to calling function.
Example : if (error)
return;
If return(expression); is encountered, it returns value of expression to calling function. In above
example: return s; return the value of s.
It is possible for a function to have multiple return statements.
int calculate (char ch)
{
switch(ch)
{
case '+' :
return 1;
Function call
It is an inactive part of the program which comes in to life when a call is made to the function. A
function call is specified by the function name followed by the values of parameters enclosed
within parenthesis, terminated by a semicolon. In above example, add(a , b); is the function call
and a and b are the parameters.
2. User defined function : These are the function declared and defined by the user according to
their program requirements. These functions are available only for the current program in which
it is defined. It can be used by the program in which it is defined as well as the related files of the
program. But it can't be used as library function in all program. When a function is called in the
block or any other function, the execution control will jump to the called function; it will execute
the statements in the function and return back to the called block/function with/without some
values.
#include<stdio.h>
#include<conio.h>
void function_name(){
------------
------------
}
void main(){
function_name();
---------------------
---------------------
}
From above diagram, it is clear how a function call works. It acts like a label, but it returns back
to the calling block once its execution is over.
Benefits of Using Functions
It provides modularity to your program's structure.
It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
In case of large programs with thousands of code lines, debugging and editing becomes
easier if you use functions.
It makes the program more readable and easy to understand.
Flowchart
Program
#include<stdio.h>
#include<conio.h>
void add(int, float);
void main()
{
int a;
float b;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
add(a , b);
getch();
}
Function main() : Main is also a user-defined function except its name, number and type of
arguments. It is starting point of program execution. Each program must have a main function.
Programmers can write statements in body of main to solve any problems. More complex
problems can be divided into small easier chunks. Each small problem can be solved writing
other small functions separately. These all functions are required to be called from the main to
combine the solutions and to get the integrated solution of the complex problem. The required
statements must be written either inside the main or can be called to other function from the
main. The general form of main is
main()
{}
The above statement is sufficient for the execution of the program, through the program does not
do any useful operation.
Scope of variables (Local and global variables) : It determines over what part(s) of the
program a variable is actually available for use (active). On the basis of place of declaration,
variables are categorized as local(internal , automatic) and global(external).
Local
A local variable is always declared inside a function block. In C, a local variable is declared at
the start of a code block. In C++, they can be declared anywhere in the code block prior to their
use. Local variables can be accessed only by the statements written inside a function in which the
local variable are declared. They are secure in a sense that, they cannot be accessed by any other
function of the same program.
Local variable exist till the block of the function is in execution, and thereby destroyed after the
execution exits the block. Local variables lose their content as soon as the execution left the
block in which they are declared.
The reason behind it is that the local variables are stored on the stack unless their special storage
is specified. The stack is dynamic in nature, and the change in memory location leads to the
reason why local variable doesn’t hold their value as soon as the block of a function exists.
Note:
However, there is a way to retain the value of a local variable, by using the ‘static’ modifier.
Global
A global variable is declared outside all the functions present in a program. Unlike local
variables, the global variable can be accessed by any function present in a program. Global
variables are not much reliable as their value can be changed by any function present in the
program.
Global variables remain in existence till the whole program get executed completely. Global
variables retain their values till the program is in execution. The reason is that they are stored on
a fixed region of memory, decided by the compiler.
A Global variable is helpful in situations where multiple functions are accessing the same data.
Using a large number of global variables might be problematic, as there may be unwanted
changes to the value of a global variable.
Example
#include<stdio.h>
#include<conio.h>
int a, b, result;
void main()
{
clrscr();
sum();
sub();
getch();
}
extern variables : The variables that are active and alive throughout the entire program are
known as external variable. Up to now, all the examples have shown an entire program within
one file. This is fine short and simple programs but any large real world program is likely to have
its code distributed among multiple files. There are several practical reasons for organizing a
program into multiple files. First, it allows parts of the program to be developed independently,
possibly by different programmers. This separation also allows independent compiling and
testing of the modules in each file. Second, it allows greater reuse of code. Files containing
related functions can become libraries of routines that can be used in multiple programs. Having
a program distributed in multiple files uses external variables. Within one file, the scope of a
global variable is from its definition to the end of the file. The keyword extern makes it possible
to use a global variable in multiple files. Notice that a variable may only be defined once. It may
be declared multiple times. Remember that a definition creates space or reserves memory, for the
variable. The declaration just informs the compiler that a variable or function exists. The
keyword extern tells the compiler that the variable is defined in another file.
Example
#include<stdio.h>
#include<conio.h>
int g;
extern int g;
void function1();
void function2();
void function3();
void main()
{
int i;
printf("Enter the value of g: ");
scanf("%d", &g);
function1();
function2();
function3();
getch();
}
Recursion in C
Expressing an entity in terms ofitself is called recursion.That is, a function calling itself.
Function - recursive function
Calls - recursive calls
Two important conditions that must be satisfied by any recursive functions are:
Each time a function calls itself and it must be closer to a solution.
There ust be decision criteria for stopping the process.
When a recursive function is called, the function knows to solve only the simplest case.
recursive algorithm
if this is the simplest case
solev it
else
redefine (simplify) the problem using recursion
Termination A conditional statement is included in the body The iteration statement is repeatedly
of the function to force the function to return executed until a certain condition is
without recursion call being executed. reached.
Condition If the function does not converge to some If the control condition in the iteration
condition called (base case), it leads to infinite statement never become false, it leads
recursion. to infinite iteration.
Infinite Infinite recursion can crash the system. Infinite loop uses CPU cycles
Repetition repeatedly.
Stack The stack is used to store the set of new local Does not uses stack.
variables and parameters each time the function
is called.
Overhead Recursion possesses the overhead of repeated No overhead of repeated function call.
function calls.
Size of Code Recursion reduces the size of the code. Iteration makes the code longer.
Advantages of recursion
The code may be much easier to write.
To solve some problem which are naturally recursive such as towers of Hanoi.
Disadvantages of recursion
Recursive functions are generally slower than non-recursive functions.
May require a lot of memory to hold intermediate results on system stack so excessive
recursion may overflow the system stack.
It is difficult to think recursively so one must be very careful when writing recursive
functions.
Q. WAP to find x^y using recursive function where x is float and y are unsigned integers. Use
recursive function.
function body is
float power(float x, unsigned int n)
{
if(n==1)
{
return x;
}
else
{
return (x*power(x,n-1));
}
}
Q. Fibonacci Sequence
#include<stdio.h>
#include<conio.h>
void Fibonacci(unsigned int, unsigned int, unsigned int);
void main()
{
unsigned int n;
printf("Enter number of terms of Fibonacci sequence : ");
scanf("%u",&n);
Fibonacci(0, 1, n);
getch();
}
void Fibonacci(unsigned int first, unsigned int second, unsigned int x)
{
if(x!=0)
{
printf("%u\n",first);
Fibonacci(second, second+first, x-1);
}
}
Q. GCD (HCF)
function definition
int gcdhcf(int x, int y)
{
if(y!=0)
return gcdhcf(y,x%y);
Q. WAP to read an integer number and add the individual digits contained in it until the final
sum is a single digit. [2071]
example: if entered number is n=2175698
then 2+1+7+5+6+9+8=38
again 3+8=11
again 1+1=2 is output.
#include<stdio.h>
#include<conio.h>
int sum_again(long int);
void main()
{
long int n,s;
printf("Enter a positive integer : ");
scanf("%ld", &n);
s=sum(n);
printf("Final sum=%d\n",s);
getch();
}
int sum(long int n)
{
int p;
if(n/10==n)
Q. Write a program in C to find out whether the nth term of Fibonacci series is a prime number
or not. Read the value of n from the user and display the result in the main function. Use separate
user-defined functions to generate the nth Fibonacci term and to check whether a number is
prime or not. [2074]
#include<stdio.h>
#include<conio.h>
int isPrime(int);
int fibo(int);
int main()
{
int n,p,f;
printf("Enter no of terms for Fibonacci series:");
scanf("%d",&n);
f=fibo(n);
p=isPrime(f);
if(p==2)
{
printf("Prime and number : %d", f);
}
Q. Write a program to calculate the sum of the series 1+11+111+....+up to N terms using
recursive function. If N is read as 5, the series is: 1+11+111+1111+11111. [2072]
#include<stdio.h>
#include<conio.h>
int sumseries(int , int);
int arms(int p)
{
int rem;
rem=p%10;
if(p==0)
{
return 0;
}
else
{
return(rem*rem*rem+arms(p/10));
}
}
Q. Briefly explain the passing by value and passing by reference in function with example. [2072]
Q. What is the meaning of function prototyping? [2072]
Q. Write a program to display Armstrong numbers between the range entered by a user and also display
their counts. You must use a function to check for Armstrong number and display them from main.
[2071] (Also print prime, perfect, palindrome etc.)
#include<stdio.h>
#include<conio.h>
int printArmstrong(int);
int main()
{
int n1,n2,i,Arms,c=0;
printf("Enter n1 and n2 : ");
scanf("%d %d",&n1,&n2);
for(i=n1;i<=n2;i++)
{
Arms=printArmstrong(i);
if(Arms==i)
{
c++;
printf("%d\n",i);
}
}
getch();
return 0;