0% found this document useful (0 votes)
3 views

Module 14 - part 1 and 2

The document provides an overview of recursion in computer science, defining recursive functions and illustrating their use with examples such as factorial calculation and Fibonacci series. It also discusses the C preprocessor, including macro expansion directives, advantages of macros versus functions, and file inclusion directives. Key concepts include the structure of recursive functions, their advantages and disadvantages, and how preprocessor directives facilitate code management and efficiency.

Uploaded by

JAYESH HARLALKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 14 - part 1 and 2

The document provides an overview of recursion in computer science, defining recursive functions and illustrating their use with examples such as factorial calculation and Fibonacci series. It also discusses the C preprocessor, including macro expansion directives, advantages of macros versus functions, and file inclusion directives. Key concepts include the structure of recursive functions, their advantages and disadvantages, and how preprocessor directives facilitate code management and efficiency.

Uploaded by

JAYESH HARLALKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Module 14 – part 1 – Recursion

BITS Pilani Dr. Amitesh Singh Rajput


Pilani Campus
Department of Computer Science & Information Systems
Module Overview

• Recursion
• Recursive Functions

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Definition (mathematical)
• Recursion is the process of defining something in terms of itself,
and is sometimes called circular definition.

• A recursive process is one in which objects are defined in terms


of other objects of the same type.

• The entire class of objects can then be built up from a few


initial values and a small number of rules.

• Ex: Fibonacci Number series

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Definition (Computer Science)
• A recursive function is one which calls itself.

• Recursive functions are useful in evaluating certain types of


mathematical function.

• When a function calls another function and that second function


calls the third function then this kind of a function is called nesting
of functions.

• But a recursive function is the function that calls itself repeatedly.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Simple Example
main()
{
printf(“This is an example of recursive function”);
main();
}

When this program is executed. The line is printed repeatedly and


indefinitely. We might have to abruptly terminate the execution.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Factorial Calculation
int fact(int n) /* non-recursive */
{
int t, ans;
ans = 1;
for(t = 1; t <= n; t++)
ans = ans*t;
return(ans);
}

