0% found this document useful (0 votes)
19 views37 pages

Unit 5

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views37 pages

Unit 5

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter-5

Functions: Need of Functions, Function Declaration, Definition and Call. Inbuilt functions and User Defined
Functions. Passing arguments to a function, Returning values from a function. Scope of variable, local and global
variable. Storage classes.
Recursive Functions: Need of Recursion, Direct Recursion, Indirect Recursion, Examples of Recursive Programs
– Factorial, Fibonacci series. Recursive Vs Iterative solutions,Disadvantages of Recursion.

Give the brief explanation of below topics.

Aims and Objectives


################
Introduction
################

Functions in C:
The function is a self contained block of statements which performs a coherent task of a
same kind.
C program does not execute the functions directly. It is required to invoke or call that
functions. When a function is called in a program then program control goes to the
function body. Then, it executes the statements which are involved in a function body.
Therefore, it is possible to call function whenever we want to process that functions
statements.
Advantages of functions:
1. Many programs require that a specific function is repeated many times instead of
writing the function code as many timers as it is required we can write it as a single
function and access the same function again and again as many times as it is required.
2. We can avoid writing redundant program code of some instructions again and again.
3. Programs with using functions are compact & easy to understand.
4. Testing and correcting errors is easy because errors are localized and corrected.
5. We can understand the flow of program, and its code easily since the readability is
enhanced while using the functions.
6. A single function written in a program can also be used in other programs also.

Concept of Function
########################

Purpose of function
############################

USING FUNCTIONS
##########################
Function Definition
#######################

Function Calling
############################

Designing Structured Programs


############################

Return Statement
################################

Characteristics of Function
####################

Advantages of Functions
##########################

Types of functions:
There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions

1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by
system. These functions are stored in library files.
Examples:
main()
- The execution of every C program starts from this main.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C.
2. User defined function
C provides programmer to define their own function according to their requirement
known as user defined functions.
Example of how C function works
#include <stdio.h>
void function_name(){
................
................
}
int main(){
...........
...........
function_name();
...........
...........
}
As mentioned earlier, every C program begins from main() and program starts executing
the codes inside main function. When the control of program reaches to function_name()
inside main. The control of program jumps to "void function_name()" and executes the
codes inside it. When, all the codes inside that user defined function is executed, control
of the program jumps to statement just below it. Analyze the figure below for
understanding the concept of function in C.

Remember, the function name is an identifier and should be unique.

Advantages of user defined functions


 User defined functions helps to decompose the large program into small segments
which makes programmer easy to understand, maintain and debug.
 If repeated code occurs in a program. Function can be used to include those codes
and execute when needed by calling that function.
 Programmer working on large project can divide the workload by making
different functions.
Example of user defined function
1. Write a C program to add two integers. Make a function add() to add integers and
display sum in main function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
#include <conio.h>
int add(int a, int b); //function prototype(declaration)
void main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
}
int add(int a,int b) //function declarator
{
int add;
add=a+b;
return add; //return statement of function
}
2. Write a program to find biggest of the two numbers. Make a function bigger() to
perform this and return the biggest value back to the main().

#include <stdio.h>

/* a function taking two double numbers and returning


the larger number of the two */

/* this function will return a double */


double bigger (double n1, double n2)
{
double big;

if (n1>n2)
big = n1;
else
big = n2;

return (big);
}

void main ()
{
double x, y, result;
printf ("Enter a real number: ");
scanf ("%lf", &x);

printf ("Enter a real number: ");


scanf ("%lf", &y);

/* calling the function (2 arguments) */


result = bigger (x,y);

/* printing the report */


printf ("The bigger number is %lf.\n", result);

}
Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler
information about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
Here, in the above example, function prototype is "int add(int a, int b);" which provides
following information to the compiler:
1. name of the function is "add"
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype is not needed, if you write function definition above the main function.
Function call
Control of the program cannot be transferred to user-defined function (function definition)
unless it is called (invoked).

Syntax of function call


