Chapter 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

User Defined Function

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

Compiled By : Deepak Kr. Singh, Pradip Khanal


Algorithm of called function [add()]

Step 1 : Declare local variables x, y, s


Step 2 : Assign a to x and b to y
Step 3 : s <- a+b
Step 4 : Return s
Flowchart for called 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;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Output : Enter values of a and b : 5, 20
The sum = 25.000000

Concept associated with functions


 Function declaration or prototype
 Function definition (function declaration and function body)
 Passing arguments
 Return statements
 Function call
 Combination of function declaration and function definition

Function declaration or prototype


A function tells the compiler about
 Function name
 Type of values to be returned (optional, default return type is integer)
 The number of arguments that must be supplied in a call to the function
 The type of arguments (parameters) that must be supplied in a call to the function.
When a function call is encountered, the compiler checks the function call with its declaration so
that correct arguments types are used.

Syntax : return_type function_name (parameters_list);

example : int max (int , int);


float add ( int, float); are function prototype

Function definition (function declarator and function body)


The general form of function definition in C programming language is :
Syntax : return_type function_name (type1 arg1, type2 arg2, type3 arg3, ............, type n arg n)
{
/* body of function */
}
A function in C consists of function header/declarator and function body. Here are all parts.
 Return_type : A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
 Function_name : This is the actual name of the function. The function nameand the
parameter list together constitute the function signature.
 Parameter : A parameter is like a placeholder. When a function is involved, you pass a
value to the parameter. This value is referred to as actual parameter or arguments. The

Compiled By : Deepak Kr. Singh, Pradip Khanal


parameter list refers to the type, order and number of parameters of a function.
Parameters are optional, that is, a function may contain no parameters.
 Function_body : The function body contains a collections of statements that define what
the function does.
Example
int max (int num1, int num2){
int result; /* local variable declaration */
if(num1>num2)
{result = num1;}
else
{result = num2;}
return result;
}

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;

Compiled By : Deepak Kr. Singh, Pradip Khanal


case '-' :
return 2;
case '*' :
return 3;
case '/' :
return 4;
default :
return 0;
}
}
If no value is to be returned, return statement need not be present.

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.

Elimination of function declaration


If the function are defined before they are called , then the declaration is unnecessary.
Example : This example shows the combination of function declaration and definition.
#include<stdio.h>
#include<conio.h>
float add(int p, int q)
{
float s;
s=p+q;
return s;
}
void main()
{
int a;
float b, sum;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
sum=add(a , b);
printf("\nThe sum = %f",sum);
getch();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Categories of function
In C, we have two types of function
1. Library function : Library function are the inbuilt function in C. The most commonly used
functionalities like getting the input from the user, displaying the output on the screen,
comparing any two string, copying two string values, allocating the memory etc are already
coded into different function in C and placed in the libraries. These function can be called
whenever required in our program.
Some examples of library functions are printf(), main(), strcpy(), strcmp((), strlen(), malloc() etc.
These library function are again categorized based on their usage and functionality and placed in
different files. These files are saved with '.h' extensions indicating header files. These header
files are added to our program by using a preprocessor directive called '#include'.

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.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Categories of user defined function
Depending on whether arguments are present or not and whether a value is returnedor not, user
defined functions are categorized as follows:
a) Functions with arguments and return value
#include<stdio.h>
#include<conio.h>
float add(int, float);
void main()
{
int a;
float b, sum;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
sum=add(a , b);
printf("\nThe sum = %f",sum);
getch();
}
float add(int p, int q)
{
float s;
s=p+q;
return s;
}
Above example where function add() falls in this category. It takes two arguments a and b from
the calling function main() and it returns the value of sum to the calling function.

b) Functions with arguments and no return value


In this case the called function takes arguments from the calling function but don't return the
value to the calling function. The function displays the result itself. So, return type is void and
the return statement is not required in the called function.
Example
Algorithm of calling function
Step 1 : Start
Step 2 : Declare local variables a, b and function add()
Step 3 : Read values of variables a, b
Step 4 : Call function add() with arguments a and b i.e. add(a , b)
Step 5 : Stop

