Table of contents
Our previous article presented various selection statements provided by the Java (and C#) language. We discussed how they can be used to change the flow of execution of a program according to the evaluation of a condition, usually a boolean expression.
In this article, we will learn about a new type of language construct—known as iteration statement—that allows the repeated execution of a block of instructions according to the outcome of the evaluation of a boolean expression.
Suppose we want to create a basic program that displays a sequence of numbers, 1 through 3. This can be accomplished with the following code snippet.
public static void main(String[] args)
{
System.out.println("Number :" + 1);
System.out.println("Number :" + 2);
System.out.println("Number :" + 3);
}
The above program works perfectly well if we need to print a short sequence of numbers on the screen. However, if we were required to print the sequence of all integer numbers from 1 to 1000, the usage of 1000 of System.out.println
instructions would not be practical. Iterative statements—also known as loops—would instead be the right way to write that program.
While selection statements allow the execution of a block of instructions according to the evaluation of a given condition, loops can be used to repeat the execution of a block of instructions under a specific condition. The block of statements executed within a loop is known as the body of the loop.
Java and C# provide different types of iteration statements. This article will present both the while
and the for
loops.
while loop
The following snippet of code describes the syntax of the while
loop.
while (CONDITION)
{
// block: statements executed in each iteration
}
It may be noticed how this is similar to the syntax of the if
selection statement, with a CONDITION specified between parenthesis and a block of instructions enclosed between curly braces. However, with the if
statement, a given block of instructions is executed zero or one time, according to the result of the evaluation of the associated condition. With a while
loop, a block of instructions can repeatedly be executed through different iterations while the specified condition remains true
.
In computer programming, a loop counter is a control variable that manages the iterations of a loop. It typically takes on a sequence of integer values in a specific pattern (for instance, starting at 0 and increasing by 1 until it reaches 10). As the loop progresses, the counter changes to provide a distinct value for each iteration. The loop counter is crucial in determining when the loop should end and allowing the program to move on to the next instruction after the loop.
To understand how a while
loop works, let's use it to write a program that solves the simple problem discussed earlier, i.e., printing the first N (e.g., 3, 4, 5, or 1000) natural numbers on the screen.
public static void main(String[] args)
{
int i = 0;
int N = 3;
while (i < N)
{
System.out.println("Number: " + (i + 1));
i = i + 1;
}
System.out.println("Done!");
}
To simplify the discussion, we consider the case where N = 3
; however, the program can work for any value of N
using proper initialisation. When the above program is started, the following steps are executed.
Loop Counter Initialisation: int i = 0;
initialises an integer variable i
and sets it to 0. This variable will serve as the loop counter.
Loop Initialisation: The while
loop begins, and the condition i < 3
is checked. Since i
is initially 0, the condition is true
, and the loop body is entered.
Loop Body (1st Iteration):
System.out.println("Number: " + (i + 1));
is executed. This line prints the current value ofi
plus 1, which is "Number: 1" becausei
is 0 in the first iteration.i = i + 1;
increments the value ofi
by 1, soi
becomes 1.
Loop Iteration (2nd Iteration):
The condition
i < 3
is re-evaluated.i
is now 1, which is still less than 3, so the condition istrue
.The loop body executes again:
System.out.println("Number: " + (i + 1));
prints "Number: 2" becausei
is 1 in the second iteration.i = i + 1;
incrementsi
to 2.
Loop Iteration (3rd Iteration):
The condition
i < 3
is checked again.i
is now 2, which is still less than 3, so the condition remainstrue
.The loop body is executed once more:
System.out.println("Number: " + (i + 1));
prints "Number: 3" becausei
is 2 in the third iteration.i = i + 1;
incrementsi
to 3.
Loop Termination: After the third iteration, the condition i < 3
is checked again. This time, i
is 3, which is not less than 3, so the condition is false
.
Exiting the Loop: Since the condition is false
, the loop exits and the program continues with the next line of code.
Final Output: System.out.println("Done!");
is executed, and the message "Done!" is printed to the console.
In summary, this code is designed to utilise a while
loop that will execute a specific code block repeatedly as long as the loop counter i
remains less than 3. During each iteration, i
is incremented, and the value of i + 1
is printed. Eventually, the loop will end once i
reaches 3, and the message "Done!" will be displayed on the console to signal the completion of the loop.
for loop
Like while
loops, for
loops are control flow structures that allow the execution of a block of code repeatedly. However, these iterative instructions differ in their syntax and use cases. The for
loops are especially useful when it is already known how many times a particular task needs to be repeated. They have a structured syntax comprising three main parts, as presented in the following code snippet.
for (Initialisation; CONDITION; Update)
{
// block: statements executed in each iteration
}
Initialisation: Is the part where the loop control variable is set up and given an initial value. It typically includes declaring and initialising a variable used as the loop counter.
CONDITION: This part defines a condition checked before each loop iteration. Like in the
while
loop, if the condition istrue
, the loop continues to execute; iffalse
, the loop terminates.Update: This part specifies how the loop control variable—the loop counter—is updated after each iteration. It is responsible for ensuring that the loop eventually terminates by changing the control variable in a predictable way.
The previous program that prints the first N
natural numbers (with N = 3
) is rewritten below using a for
loop.
public static void main(String[] args)
{
int N = 3;
for (int i = 0; i < N; i = i + 1)
{
System.out.println("Number: " + (i + 1));
}
System.out.println("Done!");
}
When the program is started, the following steps are executed.
Initialisation (int i = 0
): The loop control variable i
is initialised to 0. This is the first step in the for
loop.
Condition Check (i < 3
): The condition i < 3
is checked before each iteration. In the first iteration, i
is 0, which is less than 3, so the condition is true
—the loop proceeds.
Loop Body (System.out.println("Number: " + (i + 1))
): The code inside the loop body is executed. It prints "Number: " followed by the value of i + 1
, 1 in the first iteration.
Update (i = i + 1
): The loop control variable i
is incremented by 1 (i = i + 1
) after each iteration. So, i
becomes 1.
Second Iteration:
Condition Check: The condition
i < 3
is checked again. Now,i
is 1, which is still less than 3, so the condition istrue
for the second iteration.Loop Body: The code inside the loop body is executed again. It prints "Number: 2" because
i
is 1 in the second iteration.Update:
i
is incremented by 1 again, becoming 2.
Third Iteration:
Condition Check: The condition
i < 3
is checked once more.i
is now 2, which is still less than 3, so the condition istrue
for the third iteration.Loop Body: The code inside the loop body is executed. It prints "Number: 3" because
i
is 2 in the third iteration.Update:
i
is incremented by 1, becoming 3.
Fourth Iteration:
- Condition Check: The condition
i < 3
is checked again. Now,i
is 3, which is not less than 3. The condition isfalse
, so the loop terminates.
Exiting the Loop: Since the condition is false
, the loop exits and the program continues with the next line of code.
Final Output: System.out.println("Done!");
is executed and prints "Done!" to the console.
The for loop in this code behaves similarly to the while loop in the previous program but provides a more concise and structured way of handling the loop control variables using the initialisation, condition, and update parts.
Loops in C
The above while
and for
loop statements can be used in C# with similar syntax. The difference is the name of the program entry point, which is Main
instead of main
, and the use of Console.WriteLine
to print messages on the console instead of System.out.println
.
static void Main(string[] args)
{
int i = 0;
int N = 3;
while (i < N)
{
Console.WriteLine("Number: " + (i + 1));
i = i + 1;
}
Console.WriteLine("Done!");
}
For-each Loop
A type of loop used to iterate over all the elements of Collections, such as arrays or lists, is called for-each and is described in this article with the concept of array.