function_name(argument(1),....argument(n));
In the above example, function call is made using statement "add(num1,num2);"
Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Function definition has two major components:
1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from
calling function, control of the program is transferred to function declarator or called
function.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no
semicolon at the end of declarator and function declarator is followed by function body.
In above example, " int add(int a,int b)" in line 12 is function declarator.
2. Function body
Function declarator is followed by body of function which is composed of statements.
In above example, line 13-19 represents body of a function.
Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or variable) passed
from a program to the function.
In above example two variable, num1 and num2 are passed to function during function
call and these arguments are accepted by arguments a and b in function definition.

Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument a should be
of int type and b should be of float type in function definition. i.e. type of argument during
function call and function definition should be same.
A function can be called with or without an argument.
Function parameters / Arguments
There are Two types of function parameters. They are
(i)Actual Parameters
The parameters that are mentioned in the function call are said to be actual parameters.
(ii) Formal Parameters
The parameters that are mentioned in the function declaration are said to be formal
parameters.
In the above example, num1 and num2 are Actual Parameters.
Where as a and b are Formal Parameters.

Passing Arguments (or) Passing Parameters


###################
Call-by-Value Vs Call-by-reference
#########################
Pass or Call by Reference
######################

Differences between Call-by-Value and Call-by-reference


######################################

FORMAL PARAMETERS AND ACTUAL PARAMETERS


############################

NESTING OF FUNCTIONS
############

STANDARD/LIBRARY FUNCTIONS
##################################

SCOPE OF VARIABLES
###########

PASSING ARRAYS TO FUNCTIONS


#############

RECURSION VS ITERATION
################
Return Statement
Return statement is used for returning a value from function definition to calling
function.
Syntax of return statement
return (expression);
OR
return;

For example:
return; // returns a garbage value back to the calling function
return a; // returns value of ‘a’ back to the calling function

return(a+b); /* returns the value that is produced after evaluating the expression a+b */
Note that, data type of add is int and also the return type of function is int. The data type
of expression in return statement should also match the return type of function.

The Standard Library Functions and Header files


Some of the "commands" in C are not really "commands" at all but are functions. For
example, we have been using printf and scanf to do input and output, and we have used
rand to generate random numbers - all three are functions.
A list of the most common libraries and a brief description of the most useful functions
they contain follows:
 stdio.h: I/O functions:
o getchar() returns the next character typed on the keyboard.
o putchar() outputs a single character to the screen.
o printf() as previously described
o scanf() as previously described
 string.h: String functions
o strcat() concatenates a copy of str2 to str1
o strcmp() compares two strings
o strcpy() copys contents of str2 to str1
 ctype.h: Character functions
o isdigit() returns non-0 if arg is digit 0 to 9
o isalpha() returns non-0 if arg is a letter of the alphabet
o isalnum() returns non-0 if arg is a letter or digit
o islower() returns non-0 if arg is lowercase letter
o isupper() returns non-0 if arg is uppercase letter
 math.h: Mathematics functions
o acos() returns arc cosine of arg
o asin() returns arc sine of arg
o atan() returns arc tangent of arg
o cos() returns cosine of arg
o exp() returns natural logarithim e
o fabs() returns absolute value of num
o sqrt() returns square root of num
 time.h: Time and Date functions
o time() returns current calender time of system
o difftime() returns difference in secs between two times
o clock() returns number of system clock cycles since program execution
 stdlib.h:Miscellaneous functions
o malloc() provides dynamic memory allocation, covered in future sections
o rand() as already described previously
o srand() used to set the starting point for rand()

User defined functions are classified into 4 types depending on Arguments and their
Return values
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.

1. Function with no arguments and no return value:- When a function has no


arguments it does not receive any 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 affect there is no data transfer between the calling function and the called function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(); /*declaration;*/
clrscr();
sum(); /*calling;*/
getch();
}
void sum() /* definition*/
{
int a,b;
printf("Enter any two values:");
scanf("%d%d",&a,&b);
printf("Sum is %d\n",a+b);
}
2. Functions with arguments and no return value.
In this type the function has some arguments, it receive data from the calling function but
it does not return any value. The calling function does not receive data from the called
function. So there is one way data communication calling function and the called function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(int, int); /*declaration;*/
int a,b;
clrscr();
printf("Enter any two values:"); scanf("%d
%d",&a,&b);
sum(a,b); /*calling;*/
getch();
}
void sum(int x, int y) /* definition*/
{
printf("Sum is %d\n",x+y);
}

