Mastery 21

 

Recursion is a method used to complete many algorithms such as factorial, fibonacci series, common great divisor and square root of numbers given by the user.It can be used to decrease the amount of lines in a code as well. In recursion, the code does not include any kind of loop as a “for” loop or a “do while” loop. Instead it used anidated conditionals in order to create a form of loop until the program gets to the desired number. Here is an example of factorial of a number recursively. 

# include <iostream>

using namespace std;

 

int fact(int a){

  if(  a == 0) {

   return 1;

 }else {

   a= a*fact(a-1);

 }

}

int main () {

int a;

cout <<“give me a number for the factorial “;

cin>> a;

cout <<“the factorial is “<<fact(a);

}

CC BY 4.0 Mastery 21 by carlos green is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.