A recursive program is a kind of program that is compact. It allows a program to define things upon themselves by using a kind of stack. In the case of factorials, this means it allows the program to take in a variable and multiply it by one less than itself until it reaches one, then send to back out of the recursive stack back to the code and say “ this is the factorial of this variable.
namespace Recursive_summative { class Program { static void Main(string[] args) { int n = 4; int value = Factorial(n); Console.WriteLine("n"); Console.ReadLine; } static int Factorial(int n) { if (n < 0) // Throw Exception #This makes it so that when n<0 the program just doesn't go if (n == 0) return 0; # Makes the program’s variable 0 if (n == 1) return 1; # Makes the programs variable 1 return n * Factorial(n - 1); #the recursion part of the code. N (the variable) is multiplied by itself minus 1 until it reaches one and then sends the stack back into the program } } }
Iterative loops are somewhat different. If a recursive program stacks on itself creating a loop inside, an iterative program loops out of the program. It has to use more variables to create and answer setting variables as variable multiplied by a different variable to get the answer.
In the example of using factorials Int factorial(n) ( Int value = n for (int i = n-1; i >0, i--) # sets the interval i to be n-1 as long as i is bigger than zero value = value*i # makes the program multiply on itself as long as there is an i value to do so, then sends the complete value to the top of the code return value;