Logic of the function with arguments and no return value.

Department of BS&H Page 100


NRI Institute of Technology, Pothavarappadu
3. Functions with arguments and return value.
In this type the function has some arguments. It receives data from the calling function.
Similarly it returns a value. The calling function receive data from the called function. So
it is a two way data communication between the calling function and the called function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int,int);
int a,b,n;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
n=sum(a,b);
printf("Sum is %d",n);
getch();
}
int sum(int x,int y)
{
return x+y;
}

Logic of the function with arguments and return value.


4. Functions with no arguments and returns value.
In this type the function has no arguments. It does not receive data from the callin g
function. But it returns a value the calling function receive data from the called function.
So it is a one way data communication between called function and the calling function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(); /*declaration;*/

Department of BS&H Page 101


NRI Institute of Technology, Pothavarappadu
int s;
clrscr();
s=sum(); /*calling;*/
printf("Sum is %d",s);
getch();
}
int sum() /* definition*/
{
int a,b;
printf("Enter any two values:"); scanf("%d
%d",&a,&b);
return a+b;
}

**Note that the value return by any function when no format is specified is an
integer
Parameter passing mechanisms
Pass By Value
Passing a variable by value makes a copy of the variable before passing it onto a function.
This means that if you try to modify the value inside a function, it will only have the
modified value inside that function. One the function returns, the variable you passed it
will have the same value it had before you passed it into the function.
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf("Swapped values are a = %d and b = %d", x, y);
}

void main()
{

Department of BS&H Page 102


NRI Institute of Technology, Pothavarappadu
int a = 7, b = 4;

printf("Original values are a = %d and b = %d", a, b);


swap(a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}

Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 7 and b = 4
Pass By Reference
There are two instances where a variable is passed by reference:
1. When you modify the value of the passed variable locally and also the value of the
variable in the calling function as well.
2. To avoid making a copy of the variable for efficiency reasons.
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("Swapped values are a = %d and b = %d", *x, *y);
}
void main()
{
int a = 7, b = 4;
printf("Original values are a = %d and b = %d",a,b);
swap(&a, &b);
printf("The values after swap are a = %d and b = %d",a,b);
}

Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 4 and b = 7
Storage Classes:
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used. Storage
class defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer system
where variables are stored as : Memory and CPU Registers.
Functions of storage class :
To determine the location of a variable where it is stored?

Department of BS&H Page 103


NRI Institute of Technology, Pothavarappadu
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
To determine the life of a variable.
Types of Storage Classes :
Storage classes are categorized in 4 (four) types as,
 Automatic Storage Class
 Register Storage Class
 Static Storage Class
 External Storage Class
Automatic Storage Class:
You can go forever without ever declaring a variable automatic, the reason being that all
variables are implicitly automatic. The technical meaning of automatic variable means
that memory will automatically allocated for it by the compiler and will be destroyed
automatically after it is no longer within scope.
Syntax :
auto [data_type] [variable_name];

Example :
auto int a;

1. auto int var = 0;


2. int var = 0;
Are exactly the same.
o Keyword : auto
o Storage Location : Main memory
o Initial Value : Garbage Value
o Life time : Control remains in a block where it is defined.
o Scope : Local to the block in which variable is declared.

Program

#include <stdio.h>
#include <conio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}

Department of BS&H Page 104


NRI Institute of Technology, Pothavarappadu
printf("\n\n\t %d",i);
getch();
}
Output :
20
10

Register Storage Class:


When the calculations are done in CPU, then the values of variables are transferred from
main memory to CPU. Calculations are done and the final result is sent back to main
memory. This leads to slowing down of processes.
Register variables occur in CPU and value of that register variable is stored in a register
within that CPU. Thus, it increases the resultant speed of operations. There is no waste of
time, getting variables from memory and sending it to back again.
It is not applicable for arrays, structures or pointers.
Unary and address of (&) cannot be used with these variables as explicitly or implicitly.
o Keyword : register
o Storage Location : CPU Register
o Initial Value : Garbage
o Life : Local to the block in which variable is declared.
o Scope : Local to the block.
Syntax :
register [data_type] [variable_name];
Example :
register int a;
Program
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
OUTPUT
20
10

