Recursion in C - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

Recursion in C

Description:

A recursive function has two parts: the terminal/base case. - a stopping condition ... int fact(int n) if (n 2) // terminal case. return 1; else // recursive step ... – PowerPoint PPT presentation

Number of Views:101
Avg rating:3.0/5.0
Slides: 10
Provided by: acsd4
Category:
Tags: fact | recursion

less

Transcript and Presenter's Notes

Title: Recursion in C


1
Recursion in C
2
Recursion
  • Recursive tasks
  • A task that is defined in terms of itself.
  • A function that calls itself.
  • With each invocation, the problem is reduced to a
    smaller task (reducing case) until the task
    arrives at some terminal case.

3
Recursive Functions
  • A recursive function has two parts
  • the terminal/base case.
  • - a stopping condition
  • the reducing case/recursive step
  • an expression of the computation or definition in
    terms of itself

4
General algorithm for recursion
  • if (!terminal_condition)
  • reducing_case
  • if (terminal_condition)
  • terminal_case
  • else
  • reducing_case

5
The Factorial Function
  • n! n (n-1) (n -2) 2 1
  • 5! 5 4 3 2 1
  • The same function can be defined recursively as
    fallows
  • 0! 1 terminal case
  • n! n (n - 1)! - the reducing case

6
The Factorial Function
  • 5! 5 4!
  • 4! 4 3!
  • 3! 3 2!
  • 2! 2 1!
  • 1! 1! 0!
  • 0! 1 - Terminal Case

Reducing Case
7
Recursive Factorial Function in C
  • int fact(int n)
  • if (n lt 2) // terminal case
    return 1 else //
    recursive step return (n fact(n - 1))

8
  • include ltiostreamgt
  • include ltcstdlibgt
  • using namespace std
  • int sum_of (int ary , int num)
  • int main ()
  • int ary 5 5, 10, 15, 20, 25
  • int num 5
  • int ans
  • ans sum_of (ary, num)
  • coutltlt"\nThe sum of the elements of the array is
    "ltltans
  • system("pause")
  • return EXIT_SUCCESS
  • int sum_of (int ary , int num)

9
int ary 5 5, 10, 15, 20, 25
  • Descending - num is 5
  • Descending - num is 4
  • Descending - num is 3
  • Descending - num is 2
  • Descending - num is 1 At the ladder bottom - num
    is 0
  • Ascending - num is 1 sum is 5
  • Ascending - num is 2 sum is 15
  • Ascending - num is 3 sum is 30
  • Ascending - num is 4 sum is 50
  • Ascending - num is 5 sum is 75
Write a Comment
User Comments (0)
About PowerShow.com