While loops

While Loop in Computer Programming

The while loop is a fundamental control flow statement in computer programming that repeatedly executes a block of code as long as a given condition is true. It's used for iterative tasks when the number of iterations isn't known before the loop starts. The loop includes a condition that is evaluated before each iteration, and if the condition evaluates to false, the loop terminates and control passes to the next statement following the loop.

Example in Python

In Python, a while loop syntax is straightforward. Here's a basic example that prints numbers from 1 to 5.

counter = 1
while counter <= 5:
    print(counter)
    counter += 1

Example in C#

Similarly, in C#, a while loop can perform the same task. Below is a simple example that demonstrates iterating from 1 to 5.

int counter = 1;
while (counter <= 5)
{
    Console.WriteLine(counter);
    counter++;
}

Last updated

Was this helpful?