Department of BS&H Page 105


NRI Institute of Technology, Pothavarappadu
Static Storage Class :
Static storage class can be used only if we want the value of a variable to persist between
different function calls.
o Keyword : static
o Storage Location : Main memory
o Initial Value : Zero and can be initialized once only.
o Life : depends on function calls and the whole application or program.
o Scope : Local to the block.
Syntax :
static [data_type] [variable_name];
Example :
static int a;
Program
#include<stdio.h>
#include<conio.h>
void Check();
void main()
{
Check();
Check();
Check();
}
void Check()
{
static int c=0;
printf("%d\t",c);
c+=5;
}
Output
0 5 10

Explanation
During first function call, it will display 0. Then, during second function call, variable c
will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second
function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0 0 0

External storage class


External variable can be accessed by any function. They are also known as global
variables. Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is
declared in file 1 and that variable is used in file 2 then, compiler will show error. To

Department of BS&H Page 106


NRI Institute of Technology, Pothavarappadu
solve this

Department of BS&H Page 107


NRI Institute of Technology, Pothavarappadu
problem, keyword extern is used in file 2 to indicate that, the variable specified is global
variable and declared in another file.
o Keyword : extern
o Storage Location : Main memory
o Initial Value : Zero
o Life : Until the program ends.
o Scope : Global to the program.
Syntax :
extern [data_type] [variable_name];
Example :
extern int a;
Program
#include <stdio.h>
void Check();
int a=5; // a is global variable because it is outside every function
int main()
{
a+=4;
Check();
return 0;
}

Void Check ()
{
++a; /* Variable a is not declared in this function but, works in any function as they
are global variable */
printf ("a=%d\n",a);
}
Output
a=10

SCOPE RULES:
1. The scope of a global variable is the entire program file.
2. The scope of a local variable begins at point of declaration and ends at the end of the
block or function in which it is declared.
3. The scope of a formal function argument is its own function.
4. The life time of an auto variable declared in main( ) is the entire program exception
time
,although its scope is only the main function .
5. The life of an auto variable declared in a function ends when the function is exited.
6. A static local variable ,although its scope is limited to its function,its life time extends
till the end of program execution.
7. All variables have visibility in their scope, provided they are not declared again.
8. If a variable is redeclared within its scope again,it loses its visibility in the scope of the
redeclared variable.
Department of BS&H Page 108
NRI Institute of Technology, Pothavarappadu
Type Qualifiers:

Constants:
The Keyword for the constant type qualifier is const.
A constant object is a read-only object,that is , it can only be used as rvalue.A constant
object must be initialized when it is declared because , it cannot be changed later.A
simple constant is shown below.
Example: const double pi=3.1414926;
Const char str[]=”hello”;
Volatile:
The Keyword for the volatile type qualifier is volatile
The volatile qualifier tells the computer that an object value may be changed by
entities other than this program.
Example: volatile int x;
volatile int *ptr;

Restricted: The Keyword for the restricted type qualifier is restrict


The restrict qualifier which is used only with pointers, indicates that the pointer is
only the initial way to access the dereferenced data.
Example: restrict int *ptr;
int a=0;
ptr=&a;

Block Structure :
C is not a block-structured language in the sense of Pascal or similar languages, because
functions may not be defined within other functions. On the other hand, variables can be
defined in a block-structured fashion within a function. Declarations of variables
(including initializations) may follow the left brace that introduces any compound
statement, not just the one that begins a function. Variables declared in this way hide
any identically named variables in outer blocks, and remain in existence until the
matching right brace. For example, in
if (n > 0) {
int i; /* declare a new i */
for (i = 0; i < n; i++)
...
}

Department of BS&H Page 109


