SlideShare a Scribd company logo
Recursion Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
Recursion
In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement
within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion
is thus the process of defining something in terms of itself.
Let us now see a simple example of recursion. Suppose we want to calculate the factorial value of
an integer. As we know, the factorial of a number is the product of all the integers between 1 and that
number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’
stands for factorial. Thus factorial of a number can be expressed in the form of itself. Hence this can be
programmed using recursion. However, before we write a recursive function for calculating factorial let
take a look at the non-recursive function for calculating the factorial value of an integer.
main( )
{
int a, fact ;
printf ( "nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = factorial ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
factorial ( int x )
{
int f = 1, i ;
for ( i = x ; i >= 1 ; i-- )
f = f * i ;
return ( f ) ;
}
And here is the output...
Enter any number 3
Factorial value = 6
Following is the recursive version of the function to calculate the factorial value.
main( )
{
int a, fact ;
printf ( "nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
Recursion Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
f = x * rec ( x - 1 ) ;
return ( f ) ;
}
And here is the output for four runs of the program
Enter any number 1
Factorial value = 1
Enter any number 2
Factorial value = 2
Enter any number 5
Factorial value = 120
Let us understand this recursive factorial function thoroughly. In the first run when the number
entered through scanf( ) is 1, let us see what action does rec( ) take. The value of a (i.e. 1) is
copied into x. Since x turns out to be 1 the condition if ( x == 1 ) is satisfied and hence 1 (which
indeed is the value of 1 factorial) is returned through the return statement.
When the number entered through scanf( ) is 2, the ( x == 1 ) test fails, so we reach the
statement, f = x * rec ( x - 1 ) ;
And here is where we meet recursion. How do we handle the expression x * rec ( x - 1 )?
We multiply x by rec ( x - 1 ). Since the current value of x is 2, it is same as saying that we must
calculate the value (2 * rec ( 1 )). We know that the value returned by rec ( 1 ) is 1, so
the expression reduces to (2 * 1), or simply 2. Thus the statement, x * rec ( x - 1 ) ;
evaluates to 2, which is stored in the variable f, and is returned to main( ), where it is duly printed as
Factorial value = 2
In case the value of a is 5, main( ) would call rec( ) with 5 as its actual argument, and rec( ) will send
back the computed value. But before sending the computed value, rec( ) calls rec( ) and waits for a
value to be returned. It is possible for the rec( ) that has just been called to call yet another rec( ), the
argument x being decreased in value by 1 for each of these recursive calls. We speak of this series of
calls to rec( ) as being different invocations of rec( ). These successive invocations of the same function
are possible because the C compiler keeps track of which invocation calls which. These recursive
invocations end finally when the last invocation gets an argument value of 1, which the preceding
invocation of rec( ) now uses to calculate its own f value and so on up the ladder. So we might say what
happens is,
rec ( 5 ) returns ( 5 times rec ( 4 ),
which returns ( 4 times rec ( 3 ),
which returns ( 3 times rec ( 2 ),
which returns ( 2 times rec ( 1 ),
which returns ( 1 ) ) ) ) )
Foxed? Well, that is recursion for you in its simplest garbs. I hope you agree that it’s difficult to
visualize how the control flows from one function call to another. Possibly Figure 5.4 would make
things a bit clearer.
Assume that the number entered through scanf( ) is 3. Using Figure 5.4 let’s visualize what exactly
happens when the recursive function rec( ) gets called. Go through the figure carefully. The first time
when rec( ) is called from main( ), x collects 3. From here, since x is not equal to 1, the if block is
Recursion Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
skipped and rec( ) is called again with the argument ( x – 1 ), i.e. 2. This is a recursive call. Since x is still
not equal to 1, rec( ) is called yet another time, with argument (2 - 1). This time as x is 1, control goes
back to previous rec( ) with the value 1, and f is evaluated as 2.
Similarly, each rec( ) evaluates its f from the returned value, and finally 6 is returned to main( ). The
sequence would be grasped better by following the arrows shown in Figure 5.4. Let it be clear that
while executing the program there do not exist so many copies of the function rec( ). These have been
shown in the figure just to help you keep track of how the control flows during successive recursive
calls.
Recursion may seem strange and complicated at first glance, but it is often the most direct way to
code an algorithm, and once you are familiar with recursion, the clearest way of doing so.

More Related Content

PDF
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 

What's hot (20)

PDF
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
PPTX
C Programming Unit-2
Vikram Nandini
 
PPTX
Operators and expressions in c language
tanmaymodi4
 
PPT
Lecture 11 - Functions
Md. Imran Hossain Showrov
 
PPTX
Decision statements in c language
tanmaymodi4
 
PPT
Lecture 9- Control Structures 1
Md. Imran Hossain Showrov
 
PPT
Lecture 14 - Scope Rules
Md. Imran Hossain Showrov
 
PPT
RECURSION IN C
v_jk
 
PPT
Lecture 8- Data Input and Output
Md. Imran Hossain Showrov
 
PPT
Lecture 12 - Recursion
Md. Imran Hossain Showrov
 
PPTX
C Programming Unit-1
Vikram Nandini
 
PPT
Lecture 10 - Control Structures 2
Md. Imran Hossain Showrov
 
PPT
Lecture 13 - Storage Classes
Md. Imran Hossain Showrov
 
PDF
Pointers in C language
Infinity Tech Solutions
 
PPTX
Getting started in c++
Neeru Mittal
 
DOCX
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
PPTX
C function
thirumalaikumar3
 
PPTX
Programming in C (part 2)
Dr. SURBHI SAROHA
 
PDF
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
C Programming Unit-2
Vikram Nandini
 
Operators and expressions in c language
tanmaymodi4
 
Lecture 11 - Functions
Md. Imran Hossain Showrov
 
Decision statements in c language
tanmaymodi4
 
Lecture 9- Control Structures 1
Md. Imran Hossain Showrov
 
Lecture 14 - Scope Rules
Md. Imran Hossain Showrov
 
RECURSION IN C
v_jk
 
Lecture 8- Data Input and Output
Md. Imran Hossain Showrov
 
Lecture 12 - Recursion
Md. Imran Hossain Showrov
 
C Programming Unit-1
Vikram Nandini
 
Lecture 10 - Control Structures 2
Md. Imran Hossain Showrov
 
Lecture 13 - Storage Classes
Md. Imran Hossain Showrov
 
Pointers in C language
Infinity Tech Solutions
 
Getting started in c++
Neeru Mittal
 
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
C function
thirumalaikumar3
 
Programming in C (part 2)
Dr. SURBHI SAROHA
 
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
Ad

Similar to [ITP - Lecture 14] Recursion (20)

DOCX
PPS 7.7 RECURSION, AS A DIFFERENT WAY OF SOLVING PROBLEMS. EXAMPLE PROGRAMS
Sitamarhi Institute of Technology
 
PPTX
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
PDF
Composition birds-and-recursion
David Atchley
 
PPTX
Unit-I Recursion.pptx
ajajkhan16
 
PPT
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
PDF
Python_Module_2.pdf
R.K.College of engg & Tech
 
PDF
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
PPTX
Working with functions.pptx. Hb.
sabarivelan111007
 
PPTX
1. DSA - Introduction.pptx
hara69
 
PPTX
Dti2143 chapter 5
alish sha
 
PDF
Functional Programming by Examples using Haskell
goncharenko
 
PDF
14. Recursion.pdf
VivekBhimajiyani
 
PDF
Java Code The traditional way to deal with these in Parsers is the .pdf
stopgolook
 
PPT
Recursion in C
v_jk
 
PDF
Recursion.pdf
Flavia Tembo Kambale
 
DOC
Functions
zeeshan841
 
DOC
C aptitude.2doc
Srikanth
 
DOC
Captitude 2doc-100627004318-phpapp01
ManjeeraBhargavi Varanasi
 
PPS 7.7 RECURSION, AS A DIFFERENT WAY OF SOLVING PROBLEMS. EXAMPLE PROGRAMS
Sitamarhi Institute of Technology
 
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Composition birds-and-recursion
David Atchley
 
Unit-I Recursion.pptx
ajajkhan16
 
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Python_Module_2.pdf
R.K.College of engg & Tech
 
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Working with functions.pptx. Hb.
sabarivelan111007
 
1. DSA - Introduction.pptx
hara69
 
Dti2143 chapter 5
alish sha
 
Functional Programming by Examples using Haskell
goncharenko
 
14. Recursion.pdf
VivekBhimajiyani
 
Java Code The traditional way to deal with these in Parsers is the .pdf
stopgolook
 
Recursion in C
v_jk
 
Recursion.pdf
Flavia Tembo Kambale
 
Functions
zeeshan841
 
C aptitude.2doc
Srikanth
 
Captitude 2doc-100627004318-phpapp01
ManjeeraBhargavi Varanasi
 
Ad

More from Muhammad Hammad Waseem (19)

PDF
[ITP - Lecture 08] Decision Control Structures (If Statement)
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 09,10,11] Class Members & their Accessing
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 08] Encapsulation (Information Hiding)
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 06] Classes and Objects
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 03] Programming Paradigms
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 02] Why do we need OOP
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 01] Introduction to OOP
Muhammad Hammad Waseem
 
