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
sqrt
function from theMath
library to determine the maximum divisor needed, which optimizes our checks. - Line 16: The
while
loop checks two conditions:isPrime
must remaintrue
, and the currentdivisor
should not exceedmaxDivisor
. - Line 18: If the number is divisible by
divisor
, it is not prime, andisPrime
is 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 ... while
loop ensures that the calculation occurs at least once. - We multiply
factorial
by the input valuen
and then decrementn
until it reaches 0. - The
ulong
type is used to accommodate larger numbers, but be aware that factorial values grow quickly and can lead to overflow. Consider usingBigInteger
fromSystem.Numerics
for 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 thebreak
condition is met. - We use the formula
(approximateValue + n / approximateValue) / 2
to 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
for
loop initializesi
to1
and continues as long asi
is less than or equal to10
, incrementingi
by1
in each iteration. - This concise structure is ideal for cases where the number of iterations is known.