NRI Institute of Technology, Pothavarappadu
the scope of the variable i is the ‘‘true’’ branch of the if; this i is unrelated to any i outside
the block. An automatic variable declared and initialized in a block is initialized each time
the block is entered.
Automatic variables, including formal parameters, also hide external variables and
functions of the same name. Given the
declarations
int x;
int y;
f(double x)
{
double y;
}
then within the function f, occurrences of x refer to the parameter, which is a double;
outside f, they refer to the external int.
The same is true of the variable y.

USER DEFINED FUNCTIONS


Need for User Defined Functions
############################

RECURSION
A Function calling itself is called recursion. Any function can call any function including
itself. In this scenario, if it happens to invoke a function by itself, it is recursion. One of
the instructions in the function is a call to the function itself, usually the last statement.
In some ways it is similar to looping. When the result of ‘one time call of a function is the
input for the next time call of the function’, recursion is one of the best ways. For
example, calculating factorial, in which the product of previous digit factorial is the input
for the next digit’s factorial.
Basic elements of Recursion
 A test to stop or continue the recursion
 An end case that terminates the recursion
 A recursive call(s) that continues the recursion

Types of recursion
1) Direct recursion occurs when a method invokes itself, such as when sum calls sum.
Ex: int sum()
{
---------

Department of BS&H Page 110


NRI Institute of Technology, Pothavarappadu
----------
Sum();
}

2) Indirect recursion occurs when a method invokes another method, eventually resulting
in the original method being invoked again.

Department of BS&H Page 111


NRI Institute of Technology, Pothavarappadu
Int sum()
{
---------
---------
Calc();
}

Int calc()
{
-------
Sum();
}
Examples of Recursion
1) Ex : Calculation of factorial
Factorial of n (denoted n!) is a product of integer numbers from 1 to n. For instance, 5! = 1
* 2 * 3 * 4 * 5 = 120.
Recursion is one of techniques to calculate factorial. Indeed, 5! = 4! * 5. To calculate
factorial of n, we should calculate it for (n-1). To calculate factorial of (n-1) algorithm
should find (n-2)! and so on.
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
The above program works as follows,
fact(3) = {if(3= =1) is false thus return 3* fact (2)}
fact(2) = {if(2= =1) is false thus return 2* fact (1)}
fact(1) = {if(1= =1) is true thus return 1}
Calculation of 3! in details

/* Write C programs that use both recursive and non-recursive functions


To find the factorial of a given integer.*/
#include<stdio.h>

Department of BS&H Page 110


NRI Institute of Technology, Pothavarappadu
#include<conio.h>
unsigned int recr_factorial(int n);
unsigned int iter_factorial(int n);
void main()
{
int n,i;
long fact;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
if(n==0)
printf("Factorial of 0 is 1\n");
else
{
printf("Factorial of %d Using Recursive Function is %d\n",n,recr_factorial(n));
printf("Factorial of %d Using Non-Recursive Function is %d\n",n,iter_factorial(n));
}
getch();
}
/* Recursive Function*/
unsigned int recr_factorial(int n) {
return n>=1 ? n * recr_factorial(n-1) : 1;
}
/* Non-Recursive Function*/
unsigned int iter_factorial(int n) {
int accu = 1;
int i;
for(i = 1; i <= n; i++) {
accu *= i;
}
return accu;
}

output:-
Enter the number 6 /* here given 6 as input */

Factorial of 6 using recursive function is 720

Factorial of 6 using non recursive function is 720

2. Example Using Recursion: Fibonacci Series


The Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
begins with 0 and 1 and has the property that each subsequent Fibonacci number is
the sum of the previous two Fibonacci numbers.

Department of BS&H Page 111


NRI Institute of Technology, Pothavarappadu
The Fibonacci series can be defined recursively as follows:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2)

PROGRAM

#include<stdio.h>

int Fibonacci(int);

