Recursion and Iteration

Iteration uses one of the language constructs for, while, or do-while, as discussed in Chapter 9, “Flow of Control Part II: Iteration Statements.” Any computational problem that can be solved by using recursion also can be solved solely through iteration. For example, the Factorial method contained in Listing 23.4 uses a for loop construct to calculate the factorial and, thereby, uses iteration instead of recursion as in Listing 23.3.

Listing 23.4. IterativeFactorial.cs
 01: using System; 02: 03: class Math 04: { 05: public static long Factorial(long number) 06: { 07: long factorial = 1; 08: 09: for(long i = number; i >= 1; i--) 10: { 11: factorial *= i; 12: } 13: return factorial; 14: } 15: } 16: 17: class Tester 18: ...

Get C# Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.