Compiled By : Deepak Kr. Singh, Pradip Khanal


Flowchart

Algorithm of called function (here, add())


Step 1 : Declare local variables x, y, s
Step 2 : Assign a to x and b to y
Step 3 : s <- x+y
Step 4 : Print value stored at variable s

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();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


void add(int x, float y)
{
float s;
s=x+y;
printf("\nSum=%f",s);
}

c) Function with no arguments and no return value


In this case, void return type, no arguments, no return statements, function() reads the value of
parameters itself and display the result i.e. value of result from the function body.
The main() function only calls the function() and all other activities are done inside the called
function body.
Program
#include<stdio.h>
#include<conio.h>
void add();
void main()
{
add();
getch();
}
void add()
{
int a;
float b, sum;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
sum=a+b;
printf("\nThe sum = %f", sum);
}

d) Functions with no arguments and return value


Program
#include<stdio.h>
#include<conio.h>
float add();
void main()

Compiled By : Deepak Kr. Singh, Pradip Khanal


{
float x;
x=add();
printf("\nThe sum = %f", x);
getch();
}
float add()
{
int a;
float b;
printf("Enter values of a and b : ");
scanf("%d%f", &a, &b);
return a+b;
}

Call by value and Call by reference


Call by value : Value of actual parameter is passed. Original value of passed variable is not
modified.
Example : #include<stdio.h>
#include<conio.h>
void update(int i)
{
i=i+100; /* i=1100 */
}
int main()
{
int j=1000;
printf("Before calling function, j=%d\n", j);
update(j);
printf("After calling function, j=%d", j);
getch();
return 0;
}
Output: Before calling function, j=1000
After calling function, j=1000
Q. Swapping of two numbers
#include<stdio.h>

Compiled By : Deepak Kr. Singh, Pradip Khanal


#include<conio.h>
void change(int, int);
void main()
{
int x, y;
printf("Enter x and y: ");
scanf("%d%d", &x, &y);
printf("Before exchange, x=%d and y=%d", x, y);
change(x , y);
printf("\nAfter exchange, x=%d and y=%d", x, y);
getch();
}
void change(int p, int q)
{
int t;
t=p;
p=q;
q=t;
}
Output: Enter a and y: 10 20
Before exchange, x=10 and y=20
After exchange, x=10 and y=20
In above example, values of two operands are passed from main to the change function. Change
function swaps the values of local variables p and q which are used to copy the values sent by the
main(). But it is required to swap the values of x and y. In passing by value method, any change
on p does not reflect to x. Similarly, q to y. Return statement can't return more than one values at
a time. This is the main disadvantage of passing by value method. The main advantage of this
method is that the original value of the variable remains unchanged after the function call. The
sample output shows the values of x and y, which are same before and after function call. How to
swap the values of x and y? It can be done using passing by reference.
Call by reference : Address of the variable is passed. Value of the passed variable is modified.
Example : #include<stdio.h>
#include<conio.h>
void change (int *i)
{
*i +=100;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


int main()
{
int j=1000;
printf("Before calling function, j=%d\n", j);
change(&j);
printf("After calling function, j=%d", j);
getch();
return 0;}
Output: Before calling function, j=1000
After calling function, j=1100
// here int *i=address of j where *i means value at address of j. //
Q. Swapping of two numbers
#include<stdio.h>
#include<conio.h>
void swap (int *, int *);
void main()
{
int x =10, y=20;
printf("Before exchange, x=%d and y=%d", x, y);
swap(&x, &y);
printf("\nAfter exchange, x=%d and y=%d", x, y);
getch();
}
void swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;}
Output : Before exchange, x=10 and y=20
After exchange, x=20 and y=10
In example given above, address of the variable is passed to the called function. Here addresses
of x and y are passed to the function swap. These addresses are copied to p and q respectively.
Any operation done inside the swap is actually done on the memory location pointed by the
address. Thus, swapping done on *p and *q means swapping done on x and y. Thus the effect is
reflected to the calling function (main) though operations are done inside called (swap) function.
The advantages of this method is that we can carry out the effect of returning more than one
values from called function to calling function (but not actually return). The main disadvantage