main()
{
int n, i = 0, c;

scanf("%d",&n);

printf("Fibonacci series\n");

for ( c = 1 ; c <= n ; c++ )


{
printf("%d\n", Fibonacci(i)); i+
+;
}

return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;

Department of BS&H Page 112


NRI Institute of Technology, Pothavarappadu
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

c program to find gcd of given two numbers :


/* Write C programs that use both recursive and non-recursive functions
To find the GCD (greatest common divisor) of two given integers */
#include<stdio.h>
#include<conio.h>
#include<math.h>
unsigned int GcdRecursive(unsigned m, unsigned n);
unsigned int GcdNonRecursive(unsigned p,unsigned q);
void main(void)
{
int a,b;
clrscr();
printf("Enter the two numbers whose GCD is to be found: ");
scanf("%d%d",&a,&b);
printf("GCD of %d and %d Using Recursive Function is %d\n",a,b,GcdRecursive(a,b));
printf("GCD of %d and %d Using Non-Recursive Function is
%d\n",a,b,GcdNonRecursive(a,b));
getch();
}
/* Recursive Function*/
unsigned int GcdRecursive(unsigned m, unsigned n)
{
if(n>m)
return GcdRecursive(n,m);
if(n==0)
return m;
else
return GcdRecursive(n,m%n);
}
/* Non-Recursive Function*/
unsigned int GcdNonRecursive(unsigned p,unsigned q)
{
unsigned remainder;
remainder = p-(p/q*q);
if(remainder==0)
return q;
else
GcdRecursive(q,remainder);
}

Department of BS&H Page 113


NRI Institute of Technology, Pothavarappadu
Write a C program to find the highest common factor using recursion.
#include <stdio.h>
int hcf(int x, int y);
int main(){
int n1,n2;
printf("Enter two numbers to calculate hcf\n");
scanf("%d%d",&n1,&n2);
printf("Highest common factor=%d",hcf(n1,n2));
return 0;
}
int hcf(int x, int y)
{
if(y==0)
return x;
else
return hcf(y,x%y);
}

Write a C program to reverse a sentence using recursive function.


#include <stdio.h>
void Reverse(char c);
int main(){
char c;
printf("Enter sentence to reverse: \n");
Reverse(c);
return 0;
}
void Reverse(char c)
{ scanf("%c",&c);
if(c!='\n')
{ Reverse(c);
printf("%c",c);
}
}

Write a C program to reverse a number entered by user. Make function Reverse() to


reverse the numbers.
#include<stdio.h>
int Reverse(int n);
int main()
{
int num,i;
printf("Enter number to reverse\n");
scanf("%d",&num);

Department of BS&H Page 114


NRI Institute of Technology, Pothavarappadu
printf("Reverse of %d=%d",num,Reverse(num));
return 0;
}
int Reverse(int n)
{
int rem,rev=0; while(n!=0)
{
rem=(n%10);
n=(n/10);
rev=rev*10+rem;
}
return rev;
}

Towers of Hanoi - Problem and solution


The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a
number of disks of different sizes which can slide onto any rod. The puzzle starts with the
disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus
making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the
following rules:
 Only one disk may be moved at a time.
 Each move consists of taking the upper disk from one of the rods and sliding it
onto another rod, on top of the other disks that may already be present on that
rod.
 No disk may be placed on top of a smaller disk.
Solution

c program to solve towers of hanoi problem


/* Write C programs that use both recursive and non-recursive functions
To solve Towers of Hanoi problem.*/

Department of BS&H Page 115


NRI Institute of Technology, Pothavarappadu
#include<conio.h>
#include<stdio.h>
/* Non-Recursive Function*/
void hanoiNonRecursion(int num,char sndl,char indl,char dndl)
{
char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp;
int top,add;
top=NULL;
one:
if(num==1)
{
printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);
goto four;
}
two:
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=3;
num=num-1;
sndl=sndl;
temp=indl;
indl=dndl;
dndl=temp;
goto one;
three:
printf("\nMove top disk from needle %c to needle %c ",sndl,dndl);
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=5;
num=num-1;
temp=sndl;
sndl=indl;
indl=temp;
dndl=dndl;
goto one;
four:
if(top==NULL)
return;
num=stkn[top];

Department of BS&H Page 116


NRI Institute of Technology, Pothavarappadu
sndl=stksndl[top];
indl=stkindl[top];
dndl=stkdndl[top];
add=stkadd[top];
top=top-1;
if(add==3)
goto three;
else if(add==5)
goto four;
}
/* Recursive Function*/
void hanoiRecursion( int num,char ndl1, char ndl2, char ndl3)
{
if ( num == 1 ) {
printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );
return;
}
hanoiRecursion( num - 1,ndl1, ndl3, ndl2 );
printf( "Move top disk from needle %c to needle %c.", ndl1, ndl2 );
hanoiRecursion( num - 1,ndl3, ndl2, ndl1 );
}
void main()
{
int no;
clrscr();
printf("Enter the no. of disks to be transferred: ");
scanf("%d",&no);
if(no<1)
printf("\nThere's nothing to move.");
else
printf("Non-Recursive");
hanoiNonRecursion(no,'A','B','C'); printf("\
nRecursive"); hanoiRecursion(no,'A','B','C');
getch();
}
The C Preprocessor Directives: A unique feature of c language is the preprocessor.
A program can use the tools provided by preprocessor to make the program easy to
read, modify, portable and more efficient.
The preprocessor more or less provides its own language which can be a very
powerful tool to the programmer. Recall that all preprocessor directives or commands
begin with a #.
Preprocessor is a program that processes the code before it passes through the
compiler. It operates under the control of preprocessor command lines and directives.
Preprocessor directives are placed in the source program before the main line before the