PPTX
Data Structures - Lecture 10 [Graphs]
Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
Muhammad Hammad Waseem
 
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Muhammad Hammad Waseem
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
[OOP - Lec 09,10,11] Class Members & their Accessing
Muhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
Muhammad Hammad Waseem
 
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
[OOP - Lec 06] Classes and Objects
Muhammad Hammad Waseem
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
[OOP - Lec 03] Programming Paradigms
Muhammad Hammad Waseem
 
[OOP - Lec 02] Why do we need OOP
Muhammad Hammad Waseem
 
[OOP - Lec 01] Introduction to OOP
Muhammad Hammad Waseem
 
Data Structures - Lecture 10 [Graphs]
Muhammad Hammad Waseem
 

Recently uploaded (20)

PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
High Ground Student Revision Booklet Preview
jpinnuck
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
High Ground Student Revision Booklet Preview
jpinnuck
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
Landforms and landscapes data surprise preview
jpinnuck
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 

[ITP - Lecture 14] Recursion

  • 1. Recursion Intro to Programming MUHAMMAD HAMMAD WASEEM 1 Recursion In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself. Let us now see a simple example of recursion. Suppose we want to calculate the factorial value of an integer. As we know, the factorial of a number is the product of all the integers between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for factorial. Thus factorial of a number can be expressed in the form of itself. Hence this can be programmed using recursion. However, before we write a recursive function for calculating factorial let take a look at the non-recursive function for calculating the factorial value of an integer. main( ) { int a, fact ; printf ( "nEnter any number " ) ; scanf ( "%d", &a ) ; fact = factorial ( a ) ; printf ( "Factorial value = %d", fact ) ; } factorial ( int x ) { int f = 1, i ; for ( i = x ; i >= 1 ; i-- ) f = f * i ; return ( f ) ; } And here is the output... Enter any number 3 Factorial value = 6 Following is the recursive version of the function to calculate the factorial value. main( ) { int a, fact ; printf ( "nEnter any number " ) ; scanf ( "%d", &a ) ; fact = rec ( a ) ; printf ( "Factorial value = %d", fact ) ; } rec ( int x ) { int f ; if ( x == 1 ) return ( 1 ) ; else
  • 2. Recursion Intro to Programming MUHAMMAD HAMMAD WASEEM 2 f = x * rec ( x - 1 ) ; return ( f ) ; } And here is the output for four runs of the program Enter any number 1 Factorial value = 1 Enter any number 2 Factorial value = 2 Enter any number 5 Factorial value = 120 Let us understand this recursive factorial function thoroughly. In the first run when the number entered through scanf( ) is 1, let us see what action does rec( ) take. The value of a (i.e. 1) is copied into x. Since x turns out to be 1 the condition if ( x == 1 ) is satisfied and hence 1 (which indeed is the value of 1 factorial) is returned through the return statement. When the number entered through scanf( ) is 2, the ( x == 1 ) test fails, so we reach the statement, f = x * rec ( x - 1 ) ; And here is where we meet recursion. How do we handle the expression x * rec ( x - 1 )? We multiply x by rec ( x - 1 ). Since the current value of x is 2, it is same as saying that we must calculate the value (2 * rec ( 1 )). We know that the value returned by rec ( 1 ) is 1, so the expression reduces to (2 * 1), or simply 2. Thus the statement, x * rec ( x - 1 ) ; evaluates to 2, which is stored in the variable f, and is returned to main( ), where it is duly printed as Factorial value = 2 In case the value of a is 5, main( ) would call rec( ) with 5 as its actual argument, and rec( ) will send back the computed value. But before sending the computed value, rec( ) calls rec( ) and waits for a value to be returned. It is possible for the rec( ) that has just been called to call yet another rec( ), the argument x being decreased in value by 1 for each of these recursive calls. We speak of this series of calls to rec( ) as being different invocations of rec( ). These successive invocations of the same function are possible because the C compiler keeps track of which invocation calls which. These recursive invocations end finally when the last invocation gets an argument value of 1, which the preceding invocation of rec( ) now uses to calculate its own f value and so on up the ladder. So we might say what happens is, rec ( 5 ) returns ( 5 times rec ( 4 ), which returns ( 4 times rec ( 3 ), which returns ( 3 times rec ( 2 ), which returns ( 2 times rec ( 1 ), which returns ( 1 ) ) ) ) ) Foxed? Well, that is recursion for you in its simplest garbs. I hope you agree that it’s difficult to visualize how the control flows from one function call to another. Possibly Figure 5.4 would make things a bit clearer. Assume that the number entered through scanf( ) is 3. Using Figure 5.4 let’s visualize what exactly happens when the recursive function rec( ) gets called. Go through the figure carefully. The first time when rec( ) is called from main( ), x collects 3. From here, since x is not equal to 1, the if block is
  • 3. Recursion Intro to Programming MUHAMMAD HAMMAD WASEEM 3 skipped and rec( ) is called again with the argument ( x – 1 ), i.e. 2. This is a recursive call. Since x is still not equal to 1, rec( ) is called yet another time, with argument (2 - 1). This time as x is 1, control goes back to previous rec( ) with the value 1, and f is evaluated as 2. Similarly, each rec( ) evaluates its f from the returned value, and finally 6 is returned to main( ). The sequence would be grasped better by following the arrows shown in Figure 5.4. Let it be clear that while executing the program there do not exist so many copies of the function rec( ). These have been shown in the figure just to help you keep track of how the control flows during successive recursive calls. Recursion may seem strange and complicated at first glance, but it is often the most direct way to code an algorithm, and once you are familiar with recursion, the clearest way of doing so.