O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required