Department of BS&H Page 117


NRI Institute of Technology, Pothavarappadu
source code passes through the compiler it is examined by the preprocessor for any
preprocessor directives.
Preprocessor directives:
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies a file to be included

#ifdef Tests for macro definition


#endif Specifies the end of # if
#ifndef Tests whether the macro is not def

#if Tests a compile time condition


#else Specifies alternatives when # if test fails
The preprocessor directives can be divided into three categories
1. Macro substitution division
2. File inclusion division
3. Compiler control division
Macros: Macro substitution is a process where an identifier in a program is replaced by a
pre defined string composed of one or more tokens we can use the #define statement for the
task. It has the following form
#define identifier string
The preprocessor replaces every occurrence of the identifier int the source code by
a string. The definition should start with the keyword #define and should follow on
identifier and a string with at least one blank space between them. The string may be any
text and identifier must be a valid c name.
There are different forms of macro substitution. The most common form is
1. Simple macro substitution
2. Argument macro substitution
3. Nested macro substitution
Simple macro substitution: Simple string replacement is commonly used to define
constants example:
#define pi 3.1415926
Writing macro definition in capitals is a convention not a rule a macro definition can
include more than a simple constant value it can include expressions as well. Following
are valid examples:
#define AREA 12.36
Macros as arguments: The preprocessor permits us to define more complex and
more useful form of replacements it takes the following form.
# define identifier(f1,f2,f3…..fn) string.
Notice that there is no space between identifier and left parentheses and the identifier
f1,f2,f3 …. Fn is analogous to formal arguments in a function definition.
There is a basic difference between simple replacement discussed above and replacement
of macro arguments is known as a macro call

Department of BS&H Page 118


NRI Institute of Technology, Pothavarappadu
A simple example of a macro with arguments is
#define CUBE(x) (x*x*x)
If the following statements appears later in the program,
volume=CUBE(side);
The preprocessor would expand the statement to
volume =(side*side*side)
Nesting of macros: We can also use one macro in the definition of another macro.
That is macro definitions may be nested. Consider the following macro definitions
#define SQUARE(x) ((x)*(x))
Undefining a macro: A defined macro can be undefined using the statement
#undef identifier.
This is useful when we want to restrict the definition only to a particular part of the
program.
File inclusion: The preprocessor directive "#include file name” can be used to include any
file in to your program if the function s or macro definitions are present in an external file
they can be included in your file
In the directive the filename is the name of the file containing the required
definitions or functions alternatively the this directive can take the form
#include< filename >
Without double quotation marks. In this format the file will be searched in only
standard directories. The c preprocessor also supports a more general form of test
condition #if directive. This takes the following form
#if constant expression
{
statement-1;
statemet2’
….
….
}
#endif
the constant expression can be a logical expression such as test < = 3 etc
Passing entire one-dimensional array to a function
Arrays are the contiguous block of area. So, if the area of first element is known, then
other element of arrays can also be accessed. While passing arrays to the argument, the
name of the array is passed as an argument(,i.e, starting address of memory area is
passed as argument)
passing an array to function, as an actual argument only the name must be passed;
without the square brackets and the subscripts.
The corresponding formal argument is written in the same way but it must be declare
inside the function. The formal declaration of the array should not contain the array
dimension. In the
declaration of function using arrays as arguments, a pair of empty square brackets must
follow the data type of array argument (or name of array if given).

