0% found this document useful (0 votes)
9 views109 pages

Unit 4

Unit 4 covers functions in C programming, including user-defined functions, standard functions, and their classifications. It discusses function design, parameter passing methods, recursion, and storage classes, emphasizing modular programming and structured design. The unit also outlines the importance of function declarations, definitions, and the communication between functions through parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views109 pages

Unit 4

Unit 4 covers functions in C programming, including user-defined functions, standard functions, and their classifications. It discusses function design, parameter passing methods, recursion, and storage classes, emphasizing modular programming and structured design. The unit also outlines the importance of function declarations, definitions, and the communication between functions through parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 109

UNIT-4

Topics to be covered in UNIT-4

Functions – User-defined functions, Function definition,


arguments, return value, prototype, arguments and parameters,
inter-function communication, Standard functions – Math
functions,
Scope – local global.

Parameter passing – Call by value and call by reference.

Recursive functions – Definition, examples, advantages and


disadvantages.

Macros – Definition, examples, comparison with functions.

Storage classes- Automatic, static ,register and external


Functions
Objectives
 To design and implement programs with more than one function.

 To understand the purpose of the function declaration, call, and


definition.

 To understand the four basic function designs.

 To understand how two functions communicate through parameters.

 To understand the differences between global and local scope.

3
When the program grows into larger,
may have many disadvantages.

1. Difficult to write a larger programs


2. Difficult to identify the logical errors
and correct.
3. Difficult to read and understand.
4. Larger programs prone for more
errors.
Designing Structured Programs

 The programs we have done so far have been very simple.

 They solved problems that could be understood without too much effort.

 The principles of top–down design and structured programming


dictate that a program should be divided into a main module and its
related modules.

 Each module is in turn divided into sub-modules until the resulting


modules are intrinsic; that is, until they are implicitly understood
without further division.

5
 Top-down design is usually done using a visual representation of the
modules known as a structured chart.

Structure Chart
6
FUNCTIONS IN C
If any module has sub modules that is called as calling module and sub
modules are called modules.

one module is communicate with other module through calling module

A c program consists of one or more functions, one and only one of


which must be named main

the function which is calling other function is called calling function

A function whom it called is called function

A called function receives control from the a calling function, when it


completes its task, it returns control to the calling function.

the main function called by the operating system, in turn main function
calls the other function to do some task.
.
7
FUNCTIONS IN C
 A function is a self-contained block of code that carries out some
specific and well-defined task.

 In general, the purpose of a function is to receive zero or more pieces


of data, operate on them, and return at most one piece of data.

 C functions are classified into two categories


1. Library Functions
2. User Defined Functions

8
FUNCTIONS IN C (contd…)

Library Functions:
 These are the built in functions available in standard library of C.

 The standard C library is collection of various types of functions which


perform some standard and predefined tasks.

Example:
 abs (a) function gives the absolute value of a, available in <math.h>

 pow (x, y) function computes x power y. available in <math.h>

 printf () and scanf () performs I/O functions and etc..,

9
FUNCTIONS IN C (contd…)

User Defined Functions:


 These functions are written by the programmer to perform some specific
tasks.

 Example: main (), sum (), fact () , show(), display() and etc.,

 The main distinction between these two categories is that library


functions are not required to be written by us whereas a user defined
function has to be developed by the user at the time of writing a
program.

Note:
 In C, a program is made of one or more functions, one and only one of
which must be called main.

 The execution of the program always starts with main, but it can call
other functions to do some part of the job. 10
Advantages of User-defined Functions

Modular Programming: It facilitates top down modular programming.

Reduction of Source Code: The length of the source program can be


reduced by using functions at appropriate places.

Easier Debugging: It is easy to locate and isolate a faulty function for


further investigation.

Code Reusability: A program can be used to avoid rewriting the same


sequence of code at two or more locations in a program.

Function Sharing: Programming teams does a large percentage of


programming. If the program is divided into subprograms, each
subprogram can be written by one or two team members of the team rather
than having the whole team to work on the complex program.

11
Structure Chart for a C Program
12
User-defined Functions
 Like every other object in C, functions must be both declared and
defined.

 The function declaration or prototype gives the whole picture of the


function that needs to be defined later.

 The function definition contains the code for a function.

 A function name is used three times in a C program: for declaration,


in a call, and for definition.

13
The general form of a C user-defined function:

return_type function_name (argument declaration)


{
//local declarations
……
//statements
……
return (expression);
}

14
The general form of a C user-defined function
(contd…)
return-type:
 Specifies the type of value that a function returns using the return
statement.
 It can be any valid data type.
 If no data type is specified the function is assumed to return an integer
result.

function-name:
 Must follow same rules of variable names in C.
 No two functions have the same name in a C program.

argument declaration:
 It is a comma-separated list of variables that receive the values of the
argument when function is called.
 If there is no argument declaration the bracket consists of keyword void.
15
User-defined Functions (Contd…)

 A function name is used three times in a C program: for declaration,


in a call, and for definition.

Function Declaration (or) Prototype:


 The ANSI C standard expands the concept of forward function
declaration.
This expanded declaration is called a function prototype.