Compiled By : Deepak Kr. Singh, Pradip Khanal


of this method is the original value of the passed variables does not remain the same after the
function call.

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.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, sum; //Here a , b and sum are local variables.
clrscr();
printf("Enter any two integer value : ");
scanf("%d%d", &a, &b);
sum=a+b;
printf("\nSum of two integers %d and %d is %d", a, b, sum);
getch();
}

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();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


sum()
{
printf("Enter two numbers to find their sum : ");
scanf("%d%d", &a, &b);
result = a + b;
printf("\nThe sum is %d", result);
return 0;
}
sub()
{
printf("Enter two numbers : ");
scanf("%d%d", &a, &b);
result = a - b;
printf("\nThe difference between two numbers is %d", result);
return 0;
}

Here a, b and result are global variables.


Basis For comparison Local variable Global variable
Declaration Variables are declared inside a Variables are declared outside
function. any function
Scope Within a function, inside Throughout the program
which they are declared
Access Accessed only by the Accessed by any statement in
statements, inside a function the entire program.
in which they are declared.
Life Created when the function Remain in existence for the
block is entered and destroyed entire time your program is
upon exit. executing.
Storage Local variables are stored on Stored on a fixed location
the stack, unless specified. decided by a compiler.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Key Difference Between Local and Global Variable.
 Local Variables are called ‘local’ because they are only known to the statements written
in a function inside which they are declared and not known to any other function present
outside that function block. In the case of global variable they are known to each and
every function present in a program; hence, they are called ‘global’.
 Global variables retain their value till the program is in the execution phase, as they are
stored at a fixed location decided by the compiler. Local variables are stored on the stack;
hence, they do not retain their value as ‘stack’ is dynamic in nature, but the compiler can
be directed to retain their value, by using the ‘static’ modifier.
 If a global and a local variable are declared with the same name then, all the statements of
a code block in which local variable is declared will refer only to a local variable and will
cause no effect to a global variable.
 A local variable is destroyed when the control of the program exit out of the block in
which local variable is declared. However, a global variable is destroyed when the entire
program is terminated.
Extent of Variables(lifetime , longevity)
The time period during which memory is associated with a variable is called extent of variable.
The lifetime of a variable is categorized by its storage classes. The storage class of a variable
indicates the allocation of storage space to the variable. The storage classes in C are :
 auto variables
 register variables
 static variables
 extern variables
auto variables : All variables declared within functions are auto by default. Variables declared
auto can only be accessed within the function or nested block within they are declared. They are
created when the control is entered into the functions and destroyed when the control is exited
from the function. The variables declared inside a function without storage class specification is
auto variable by default. The auto variables can be declared as :
Example: auto int a;
auto float b;
register variables : C allows the use of the prefix register in primitive variable declarations.
Such variables are register variables. They are stored in the registers of the microprocessor. The
number of variables, which can be declared register, are limited. A program that uses register
variables executes faster as compared to the similar program without register variables. Loop
indices, to be accessed more frequently, can be declared as register variables.
Example : #include<stdio.h>
#include<conio.h>
void main()

Compiled By : Deepak Kr. Singh, Pradip Khanal


