Iteration Examples
Let’s explore some examples that require the use of iteration, loops, in C#. Each example illustrates a different loop construct and its application.
Example 1: Prime Numbers
This program calculates whether a given number is prime. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. We can check if a number, num, is prime by dividing it by all integers between 2 and the square root of num. Here’s how the program works:
Explanation
- Lines 10-14: Initialize variables and retrieve user input. We use the
sqrtfunction from theMathlibrary to determine the maximum divisor needed, which optimizes our checks. - Line 16: The
whileloop checks two conditions:isPrimemust remaintrue, and the currentdivisorshould not exceedmaxDivisor. - Line 18: If the number is divisible by
divisor, it is not prime, andisPrimeis set tofalse.
Note
The break operator can be useful for exiting the loop prematurely if needed.
Example 2: Factorial Calculation
The factorial of a number n, denoted as n!, is the product of all positive integers from 1 to n. We can use a loop to calculate this:
Explanation
- The
do ... whileloop ensures that the calculation occurs at least once. - We multiply
factorialby the input valuenand then decrementnuntil it reaches 0. - The
ulongtype is used to accommodate larger numbers, but be aware that factorial values grow quickly and can lead to overflow. Consider usingBigIntegerfromSystem.Numericsfor very large values.
Example 3: Approximation of a Square Root
In this example, we approximate the square root of a number using an iterative method. The loop uses while(true) to continuously refine the approximation until a specified accuracy is achieved:
Explanation
- The
while(true)loop continues indefinitely until thebreakcondition is met. - We use the formula
(approximateValue + n / approximateValue) / 2to calculate a better approximation of the square root. - The loop exits when the difference between the old and new approximations is less than
0.001.
Example 4: Using a For Loop
Here’s an example of using a for loop to print numbers from 1 to 10:
Explanation:
- The
forloop initializesito1and continues as long asiis less than or equal to10, incrementingiby1in each iteration. - This concise structure is ideal for cases where the number of iterations is known.