int factr(int n){ /* recursive */


int ans;
if(n == 1)
return(1);
answer = factr(n-1)*n; /* recursive call */
return(ans);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Recursive version of power
function
double power(double val, unsigned pow)
{
if(pow == 0) /*pow(x, 0) returns 1*/
return(1.0);
else
return(power(val, pow-1)*val);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How recursive function works?
• When a function calls itself, a new set of local variables and
parameters are allocated storage on the stack, and the
function code is executed from the top with these new
variables.

• A recursive call does not make a new copy of the function


(working of the function does not affect). Only the arguments
are new.

• As each recursive call returns, the old local variables and


parameters are removed from the stack and execution resumes
at the point of the function call inside the function.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Summing up the elements of
an array
Algorithm Design:
1. If we have only one element, then the sum is simple.
2. Otherwise, we use the sum of the first element and the sum
of the rest.

int sum(int first, int last, int array[])


{
if (first == last)
return (array[first]);
return(array[first] + sum(first+1,last,array));
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
For example:
Sum(1 8 3 2) = 1 + Sum(8 3 2) =
8 + Sum(3 2) =
3 + Sum (2) =
2
3+2=5
8 + 5 = 13
1 + 13 = 14

Answer = 14

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Recursive Version of Fibonacci
Series
int fib(int num){

switch(num){
case 0: return 0;
break;
case 1: return 1;
break;

default: return(fib(num - 1) + fib(num - 2));


break;
}
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Analysis
Input Value Number of time fib is called
0 1
1 1
2 3
3 5
4 9
5 15
6 25
7 41
8 67
9 109

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Analysis
factr(4)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Printing in reverse order
/* This function reads a line of text char by char and then
displays the characters in reverse order */

void Reverse(){
char c;
if((c = getchar())!= ‘\n’)
Reverse();
putchar(c);
}

How it will work???

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Pros and Cons
• The recursive versions of most routines may execute a bit slower
than their iterative equivalents because of the overhead of the
repeated function calls.

• In fact, many recursive calls to a function could cause a stack


overrun.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Pros and Cons
• The main advantage to recursive functions is that you can use
them to create clearer and simpler versions of several algorithms.

• For example, the QuickSort is quite difficult to implement in an


iterative way. Also, some problems, especially ones related to
artificial intelligence, lend themselves to recursive solutions.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Precaution
• When writing recursive functions, you must have an if statement
somewhere to force the function to return without the recursive
call being executed.

• If you don't, the function will never return once you call it.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Module 14 – part 2:
The C Preprocessor
BITS Pilani Dr. Amitesh Singh Rajput
Pilani Campus
Department of Computer Science & Information Systems
Module Overview

• C Preprocessor
– Preprocessor Directives

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
The C Preprocessor

• The C Preprocessor is a “Program that processes source program


before it is passed to the compiler”

• Preprocessor commands are called as Directives

• Each directive begins with a # symbol

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
C Program execution

Text editor

C Source Code
Preprocessor
Expanded Source Code
Compiler
Object Code
Linker
Executable Code

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Macro Expansion Directives


Macro Expansion Directives:
Example 1
#define MAX 100
#define SIZE 10
void main()
{
int k, a[SIZE];
for(k=0; k<MAX; k+=10)
printf(“%d”,k);
}

During preprocessing each occurrence of MAX is replaced by 100


and each occurrence of SIZE is replaced by 10.
And then the program is compiled!

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 2 (Define Operators)
#define AND &&
#define OR ||
#define EQUALS ==
#define MOD %
#define NOTEQUAL !=

void Leap_year(unsigned int yr)


{
if((yr MOD 4 EQUALS 0) AND (yr MOD 100 NOTEQUAL 0) OR (yr
MOD 400 EQUALS 0))
printf(“Given Year is Leap Year\n”);
else
printf(“Given Year is Not a Leap Year\n”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 3 (Define Conditions)
#define AND &&
#define OR ||
#define RANGE ((ch>=’a’ AND ch<=‘z’)OR(ch>=’A’ AND
ch<=‘Z’))
void Alpha_Check(char ch)
{
if(RANGE)
printf(“Entered character is an Alphabet\n”);
else
printf(“Entered character not an Alphabet\n”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Macros with Arguments
#define CUBE(x) (x*x*x)

If a statement appears in the program like


vol = CUBE(side);
It will expand to:
vol = (side*side*side);

If a statement appears in the program like


vol = CUBE(x+y);
It will expand to:
vol = (x+y * x+y * x+y);

If a statement appears in the program like


printf(“Volume = CUBE(a)”); Expansion???
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Nesting of Macros
One Macro definition can be used in another Macro

Example:
Consider the Macro Definitions
#define SQUARE(p) (p*p)
#define CUBE(p) (SQUARE(p)*p)
#define EIGHTH(p) (CUBE(p)*CUBE(p)*SQUARE(p))

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Nesting of Macros (Contd.)
Macros calls can be nested as function calls

Consider a Macro definition:

#define MIN(P,Q) (((P<Q))?(P):(Q))

int MinThree(int a, int b, int c)


{
int min;
min = MIN(a, MIN(b,c)); /* Macro Call */
return (min);
}

Exercise:
Write a macro call for getting min of five values.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Advantages of Macros
• One place replacement is required for any changes

• Easy to handle

• Less error prone

• Easy to debug

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Macro vs Function()
• Functions make the program compact and smaller but they slow down the
program
• Each call results in a push on the activation stack.
• The corresponding return is a pop from the stack.

• Macros make the program run faster but increases the program size
• Macros reduce the function call overhead by performing code
replacement at compile time.
• Code replacement happens once (per compilation), whereas function calls
can be repetitive causing performance bottleneck.

Important Questions:
When is it best to use macro?
And when is it best to use function?

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Can we replace all Macros with
functions?
• Macros do not have types (for parameters)
• What will happen if we declare
#define fact(n) (n==0) ? 1 : n*fact(n-1)
• Try this out! Recursive substitutions are not possible because the
compiler will not know when to stop.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

File Inclusion Directives


File Inclusion Directives
How to include a file in your program?

#include “file_name” OR
#include <file_name>

What is the difference between above?


1. If a large program is divided into several files, each containing a set of
related functions. These files should be included at the beginning of the
main program file.
2. Inclusion of header files for using some predefined functions in C library.

When a header file is included, the preprocessor includes the file in the
source code program (.c file) before its compilation.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

You might also like