{
register int i;
char name[100];
printf("Enter a string: ");
gets(name);
printf("The reverse of the string is : ");
for(i=strlen(name)-1;i>=0;i--){
printf("%c",name[i]);}
getch();
}
Output: Enter a string: advanced college of engineering and management
The reverse of the string is : tnemeganam dna gnireenigne fo egelloc decnavda
static variables : The value of static variables persists until the end of the program. A variable
can be declared static using the keyboard static like static int p; Static variable may be internal or
external type, depending on the place of declaration. Those static variables which are declared
inside functions are called internal static variables. They are similar to auto variables except that
they remain in existence (alive) throughout the remainder of the program. The static variables
can be initialized only once. The external static variables must be declared outside of all the
functions and are available to all the function in that program.
Example
#include<stdio.h>
#include<conio.h>
void staticdemo();
void main()
{
staticdemo(); // loop can be used to call staticdemo() five times //
staticdemo();
staticdemo();
staticdemo();
staticdemo();
getch();
}
void staticdemo()
{
static int p=150;
p=p+10;
printf("p=%d\n",p);
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Output:
p=160
p=170
p=180
p=190
p=200

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();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


void function1()
{
printf("\nIn MFILE1 and function1 %d", g+1);
}
//extern int g;
void function2()
{
printf("\nIn MFILE2 and function2 %d", g+2);
}
void function3()
{
printf("\nIn MFILE3 and function3 %d", g+3);
}
Output:
Enter the value of g: 4
In MFILE1 and function1 5
In MFILE2 and function2 6
In MFILE3 and function3 7
Summary
Storage Classes Place Default Value Scope Lifetime
Auto RAM garbage value Local Till the control remains within the block
in which the variable is defined
Extern RAM zero global Value of the variable persists between
different function calls
Static RAM zero local Till the control remains within the block
in which the variable is defined. If it is
defined globally it is visible to all the
functions.
register Register garbage value local As long as the program execution does not
come to the end

Compiled By : Deepak Kr. Singh, Pradip Khanal


Stack
 It is a data structure that works on the principle of last in first out (LIFO). This means that
the last item put on the stack is the first item that can be taken out, like a physical stack of
plates.
 The process of storing data in stack is called push and retrieving data from stack is called
pop.
 In recursive calls, the function should push the values of its local variables and formal
arguments onto stack upon entry and pop values of these variables and arguments on
completion of execution.

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

Compiled By : Deepak Kr. Singh, Pradip Khanal


Basic steps of recursive programs
 Define base and recursive case(s).
 Initialize the algorithm. Recursive programs often need a seed value to start with. This is
accomplished either by using a parameter passed to the function or by providing a
gateway function that is non recursive but that sets up the seed values for the recursive
calculation.
 Check to see whether the current value(s) being processed match the base case. Isso,
process and return the value else if the value(s) being processed does not match the base
case, then, redefine the solution in terms of a smaller or simpler sub-problem or sub
problems.
 Run the algorithm on the sub-problem.
 Combine the result to find the solution.
 Return the result.
Basis for Recursion Iteration
comparison
Basic The statement in a body of function calls the Allows the set of instructions to be
function itself. repeatedly executed.

Format In recursive function, only termination Iteration includes initialization,


condition (base case) is specified. condition, execution of statement
within loop and update (increments and
decrements) the control variable.

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.

Applied Recursion is always applied to functions. Iteration is applied to iteration


statements or "loops".

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.

Speed Slow in execution. Fast in execution.

Size of Code Recursion reduces the size of the code. Iteration makes the code longer.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Example for recursion
int factorial(int num){
int answer;
if (num==1) {
return 1;
}else{
answer = factorial(num-1) * num; //recursive calling
}
return (answer);
}
Example for iteration
int factorial(int num){
int answer=1; //needs initialization because it may contain a garbage value before its
initialization
for(int t =1; t>num; t++) //iteration
{
answer=answer * (t);
return (answer);
}
}

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));
}
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Q. WAP that takes a unsigned integer number from main and returns sum from 1 to that number
to the main(). Use recursive function.
function body
unsigned int sum(unsigned int n)
{
if(n==1)
{
return 1;
}
else
{
return (n+sum(n-1));
}
}

Q. Sum of sin series using recursive function


#include<stdio.h>
#include<conio.h>
long int fact(int j);
{
if(j==0)
return 1;
else
return (j*fact(j-1));
}
float numerator(float x, int n)
{
if(n==1)
return x;
else
return (x*numerator(x,n-1));
}
float compute(float x, int n, int s)
{
if(n==1)
return x;
else
return (s*numerator(x,n)/fact(n)+compute(x,n-2,-1*s));
}
void main()
{
int n,s;

Compiled By : Deepak Kr. Singh, Pradip Khanal


float x;
printf("\nEnter number of terms:");
scanf("%d",&n);
printf("\nEnter the value of angle in degree: ");
scanf("%f",&x);
x=x*3.14/180;
if(n%2==0)
s=-1;
else
s=1;
printf("Sum of terms:%f",compute(x,2*n-1,s));
getch();
}

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);

