Class 10 Exam  >  Class 10 Notes  >  C++ Programming for Beginners  >  C++ Recursion

C++ Recursion | C++ Programming for Beginners - Class 10 PDF Download

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 | C++ Programming for Beginners - Class 10 is a part of the Class 10 Course C++ Programming for Beginners.
All you need of Class 10 at this link: Class 10
15 videos|20 docs|13 tests

Top Courses for Class 10

15 videos|20 docs|13 tests
Download as PDF
Explore Courses for Class 10 exam

Top Courses for Class 10

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

C++ Recursion | C++ Programming for Beginners - Class 10

,

Semester Notes

,

mock tests for examination

,

Objective type Questions

,

Extra Questions

,

C++ Recursion | C++ Programming for Beginners - Class 10

,

shortcuts and tricks

,

pdf

,

MCQs

,

Exam

,

Free

,

ppt

,

Previous Year Questions with Solutions

,

Viva Questions

,

C++ Recursion | C++ Programming for Beginners - Class 10

,

study material

,

past year papers

,

video lectures

,

practice quizzes

,

Sample Paper

,

Summary

,

Important questions

;