A function prototype performs two special tasks:


 First it identifies the return type of the function so that the compile can
generate the correct code for the return data.

 Second, it specifies the type and number of arguments used by the


function.

Note: The prototype normally goes near the top of the program and must
appear before any call is made to the function.
16
User-defined Functions (Contd…)

The general form of the function prototype or declaration is:

17
User-defined Functions (Contd…)
User-defined Functions (Contd…)
The Function Call:
 A function call is a postfix expression.
 The operand in a function is the function name.
 The operator is the parameter lists (…), which contain the actual
parameters.

Example:
void main ()
{
sum (a, b);
}

 When the compiler encounters the function call ,the control is transferred
to the function sum().

 The function is executed line by line and produces the output for the sum
of two numbers and then control is transferred back to the main function.18
User-defined Functions (Contd…)
Function Definition: The function definition contains the code for a
function.

It is made up of two parts:


 The function header and the function body, the compound statement
is must.

Function header consists of three parts:


 the return type,
 the function name, and
 the formal parameter list.

 Function body contains local declarations and function statement.

 Variables can be declared inside function body.

 Function can not be defined inside another function.


19
User-defined Functions (Contd…)

Function Definition

20
User-defined Functions (Contd…)

A function gets called when the function name is followed by a


semicolon.

void main()
{
fun1();
}

When a function is followed by a pair of braces in which one or


more statements may be included is called function definition.
void fun1()
{
printf(“we are in fun1”);
}

21
User-defined Functions (Contd…)
Any function can be called from any other function. Even main
can be called from other functions.

A function can be called any number of times.

The order in which functions are defined in program and the


order in which they get called need not be same.

A function can be called from another function but a function


can not be defined in another function.

 function can also called itself is called recursion.

22
Each function is called in the sequence we have specified in the main function.
void fun1(); void fun2(); void fun3();
void main()
{
printf(“\n I am calling other functions”);
func1();
func2();
func3(); Output:
printf(“all functions are called\n”);
}//main I am calling other function
func1() in func1
{ in func2
in func3
printf(“in func1\n”);
all functions are called.
}//func1
func2()
{
printf(“in func2\n”);
}//func2
func3()
{
printf(“in func3\n”);
}//func3
After each function task is over the control passed to the calling function(main()).
7 One function can also call the other function which has already been called
void fun1(); void fun2(); void fun3();
void main()
{
printf(“I am in main\n”);
func1();
printf(“I back in main\n”);
}//main
void func1()
{
printf(“in func1\n”);
func2();
printf(“I back in func1\n”);
}//func1
void func2()
{
printf(“In func2\n”);
func3();
printf(“I back in func2\n”); }//func2
void func3()
{
printf(“in fun3\n”); }//func3
a function cannot be defined inside the other function.
main()
{
func1();
func2();
}//main
func1()
{
printf(“\nthis is func1”);
func2()
{
printf(“\nthis is func2”);
}//func2()
}//func1()
 called function may or may not send information (data) back
to the calling function.
 If called function return some value to the calling function at
the end of the function definition (before }) use return
statement.
void func1();
void main()
{
func1(); return; this statement says that does not return any
printf(“\nhai”); value. This may or may not used in void functions.
}//main
void func1() return(expression);- it return some value to the calling
{ function.
printf(“hello”);
return; Note- a function return only single value.
}//func1()
Categories of functions
 Functions may belong to one of the following
categories.
1. functions with no arguments and no return value.
2. functions with no arguments and return value.
3. functions with arguments and no return value.
4. functions with arguments and return value.
1. functions with no arguments and no return value.
 If the function has no arguments, it does not receive any
arguments/ parameters from the calling function.
 It does not return any value to the calling function.
 In this case, return type must be specified as void and put
empty parenthesis.

#include<stdio.h>
void msg()
void msg(); {
int main() printf(“learning c is easy”);
{ }
msg();
return 0;
}//main
#include <stdio.h>
void add(); // function declaration or
prototype
int main()
{
add(); // function call
return 0;
}
void add() // function definition
{
int a,b,c;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
c=a+b;
printf(“ a+b =%d”,c);
}
2.functions with no arguments and return value.
 In which called function does not receive in arguments from
calling function. However, end of its task it return some value
to the calling function.
 In this case, return value must be specified and parenthesis is
empty

#include<stdio.h>
char msg()
char msg(); {
int main() char ch;
{ printf(“enter character”);
char x; scanf(“%c”,&ch);
x=msg(); return ch;
printf(“%c”,x); }
return 0;
}//main
#include <stdio.h>
int add(); // function declaration
int main()
{
int x;
x=add(); // function call
printf(“addition=%d”,x);
return 0;
}
int add() // function definition
{
int a,b,c;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
c=a+b;
return c;
}
User-defined Functions (Contd…)
Generally, there are two ways that a function terminates execution and
returns to the caller.
 When the last statement in the function has executed and conceptually

the function’s ending ‘}’ is encountered.


 Whenever it faces return statement.

The return statement: It is the mechanism for returning a value from


the called function to its caller.

The general form of the return statement is:


return expression;
There can be any number of return statements in the program but each
statement can return only one value.
Return type specifies the data type of value returned
If no value is returned to the calling function then return type is
declared as void.
By default ,return type of any function will be of type int. 32
Functions with no arguments and return values (Contd…)

 The calling function is free to ignore the returned value.

 Expression after the return is not necessary.

The return statement has two important uses:


1.It causes an immediate exit of the control from the function. That is ,it
causes program execution to return to the called function.
2.It returns the value present in the expression.

Example: return(x + y);


return (6 * 8);
return (3);
return;

33
3. functions with arguments and no return value.
 Called function receives arguments from the calling function and called
function doesn’t return any value to calling function.
 In function prototype, we have to specifies no of arguments in the
parenthesis and specify return type as void.

void msg( float per)


#include<stdio.h>
{
void msg(float);
printf(“percentage of student=%f”,per);
int main()
}
{
float avg; The arguments in the calling
printf(“enter avg of student”); functions are called actual
scanf(“%f”,&avg); arguments.(ex avg)
msg(avg); The arguments in the called
return 0; function are called formal
}//main arguments.(ex per)
Actual and formal arguments
need not be same
#include <stdio.h>
void add(int ,int ); // function declaration or prototype
int main()
{
int a,b;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
add(a,b); // function call
return 0;
}
void add(int x, int y) // function definition
{
int z;
z=x+y;
printf(“ addition=%d“,z);
User-defined Functions (Contd…)

3. Functions with arguments and no return values:

 In this category there is data transfer from the calling function to the
called function using parameters.
 But, there is no data transfer from called function to the calling
function.

Local Variables:
 Variables that are defined within a function are called local variables.
 A local variable comes into existence when the function is entered and
is destroyed upon exit.

Function Arguments: The arguments that are supplied to function are


in two categories
1. Actual Arguments/Parameters
2. Formal Arguments/Parameters

36
User-defined Functions (Contd…)
Functions with arguments and no return values (Contd…)
Actual Arguments/Parameters:
 Actual parameters that are passed in function call are called actual
parameters
 These are the parameters present in the calling function.
Actual parameters can be variables, constants or expressions.
Formal Arguments/Parameters:
 Formal parameters are the variables that are declared in the header of
the function definition.
These are the parameters present in the called function
Formal parameters can be only variables,.

Note: Actual and Formal parameters must match exactly in type, order,
and number. Their names however, do not need to match.

37
4. functions with arguments and with return value.
 Called function receives arguments from the calling function and called
function return any value to calling function.
 In function prototype, we have to specifies no of arguments in the
parenthesis and specify return type .

double msg( double avg)


#include<stdio.h>
{
double msg(double);
double per;
int main()
per=avg/6;
{
return per;
double sum;
printf(“enter avg of student”);
}
scanf(“%lf”,&sum);
printf(“%lf”,msg(sum));
return 0;
}//main
#include <stdio.h>
int add(int x,int y); // function declaration or prototype
int main()
{
int a,b,x;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
x=add(a,b); // function call
printf(“ addition=%d“,x);
return 0;
}
int add(int x, int y) // function definition
{
int z;
z=x+y;
return z;
}
4. functions with arguments and return value.
#include<stdio.h>
int add(int,int); #include<stdio.h> #include<stdio.h>
int main() int add(int x,int y); int add(int,int);
{ int main() int main()
int a,b; { {
int a,b; int a,b;
printf("\nenter a and b");
scanf("%d %d",&a,&b); printf("\nenter a and b"); printf("\nenter a and b");
printf(“%d",add(a,b)); scanf("%d %d",&a,&b); scanf("%d %d",&a,&b);
return 0; c=add(a,b); printf("%d",add(a,b));
}//main printf(“c=%d",c); return 0;
int add(int a,int b) return 0; }//main
{ }//main int add(int a,int b)
int c; int add(int a,int b) {
c=a+b; { return a+b;
return c; return a+b; }//add()
}//add() }//add()
INTER-FUNCTION
COMMUNICATION

The calling and called functions communicate


with each other using three strategies.

Upward communication

Downward communication

Bidirectional communication
UPWARD
COMMUNICATION
 In this strategy ,only called
function can pass the data to the
calling function, it will not
receive anything from calling
function. Upward
Calling communication in c can be
function
implemented by using return
statement.
 Both called and calling function
Called must declare a data variable to
function
save the address and receive the
data.
#include <stdio.h>
int prime() {
int i,n,cn=0;
printf("enter n");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
cn++; }
return( cn==0?1: 0);
}
int main() {
int f;
f=prime();
f==1?printf(“prime”):printf(“not prime”);
return 0;
}
Downward Communication
In this strategy, calling function is the active function i.e.,

the information can only be sent by the calling function to


the called function, there will be no response from the
called function(One way communication).
 Called function can make changes on the received
information , but this will not effect on the original
information of the calling function
Calling
function

Called function
#include <stdio.h>
void prime(int n)
{
int i,cn=0;
for(i=2;i<n;i++)
{
if(n%i==0)
cn++;
}
cn==0?printf("prime"):printf("not prime");
}
int main() {
int n;
printf("enter n");
scanf("%d",&n);
prime(n);
return 0;
Bidirectional Communication
 In this strategy, both called and calling
function can send the data to each other.

Called
function

Calling
function
#include <stdio.h>
int prime( int n) {
int i,cn=0;
for(i=2;i<n;i++)
{
if(n%i==0)
cn++; }
return( cn==0?1: 0);
}
int main() {
int f,n;
printf("enter n");
scanf("%d",&n);
f=prime(n);
f==1?printf(“prime”):printf(“not prime”);
return 0;
}
Nesting of functions
C permits nesting of functions, main function can call function1,
function1 can call function2, which in turn calls function3 ..,
There is no limit as how deeply functions can be nested.

Consider the following example:

In the below example ,when the main() function finds the function call
sum(), then the control is transferred from main() to the function sum(),
there sum() is calling the function read(), then the control is transferred
to read() function, then the body of the function read() executes, then the
control is transferred back to sum(). Again read() function is invoked.
Observe the chain of control transfers between the nested functions.

48
#include<stdio.h> //Example program for nested-functions
int read ();
int sum (int, int);
int main ()
{
printf (“%d”, sum ());
return 0;
}
int sum (int x, int y)
{
x=read ();
y=read ();
return x + y;
}
int read ()
{
int p;
printf (“\n Enter any value: “);
scanf (“%d”, &p);
return p;
49
}
Standard Functions
 C provides a rich collection of standard functions whose definitions
have been written and are ready to be used in our programs.

To use these functions, we must include their function declarations.

 We discuss the following:


Math Functions

Some of the header files includes the following functions are:


<stdio.h> Standard I/O functions
<stdlib.h> Utility functions such as string conversion routines,
memory allocation routines, etc..,
<string.h> String manipulation functions
<math.h> Mathematical functions
<ctype.h> Character testing and conversion functions
50
Library Functions and the Linker
51
Math Functions

The following are some of the math functions:


 Absolute
 Ceil
 Floor
 Truncate
 Round
 Power
 Square Root
All the above functions are available in math.h header file.

52
Absolute Functions:
 An absolute value is the positive rendering of the values
regardless of its sign.
 The integer functions are abs, labs, llabs.

Syntax:
int abs(int number);
long labs(long number);
long long llabs(long long number);

 The float function is fabs:


float fabs(float number);
Example: abs(3) gives 3
fabs(3.4) gives 3.4

53
Ceil Function:
 A ceil computes the nearest integer value which is greater than or equal
to a number.
 Format of ceil function:
double ceil(double number);
float ceilf(float number);
long double ceill(long double number);
 Example:
ceil(-1.9) gives -1.0
ceil(1.1) gives 2.0
Floor Function:
 A floor computes the nearest integer value that is less than or equal to a
number.
 Format of floor function:
double floor(double number);
float floorf(float number);
long double floorl(long double number);
 Example:
floor(-1.1) gives -2.0 54
floor(1.9) gives 1.0
Ceiling Function
55
Floor Function
56
Truncate Function:
 The truncate function return the integral in the direction of 0.
 Format of trunc function:
double trunc(double number);
float truncf(float number);
long double truncl(long double number);
 Example:
trunc(-1.1) gives -1.0
trunc(1.9) gives 1.0
Round Function:
 The round function returns the nearest integral value.
 Format of round function:
double round(double number);
float roundf(float number);
long double roundl(long double number);
 Example:
round(-1.1) gives -1.0
round(1.9) gives 2.0
round(-1.5) gives -2.0 57
Power Function:
 The power function returns the value of the x raised to the power y that
is xy.

Format of pow function:


double pow(double number1, double number2);

 Example:
pow(2,5) gives 32

Square Root Function:


 The square root function returns the non negative square root of a
number.

 Format of sqrt function:


double sqrt(double number);

 Example:
sqrt(4.0) gives 2.0 58
Scope

 Scope determines the region of the program in which a defined


object is visible.

 Scope pertains to any object that can be declared, such as a variable


or a function declaration.

There are three types:


 Global Scope (File Scope)
 Local Scope (Block Scope)
 Function Scope

59
Rules for Local Scope(Block Scope):

 Block is zero or more statements enclosed in a set of braces.

 Variables are in scope from their point of declaration until the end of
the block.

 Variables defined within a block have a local scope.

 They are visible in that block scope only. Outside the block they are
not visible.

 For example, a variable declared in the formal parameter list of a


function has block scope, and active only in the body only.

 Variable declared in the initialization section of a for loop has also


block scope, but only within the for statement.

60
//Example for local scope or block scope

{
int a = 2;
printf (“%d\n”, a); /* outer block a 2 is printed */
{
int a = 5;
printf (“%d\n”, a); /* inner block a 5 is printed */
}
printf (“%d\n”, a); /* 2 is printed */
}
/* a no longer defined */ Outer “a” Masked.

 In the above block, A variable that is declared in an outer block is


available in the inner block unless it is re-declared.

 In this case the outer block declaration is temporarily “masked”.


61
Rules for Global Scope (File Scope):

 File scope generally includes all declarations outside function and all
function headers.

 An object with file scope sometimes referred to as a global object.

 File scope includes the entire source file for a program, including any
files included in it.

 An object with file scope has visibility through the whole source file
in which it is declared.

 For Example, a variable declared in the global section can be accessed


from anywhere in the source program.

62
//Example program for global scope
void fun1();
void fun2();
int g=10;
void main()
{
g++;
printf(“main=%d”,g);
fun1();
printf(“back in main=%d”,g);
}
void fun1()
{
g=30;
printf(“fun1 = %d\n“,g);
fun2();
}
void fun2()
{
g++;
printf(“fun2=%d”,g);
}
63
//Example program for global scope
void fun1();
void fun2();
int count;
void main()
{
count = 100;
fun1();
}
void fun1()
{
printf("Count is = %d\n",count);
fun2();
} Output:
void fun2() Count is = 100
{ *****
int count;
for(count = 0;count < 5;count++)
printf("*");
} 64
Local Variables:

 Variables that are declared in a block known as local variables.


 They are known in the block where they are created and active in the
block only.
 They hold their values during the execution of the block.
 After completing the execution of the block they are undefined.

Global Variables:

 Global variables are known throughout the entire program and may be
used in any piece of code.
 Also, they will hold their values during the entire execution of the
program.
 Global variables are created by declaring them outside of the function
and they can be accessed by any expression.
 In general we are declaring global variable at the top of the program.

65
Rules for Function Scope:

 Variables defined within a function (including main) are local to this


function and no other function has direct access to them!

 The only way is by passing variables to a function as parameters.

 The only way to pass (a single) variable back to the calling


function is via the return statement.

66
Parameter Passing Techniques

McGraw-Hill ©The McGraw-Hill Companies, Inc., 2000


 There are two ways of passing parameters to a
function

 Call-by-value
 Call-by-reference
Call-by-value:

 When a function is called with actual


parameters, the values of actual parameters are
copied into the formal parameters.
 If the values of the formal parameters changes
in the function, the values of the actual
parameters are not changed.
 This way of passing parameters is called call
by value (pass by value).
Call by value
#include <stdio.h>
void swap(int x, int y);
int main()
{
int a,b;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
printf(“before swapping a,b values:%d%d”,a,b);
swap(a,b); // function call
printf(“after swapping a,b values:%d%d”,a,b);
return 0;
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Call-by-Reference:

 In this method , the addresses of the actual


arguments are copied to the corresponding
parameters in the “called” function.
 Any modifications done to the formal
parameters in the ”called function” causes the
actual parameters to change.
Call by reference
#include <stdio.h>
void swap(int *x, int *y);
int main()
{
int a,b;
printf(“enter a, b values”);
scanf(“%d%d”, &a,&b);
printf(“before swapping a,b values:%d%d”,a,b);
swap(&a,&b);
printf(“after swapping a,b values:%d%d”,a,b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Call by Value Call by Reference

When Function is called the When a function is called


values of variables are passed. address of variables is passed.
Formal parameters contain the Formal parameters contain the
value of actual parameters. address of actual parameters.

Change of formal parameters The actual parameters are


in the function will not affect the changed since the formal
actual parameters in the calling parameters indirectly
function manipulate the actual
parameters

73
Recursion in C
 In C, functions can call themselves .

 A function calling itself is called recursive function.

 Recursion is a repetitive process, where the function calls itself.

 Generally normal function only knows how to solve the simplest


case of the problem.

 When the simplest case is given as an input, the function will


immediately return with an answer.

 However, if a more complex input is given, a recursive function will


divide the problem into 2 pieces:
 A part that it knows how to solve and
 Another part that it does not know how to solve.
74
Concept of recursive function:
 A recursive function is invoked or called to solve a problem.

 The statement that solves a problem is known as the base case.

 Every recursive function must have a base case.

 The rest of the function is known as the general case.

 The recursion step is done until the problem converges to become the
simplest case.

 This simplest case will be solved by the function which will then
return the answer to the previous copy of the function.

 The sequence of returns will then go all the way up until the original
call of the function finally return the result.

75
Example: Recursive Factorial Function

Iteration Definition:

fact (n) = 1 if n=0


= n*(n-1)*(n-2)…….3*2*1 if n>0

Recursion Definition:

fact (n) = 1 if n=0 (Base Case)


= n*fact (n-1) if n>0 (General Case)

76
#include<stdio.h>
long factorial (long); /* function prototype */
void main (void)
{
long int n;
printf(“enter n”);
scanf(“%ld”,&n);
printf ("%ld! = %1d\n“,n, factorial (n)); /* function call */
}
long factorial (long n) /* function definition */
{
if (n = =0)
return 1;
else
return (n * factorial (n-1));
}
OUTPUT:
4! = 24
77
Designing a Recursive Function:
In the above program, once the base condition has reached, the solution begins.

The program has found one part of the answer and can return that part to the next
more general statement.
Thus, after calculating factorial (0) is 1, and then it returns 1.That leads to solve
the next general case,
factorial (1)  1*factorial (0)  1*1  1

The program now returns the value of factorial (1) to next general case,
factorial (2),
factorial (2)  2*factorial (1)  2*1  2
As the program solves each general case in turn, the program can solve the next
higher general case, until it finally solves the most general case, the original
problem.

The following are the rules for designing a recursive function:


1. First, determine the base case.
2. Then, determine the general case.
3. Finally, combine the base case and general case in to a function.
78
factorial(int n)
{ number=4
int fact;
if(n==0)
return 1; Factorial(4) returns 24 to main
else because main is calling
fact=n*factorial(n-1); function to that.
return fact;
}//factorial()
factorial (4) =4*factorial factorial (4) =4*6=24
(3)

factorial (3) =3*factorial factorial (3) =3*2=6


(2)

factorial (2) =2*factorial factorial (2) =2*1=2


(1)

factorial (1) =1*factorial factorial (1) =1*1=1


(0)
factorial (0) =1
Recursion
Advantages:
1.Complex case analysis and nested loops can be avoided.
2.Recursion can lead to more readable and efficient algorithm descriptions .
3.Through recursion one can solve problems in easy way while its iterative
solution is very big and complex

Disadvantages:

1.Recursive solution is always logical and it is very difficult to debug and


understand
2.In recursive we must have an if statement somewhere to force the
function to return without the recursive call being executed, otherwise the
function will never return
3.Recursion takes a lot of stack space
4.Recursion uses more processor time

80
Fibonacci using recursion Ackerman using recursion
#include<stdio.h>
int fib(int n);
void main()
{
int n,res;
printf(“enter n”);
scanf(“%d”,&n);
res=fib(n);
printf(“Nth Fibonacci term=%d”, res);
}
int fib(int n)
{
if (n==1)
return 0;
else if(n==2)
return 1;
else
return(fib(n-1)+fib(n-2));
}
Difference between Iteration and Recursion

ITERATION RECURSION
Iteration explicitly uses Recursion achieves repetition by
repetition structure. calling the same function repeatedly.
Iteration is terminated when Recursion is terminated when base
the loop condition fails case is satisfied.
May have infinite loop if the Recursion is infinite if there is no base
loop condition never fails case or if base case never reaches.

Iterative functions execute Recursive functions are slow and


much faster and occupy less takes a lot of memory space compared
memory space. to iterative functions

82
Storage classes in c
 The storage class determines the part of member storage is allocated
for an object and how long the storage allocation continues to exit.
 A scope specifies the part of the program which a variable name is

visible, that is the accessibility of the variable by its name.


 Storage class tells us:
1) Where the variable is stored.
2) Initial value of the variable.
3) Scope of the variable. Scope specifies the part of the program which
a variable is accessed.
4) Life of the variable. How long variable exist in the program.
 There are four types of storage classes:

 1) Automatic storage class

 2) Register storage class

 3) Static storage class

 4) External storage class