Compiled By : Deepak Kr. Singh, Pradip Khanal


else
return x;
}
Q. WAP to display a line of text "Programing is fun" 10 times using recursive function.
#include<stdio.h>
#include<conio.h>
void main()
{
static int i=10;
while(i>=1)
{
printf("\nProgramming is fun");
i--;
main();
}
}

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)

Compiled By : Deepak Kr. Singh, Pradip Khanal


{
return n;
}
else
{
p=sum_again(n);
return (sum(p));
}
}
int sum_again(long int x)
{
if(x==0)
{
return 0;
}
else
{
return(x%10+sum_again(x/10));
}
}

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);
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


else
{
printf("Not prime and number : %d", f);
}
getch();
return 0;
}
int fibo(int n)
{
if(n==1)
{
return 0;
}
else if(n==2)
{
return 1;
}
else
{
return (fibo(n-2)+fibo(n-1));
}
}
int isPrime(int n)
{
int c=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
return c;
}

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);

Compiled By : Deepak Kr. Singh, Pradip Khanal


int main()
{
int n, result;
clrscr();
printf("Enter number:");
scanf("%d",&n);
result=sumseries(n,1);
printf("Sum=%d",result);
getch();
return 0;
}
int sumseries(int p, int currentTerm)
{
int nextTerm;
if(p==1)
{
return currentTerm;
}
nextTerm=10*currentTerm+1;
return currentTerm+sumseries(p-1,nextTerm);
}
Q. Write a program to calculate sum of digits of a given 5-digits number entered by the user
using recursive function. [2072]
#include<stdio.h>
#include<conio.h>
int sumdigit(int);
int main()
{
int n, temp, sum, c=0;
printf("Enter 5 digit number:");
scanf("%d",&n);
temp=n;
while(temp!=0)
{
temp=temp/10;
c++;
}
if(c==5)
{
sum==sumdigit(n);

Compiled By : Deepak Kr. Singh, Pradip Khanal


printf("Sum of digits of %d is %d",n,sum);
}
else
{
printf("\nInvalid input.");
}
getch();
return 0;
}
int sumdigit(int p)
{
if(p==0)
{
return 0;
}
else
{
return (p%10+sumdigit(p/10));
}
}
Q. Differentiate between pass by value and pass by reference. [2073]
Q. Explain the significance of user defined functions with example. [2073]
Q. What are the advantages of using functions? Differentiate between Library functions and User-defined
functions with suitable example. [2073]
Q. Write a program to check whether a given number is Armstrong number or not using recursive
function. [2072] (Also check for prime, strong, perfect, palindrome etc.)
#include<stdio.h>
#include<conio.h>
#include<math.h>
int arms(int);
int main()
{
int num, n;
printf("Enter number:");
scanf("%d", &n);
num=arms(n);
if(num==n)
{
printf("\n%d is Armstrong number",n);
}
else
{

Compiled By : Deepak Kr. Singh, Pradip Khanal


printf("\n%d is not Armstrong number",n);
}
getch();
return 0;
}

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;

Compiled By : Deepak Kr. Singh, Pradip Khanal


}
int printArmstrong(int n)
{
int j,rem,temp,sum=0;
temp=n;
while(temp!=0)
{
rem=temp%10;
sum=sum+rem*rem*rem;
temp=temp/10;
}
if(sum==n)
{
return n;
}
else
{
return 0;
}
}
Q. What do you mean by nested function and recursive function? Give an example of recursive function.
[2071]
Q. Define "function definition" and write the program to find the sum of two numbers using user-defined
functions. [2070]
Q. What do you mean by "call by value and call by reference" along with suitable example. [2070]
Q. Explain how function is defined in C? Differentiate call by value and call by reference. [2070]
Q. Write a program using a function that returns the largest number from an array of numbers that is
passed to the function. [2070]
Q. What is function? Why is it necessary in programming? [2069]
Q. Write a program to find whether a number is prime or not using function. The function should take the
number as argument and return true or false to the main program. [2069]

Compiled By : Deepak Kr. Singh, Pradip Khanal

You might also like