Class 8  >  C++ Programming for Beginners  >  C++ Recursion

C++ Recursion - Notes | Study C++ Programming for Beginners - Class 8

1 Crore+ students have signed up on EduRev. Have you?
Recursion
  • Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
  • Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.
Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

Example

int sum(int k) {

  if (k > 0) {

    return k + sum(k - 1);

  } else {

    return 0;

  }

}


int main() {

  int result = sum(10);

  cout << result;

  return 0;

}

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

10 + sum(9)

10 + ( 9 + sum(8) )

10 + ( 9 + ( 8 + sum(7) ) )

...

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns the result.

The document C++ Recursion - Notes | Study C++ Programming for Beginners - Class 8 is a part of the Class 8 Course C++ Programming for Beginners.
All you need of Class 8 at this link: Class 8
15 videos|20 docs|13 tests
Download as PDF

Download free EduRev App

Track your progress, build streaks, highlight & save important lessons and more!

Related Searches

study material

,

C++ Recursion - Notes | Study C++ Programming for Beginners - Class 8

,

Important questions

,

Viva Questions

,

Previous Year Questions with Solutions

,

mock tests for examination

,

C++ Recursion - Notes | Study C++ Programming for Beginners - Class 8

,

video lectures

,

MCQs

,

pdf

,

Extra Questions

,

ppt

,

C++ Recursion - Notes | Study C++ Programming for Beginners - Class 8

,

Semester Notes

,

Exam

,

practice quizzes

,

past year papers

,

Objective type Questions

,

Summary

,

shortcuts and tricks

,

Free

,

Sample Paper

;