1.Automatic storage class
1. the variable is declared with keyword auto. ( auto keyword is optional
while declaring variables.)
2. they must be declared at the start of a block.
3. Memory is allocated automatically upon entry to a block and freed
automatically upon exit from the block.
4. Storage- automatic variable stored in the memory.
5. Default initial value- garbage value.
6. Scope- local to the block in which they are declared, including any
blocks nested within that block. For this reasons automatic variable are
also called local variable.
7. Life – within the block in which the variable is defined.
void main()
Examples {
main() int x=10;
{
{ int x=20;
auto int x; {
int x=30;
printf(“%d”,x); printf(“x=%d”,x);
} }
printf(“x=%d”,x);
Output – gives garbage value. }
printf(“x=%d”,x);
} Output- 30 20 10
2. Register storage class
1. Automatic variables are allocated storage in the main memory of the
computer; however, for most computers, accessing data in memory is
considerably slower than processing directly in the CPU.
2. Registers are memory located within the CPU itself where data can be
stored and accessed quickly. Normally, the compiler determines what
data is to be stored in the registers of the CPU at what times.
3. Thus, register variables provide a certain control over efficiency of
program execution.
4. Variables which are used repeatedly or whose access times are critical
may be declared to be of storage class register.
5. Variables can be declared with keyword register as register int x;
6. Storage- variable stored in cpu registers rather than memory.
7. Default initial value- garbage value.
8. Scope- local to the block in which they are declared, including any
blocks nested within that block. For this reasons automatic variable are
also called local variable.
9. Life – within the block in which the variable is defined.
void main()
{
register int x;
3.Static storage class

1. Variables must be declared with the key word static. static int x;
2. Storage- variable stored in computer memory.
3. Default initial value- zero.
4. Scope- local to the block in which they are declared.
5. Life –value of the variable persists between the different function calls.
6. Static automatic variables continue to exist even after the block in which
they are defined terminates. Thus, the value of a static variable in a
function is retained between repeated function calls to the same
function.
7. In the case of recursive function calls we use static storage class.
8. Static variables may be initialized in their declarations; however, the
initializes must be constant expressions, and initialization is done only
once at compile time when memory is allocated for the static variable.
9. Static and auto variables are differ in their life and initial value.
Difference between static and auto

void main() void main()


{ { void main()
add(); add(); {
add(); add(); static int i;
add(); add(); printf(“%d”,i);
}
}//main }//main
add() add()
{ Out put 0
{
auto int i=1; static int i=1;
printf(“%d”,i); printf(“%d”,i);
i++; i++;
}//add }//add

Out put 1 1 1
Out put 1 2 3
4. External storage class
1. All variables we have seen so far have had limited scope (the
block in which they are declared) and limited lifetimes (as for
automatic variables).
2. These variables are declared with keyword extern as
extern int x; ( extern keyword may be omitted).
3. Storage- Memory.
4. Default initial value- zero.
5. Scope- as long as the programs execution.
6. Life- doesn’t come to an end.
7. External variables are declared outside the all the functions. So
that they are available to all the functions in a program.
int i; local variable has highest If any variable declared
void main() preference than global out side of the main is
{ variable so that local treated as extern variable/
printf(“%d”,i);->0 variable value gets printed. global variable.
add();--------1 If any variable declared
add();------2 extern int x=100; as global variable inside
sub();------1 void main() of the main that must be
sub();----0 { declared with key word
}//main() int x=200; extern and defined outside
add() printf(“x=%d”,x); of the main.
{ display();
i++; }// int x=20;
printf(“i=%d”i); display() void main()
}//add() { {
Sub() printf(“%d”,x); extern int y;
{ } printf(“%d %d”,x,y);
i--; }
printf(“i=%d”,i);
int y=20;
}//sub()
int var; -> declaration and definition
extern int var ; -> declaration
 When we write extern some_data_type some_variable_name; no memory is

allocated
 When an extern variable is initialized, then memory for this is allocated and it

will be considered defined.


 The undefined reference to error occurs when the variable is declared using an

extern but not defined later or the file in which the definition of the variable is
present is not included in the program
Example1: Example2: Example3:
extern int a; //declaration extern int a =10; extern int a; // declaration
void main() // declaration and void main()
{ defination {
printf("%d", a); void main()
} { printf("%d", a);
printf("%d", a); }
Output: error } int a=5; //defination
Output: 10
Output: 5
Uses of C Extern Variable
when a particular files need to access a variable from another file.
Create a global common variable that can be used in all files that are linked
together.
A C extern function is a global function that can be declared in a file and called
from another file.
Syntax: extern return_type function_name(parameter1,paremeter2,...);
there is no need to use the C extern keyword before a function because functions
are always handled as global by the compiler
umath.h Test.c
int IT=12; #include<stdio.h>
#define sqre(a) a*a #include "umath.h"
#define rect(x,y) x*y extern int IT;
void main()
int fact(int n)
{
{ printf("IT=%d\n",IT);
int i,f=1; printf("area of square=%d\n",sqre(5));
for(i=1;i<=n;i++) printf("fact=%d\n",fact(6));
f*=i; }
return f;
}
Save as 2dreadprint.c
#include<stdio.h> Add.c
void read(int x[][5],int r,int c)
{ #include<stdio.h>
int i,j; #include "2dreadprint.c"
printf("enter elements"); void main()
for(i=0;i<r;i++)
{ {
for(j=0;j<c;j++) int x[5][5],y[5][5],z[5][5],i,j;
scanf("%d",&x[i][j]);
read(x,3,3);
}
} read(y,3,3);
void print(int x[][5],int r,int c) for(i=0;i<3;i++)
{
{
int i,j;
printf("elements are:"); for(j=0;j<3;j++)
for(i=0;i<r;i++) z[i][j]=x[i][j]+y[i][j];
{
}
for(j=0;j<c;j++)
{ print(z,3,3);
printf("%3d",x[i][j]); }
}
printf("\n"); }
Macros
Preprocessor Commands:
 The C compiler is made of two functional parts: a preprocessor and a
translator.

 The preprocessor is a program which processes the source code before it


passes through the compiler.

 The translator is a program which converts the program into machine


language and gives the object module.

There are three major tasks of a preprocessor directive:


 Definition of symbolic constants and macros(macro definition)
Inclusion of other files (file inclusion
 Conditional compilation of program code/Conditional execution of
preprocessor directives

93
Symbolic Constants:
 Macro definition without arguments is referred as a constant.
 The body of the macro definition can be any constant value
including integer, float, double, character, or string.
 However, character constants must be enclosed in single quotes and
string constants in double quotes.
Example:
#define PI 3.142
#define T ‘h’
#define AND && #include <stdio.h>
#define LESSTHAN < #define PI 3.1415
#define MES “Welcome to C” int main()
{
#include<stdio.h> #include <stdio.h> float r, a;
#define T ‘h’ #define L “hello” printf("Enter the radius: ");
int main() int main() scanf(“%f", &r);
{ { a=PI*r*r;
printf(“ %c", T); printf(L); printf("Area=%f",a);
return 0; return 0 ; return 0;
} } } 94
#include <stdio.h>
#include<stdio.h> #define P printf(“welcome”);\
#define L < printf(“Snist”);
int main() int main()
{ {
int a=10,b=5; printf(“start”);
if( a L b) P
printf(“ a is small”); return 0;
else }
printf(“b is small”);
return 0;
}

95
Macro Definition:

 A macro definition command associates a name with a sequence of


tokens.

 The name is called the macro name and the tokens are referred to as the
macro body.

The following syntax is used to define a macro:

#define macro_name(<arg_list>) macro_body

Here #define is a define directive, macro_name is a valid C identifier.

macro_body is used to specify how the name is replaced in the program


before it is compiled.

96
Macro Definition (Cont…):
 Macro must be coded on a single line.

 We can use backslash( \ ) followed immediately by a new line to code


macro in multiple lines.

 Performs a text substitution – no data type checking.

 We need to carefully code the macro body.

 Whenever a macro call is encounter, the preprocessor replaces the call


with the macro body.

 If body is not created carefully it may create an error or undesired result.

97
1.We can also define macros that works like a function call
#include<stdio.h>
#define square(x) (x*x)
void main()
{
int a=10;
printf(“\nThe square of %d=%d”, a, square(a));
}
2.The macros can take function like arguments, the arguments are not
checked for data type.
#include<stdio.h>
#define max(x,y) x>y?x:y
void main()
{
int a,b;
float x,y;
printf(“enter a,b,x,y”);
scanf(“%d%d%x%y”,&a,&b,&x,&y);
printf(“\nmaxvalue=%d”, max(a,b));
printf(“\n max=%f”,max(x,y));
} 98
Nested Macros:
 C handles nested macros by simply rescanning a line after macro
expansion.

 Therefore, if an expansion results in a new statement with a macro ,the


second macro will be properly expanded.

For Example:
#define sqre(a) (a*a)
#define cube(a) (sqre(a)*a)

The expansion of x=cube(4);

results in the following expansion: x=(sqre(4)*4);

After rescanning becomes x=((4*4)*4);

99
File Inclusion:
 The first job of a preprocessor is file inclusion that is copying of one or
more files into programs.

 The files are usually header files and external files containing functions
and data declarations.
General form is:
#include filename

It has two different forms:


1. #include <filename>
 It is used to direct the preprocessor to include header files from the
system library.

2. #include “filename”
 It is used to direct the preprocessor look for the files in the current
working directory and standard library.

100
//Example program to include user defined header file

#include<stdio.h>
#include “MyFile.h”
void main()
{
int a=10,b=20;
printf(“\n The sum=%d”, sum(a,b));
}

MyFile.h
#include<stdio.h>
OUTPUT: #define sum(x, y) (x+y)
The sum=30

101
Undefining Macros:
 Once defined, a macro command cannot be redefined.

 Any attempt to redefine it will result in a compilation error.

 However, it is possible to redefine a macro by first undefining it, using


the #undef command and defining it again.

Example:
#define Val 30

#undef Val

#define Val 50

102
The Defined Operator:
 The defined operator can be used only in a conditional compilation.

 It can be used in macros.

 The value of defined (macro-name) is 0 if the name is not defined and 1


if it is defined.

For Example:
#define Val 24

The value of defined(Val) is 1 and the value of !defined(Val) is 0.

103
Conditional Compilation:
 It allows us to control the compilation process by including or excluding
statements.

 Cast expressions, size of, enumeration constants cannot be evaluated in


preprocessor directives.

 Its structure is similar to if statement.


Syntax for conditional compilation:

#if expression1 #if expression1


code to be included for true code to be included for true
#endif #elif expression2
code to be included for true
#if expression1
#else
code to be included for true
code to be included false
#else
#endif
code to be included false
#endif
104
Conditional Compilation (Cont…):
Example:
#if !defined NULL
#define NULL 0
#endif
 The above code determines the symbolic constant NULL is defined or
not.

 If NULL is defined, defined(NULL) evaluates to 1,If NULL is not


defined, and this function defines NULL to be 0.

 Every #if must end with #endif.

 #ifdef name means #if defined(name).

 #ifndef name means #if !defined(name).

105
Conditional Compilation (Cont…):

Command Meaning
When expression is true, the code that follows is
#if expression
included for compilation.
#endif Terminates the conditional command.

#else Specifies alternate code in two-way decision.


#elif Specifies alternate code in multi-way decision.
#ifdef name Tests for the macro definition.

#ifndef name Tests whether macro is not defined .

Conditional Compilation Commands 106


Conditional Compilation (Cont…):

#include<stdio.h>
#define val 1
void main()
{ Output:
#if !defined(number) The number = 100
#define number 100 The value of pi = 3.140000
#endif
#ifdef val
#define pi 3.14
#endif
printf(“\n The number = %d”,number);
printf(“\n The value of pi = %f”,pi);
}

107
Conditional Compilation (Cont…):

#include<stdio.h> #include<stdio.h>
void main() #define NUM 10
{ void main()
#ifdef max {
#define min 40 #if(NUM == 0)
#else printf("\nNumber is Zero");
#define min 100 #elif(NUM > 0)
#endif printf("\nNumber is Positive");
printf(“\n The number = %d”,min); #else
printf("\nNumber is Negative");
} #endif
}

108
Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Faster Speed of Execution is Slower
Before Compilation macro name is During function call , Transfer of
replaced by macro value Control takes place
Useful where small code appears Useful where large code appears
many time many time
Generally Macros do not extend Function can be of any number of
beyond one line lines
Macro does not Check Compile Function Checks Compile Errors
Errors

Difference between Macro and Function


109

You might also like