Department of BS&H Page 119


NRI Institute of Technology, Pothavarappadu
PASSING AN ENTIRE 1D ARRAY TO A FUNCTION
Write a C program to pass an array containing age of person to a function. This
function should find average age and display the average age in main function.
#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); // Only name of array is passed as argument.
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[])
{ int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output
Average age=27.08
C program to pass a single element of an array to function
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Output
4
Single element of an array can be passed to function as passing variable to a function.
C Program to Pass 1-D Array to Function Element by Element
#include<stdio.h>

void show(int b[3]);

void main()
{
int arr[3] = {1,2,3};
int i;

Department of BS&H Page 120


NRI Institute of Technology, Pothavarappadu
for(i=0;i<3;i++)
show(arr[i]);
}

void show(int x)
{
printf("%d\t ",x);
}
Output
1 2 3
Write a C program to display all prime numbers within the range specified by user
using functions.
#include<stdio.h>
int check_prime(int num);
int main(){
int n1,n2,i,flag;
printf("Enter the range:\
n"); scanf("%d
%d",&n1,&n2);
for(i=n1+1;i<n2;++i){
flag=check_prime(i);
if(flag==1)
printf("%d ",i);
}
return 0;
}
int check_prime(int num)
{ int j,temp=1;
for(j=2;j<=num/2;++j){
if(num%j==0){
temp=0;
break;
}
}
return temp;
}

Passing 2D array to a function


Code for Program of matrix addition using function in C .
#include<stdio.h>
#include<conio.h>

void read_arr(int a[10][10],int row,int col)


{
int i,j;

Department of BS&H Page 121


NRI Institute of Technology, Pothavarappadu
for(i=1;i<=row;i++)

Department of BS&H Page 122


NRI Institute of Technology, Pothavarappadu
{
for(j=1;j<=col;j++)
{
printf("Enter Element %d
%d : ",i,j); scanf("%d",&a[i]
[j]);
}
}
}
void add_arr(int m1[10][10],int m2[10][10],int m3[10][10],int row,int col)
{
i
n
t
i,
j;
f
o
r(
i
=
1;
i
<
=
r
o
w
;i
+
+
)
{
for(j=1;j<=col;j++)
{
m3[i][j] = m1[i][j] + m2[i][j];
}
}
}
void print_arr(int m[10][10],int row,int col)
{
i
n

Department of BS&H Page 123


NRI Institute of Technology, Pothavarappadu
t
i,
j;
f
o
r(
i
=
1;
i
<
=
r
o
w
;i
+
+
)
{
for(j=1;j<=col;j++)
{
printf("%d ",m[i][j]);
}
printf("\n");
}
}
main()
{
int m1[10][10],m2[10][10],m3[10][10],row,col;
clrscr();
printf("Enter number of
rows :"); scanf("%d",&row);
printf("Enter
number of
colomns :");
scanf("%d",&col);
read_arr(m1,row,co
l);
read_arr(m2,row,co
l);
add_arr(m1,m2,m3,
row,col);
print_arr(m3,row,c
Department of BS&H Page 124
NRI Institute of Technology, Pothavarappadu
ol);
getch();
}

Functions: Need of Functions, Function Declaration, Definition and Call. Inbuilt functions and
Passing arguments to a function, Returning values from a function. Scope of variable, local and
global variable.
#############################################
Recursive Functions: Need of Recursion, Recursive Vs Iterative solutions, Disadvantages of
Recursion.
##################################

Additional programs
####################################

Department of BS&H Page 125


NRI Institute of Technology, Pothavarappadu

You might also like