In this article
- What is a loop?
- How does while work?
- How does for work?
- What are a counter and an accumulator?
- How do you use loops in Python, PHP and C?
- What are break and continue for?
- What is do-while?
- What do other languages call loops?
- Now you ask: which loop should I use?
- What is an infinite loop?
- What are the most common mistakes with loops?
- Now it’s your turn!
A loop is the command that makes the program run the same block of instructions several times, while a condition is true. The two loops that exist in all three languages of this blog are called while and for.
This article brings together two pieces you already have. From variables comes the counter, which changes on every lap. From the if statement comes the test that decides whether the loop goes on. With loops, you can go through entire arrays and matrices in just a few lines.
Think of the sink after lunch. Nobody writes “wash dish 1, wash dish 2, wash dish 3”. There’s a single instruction: while there’s a dirty dish, wash a dish. It works for 3 dishes or for 30. Another way to repeat is the training kind: run 10 laps around the court. Here you already know the number of laps before you start. The while is the sink. The for is the court.

What is a loop?
A loop lets a sequence of commands run over and over, while certain conditions are met. Each run of the block is called a lap, or an iteration. Computers are often used to repeat tasks, either until something happens or a fixed number of times.
How does while work?
The while has a condition and a block, like the if. The difference is in what happens after the block: the program goes back and tests the condition again.
- The condition is evaluated at the start of each lap.
- If it’s true, the block runs and the program returns to the test.
- If it’s false, the loop ends. If it’s already false the first time, the block doesn’t run even once.

How does for work?
The for in C and in PHP gathers in one line the three things every loop with a counter needs: the start, the condition and the step.
for (start; condition; step) for (n = 1; n <= 100; n++)
- Start: runs only once, before the first lap.
- Condition: tested at the beginning of each lap. While it’s true, the loop goes on.
- Step: runs at the end of each lap. It usually updates the counter. The
n++is a short way of writingn = n + 1.
Python’s for is different: it goes through the items of a sequence, in the order they appear. To count, you use the range function. IMPORTANT: the end point of range is never included. range(5) generates 0, 1, 2, 3 and 4. To go from 1 to 100, you write range(1, 101).
What are a counter and an accumulator?
They’re two roles a variable can play inside a loop. The counter goes up by 1 at a time and answers “how many?”. The accumulator adds a different value on each lap and answers “what’s the total?”. Both need an initial value before the loop, usually 0.

See the animation of the loop adding 1 to 5

How do you use loops in Python, PHP and C?
The program has six numbered sections: while, for with an accumulator, counter, break, continue and a loop inside another loop.
Python:
# Loops: while, for, break and continue
# 1. while: repeats while the condition is true
i = 1
while i <= 5:
print("lap", i)
i = i + 1 # without this line, the loop never ends
# 2. for: the same counter, with start, limit and step in a single line
total = 0
for n in range(1, 101): # from 1 to 100; the 101 is left out
total = total + n # accumulator: keeps the running total
print("sum of 1 to 100:", total)
# 3. counter: how many values pass a test
grades = [7.5, 4.0, 9.0, 6.0, 3.5, 8.0]
passing = 0
for grade in grades:
if grade >= 6:
passing = passing + 1
print("passing grades:", passing, "of", len(grades))
# 4. break: leaves the loop before the end
number = 50
while True:
if number % 7 == 0:
break
number = number + 1
print("first multiple of 7 from 50:", number)
# 5. continue: skips the rest of this lap and goes to the next one
line = ""
for n in range(1, 11):
if n % 3 == 0:
continue
line = line + str(n) + " "
print("1 to 10 without the multiples of 3:", line)
# 6. loop inside a loop: for each row, all the columns
for row in range(1, 4):
text = ""
for column in range(1, 4):
text = text + "%d x %d = %d " % (row, column, row * column)
print(text)
PHP:
<?php
// Loops: while, for, break and continue
// 1. while: repeats while the condition is true
$i = 1;
while ($i <= 5) {
echo "lap $i\n";
$i = $i + 1; // without this line, the loop never ends
}
// 2. for: the same counter, with start, limit and step in a single line
$total = 0;
for ($n = 1; $n <= 100; $n++) { // from 1 to 100
$total = $total + $n; // accumulator: keeps the running total
}
echo "sum of 1 to 100: $total\n";
// 3. counter: how many values pass a test
$grades = [7.5, 4.0, 9.0, 6.0, 3.5, 8.0];
$passing = 0;
foreach ($grades as $grade) {
if ($grade >= 6) {
$passing = $passing + 1;
}
}
echo "passing grades: $passing of " . count($grades) . "\n";
// 4. break: leaves the loop before the end
$number = 50;
while (true) {
if ($number % 7 == 0) {
break;
}
$number = $number + 1;
}
echo "first multiple of 7 from 50: $number\n";
// 5. continue: skips the rest of this lap and goes to the next one
$line = "";
for ($n = 1; $n <= 10; $n++) {
if ($n % 3 == 0) {
continue;
}
$line = $line . $n . " ";
}
echo "1 to 10 without the multiples of 3: $line\n";
// 6. loop inside a loop: for each row, all the columns
for ($row = 1; $row <= 3; $row++) {
$text = "";
for ($column = 1; $column <= 3; $column++) {
$text = $text . sprintf("%d x %d = %d ", $row, $column, $row * $column);
}
echo $text . "\n";
}
C:
/* Loops: while, for, break and continue */
#include <stdio.h>
int main(void) {
/* 1. while: repeats while the condition is true */
int i = 1;
while (i <= 5) {
printf("lap %d\n", i);
i = i + 1; /* without this line, the loop never ends */
}
/* 2. for: the same counter, with start, limit and step in a single line */
int total = 0;
for (int n = 1; n <= 100; n++) { /* from 1 to 100 */
total = total + n; /* accumulator: keeps the running total */
}
printf("sum of 1 to 100: %d\n", total);
/* 3. counter: how many values pass a test */
double grades[] = {7.5, 4.0, 9.0, 6.0, 3.5, 8.0};
int count = 6, passing = 0;
for (int k = 0; k < count; k++) {
if (grades[k] >= 6) {
passing = passing + 1;
}
}
printf("passing grades: %d of %d\n", passing, count);
/* 4. break: leaves the loop before the end */
int number = 50;
while (1) {
if (number % 7 == 0) {
break;
}
number = number + 1;
}
printf("first multiple of 7 from 50: %d\n", number);
/* 5. continue: skips the rest of this lap and goes to the next one */
printf("1 to 10 without the multiples of 3: ");
for (int n = 1; n <= 10; n++) {
if (n % 3 == 0) {
continue;
}
printf("%d ", n);
}
printf("\n");
/* 6. loop inside a loop: for each row, all the columns */
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
printf("%d x %d = %d ", row, column, row * column);
}
printf("\n");
}
return 0;
}
Output:
lap 1 lap 2 lap 3 lap 4 lap 5 sum of 1 to 100: 5050 passing grades: 4 of 6 first multiple of 7 from 50: 56 1 to 10 without the multiples of 3: 1 2 4 5 7 8 10 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
Same output in all three languages. Focus on the concept, not the language!
In section 3, notice that Python and PHP go through the list of grades directly, without talking about positions. PHP has its own command for that, foreach. In C, the loop goes through the indexes from 0 to 5 and fetches each grade by its position.
In section 6, the inner loop does its three full laps for each lap of the outer loop. That’s 3 x 3 = 9 runs of the innermost block. Got it? That’s how you go through a matrix.
What are break and continue for?
- break: ends the loop right away, and execution moves to the first command after it. In section 4, you don’t know in advance how many laps will be needed. The loop runs until it finds 56 and leaves.
- continue: skips the rest of the current lap and moves on to the next one. In section 5, the multiples of 3 are skipped, but the loop goes on until 10.
When there are nested loops, break leaves only the innermost loop it’s in.
What is do-while?
C and PHP have a third loop. In do-while, the condition is checked at the end of each lap, not at the beginning. As a result, the block always runs at least once.
/* do-while: the block runs before the test */
#include <stdio.h>
int main(void) {
int attempts = 0;
int pin = 0;
do {
attempts = attempts + 1;
pin = pin + 1234; /* simulates the PIN typed on each attempt */
printf("attempt %d: PIN %d\n", attempts, pin);
} while (pin != 3702);
printf("got it right after %d attempts\n", attempts);
int counter = 10;
while (counter < 5) { /* the condition starts out false: no laps */
printf("while: never shows up\n");
}
do { /* the test comes at the end: one lap happens */
printf("do-while: ran once with counter = %d\n", counter);
} while (counter < 5);
return 0;
}
Output:
attempt 1: PIN 1234 attempt 2: PIN 2468 attempt 3: PIN 3702 got it right after 3 attempts do-while: ran once with counter = 10
The last line shows the difference. With the counter at 10, the condition counter < 5 is false from the start. The while didn’t do a single lap. The do-while did one.
In Python, the repetition commands are while and for. The effect of “run first, test later” is achieved with while True and a break, as in section 4.
What do other languages call loops?
Python, PHP and C use almost the same names: while, for and do-while. In other languages used in the industry, the loop gets other names, and some rules change along with them. The seven languages below are on the language list of Stack Overflow’s 2025 developer survey. Kotlin is the language Google recommends for starting an Android app, and VBA, which runs inside Excel and the other Office programs, uses the same For … Next and the same Do … Loop as Visual Basic.
The program does the same three things in all seven languages: it repeats a phrase 3 times, counts from 5 down to 1 and repeats the PIN attempt from the do-while until it gets it right. Switch languages in the tabs of the code box.
// Loops in Go: there is only for
package main
import "fmt"
func main() {
// Repeat 3 times: for range 3 (Go 1.22 or newer)
for range 3 {
fmt.Print("Knock! ")
}
fmt.Println("Who is it?")
// Count from 5 down to 1: for with only the condition is Go's while
i := 5
for i >= 1 {
fmt.Print(i, " ")
i--
}
fmt.Println("Liftoff!")
// Repeat until it's right: for with no condition is an endless loop, and break ends it
attempts := 0
pin := 0
for {
attempts++
pin += 1234 // simulates the PIN typed on each attempt
fmt.Printf("attempt %d: PIN %d\n", attempts, pin)
if pin == 3702 {
break
}
}
fmt.Printf("got it right after %d attempts\n", attempts)
}
// Loops in Kotlin: repeat, downTo and do-while
fun main() {
// Repeat 3 times: repeat is a function, not a keyword
repeat(3) {
print("Knock! ")
}
println("Who is it?")
// Count from 5 down to 1: the range 5 downTo 1 counts backward
for (i in 5 downTo 1) {
print("$i ")
}
println("Liftoff!")
// Repeat until it's right: the same do-while as in C
var attempts = 0
var pin = 0
do {
attempts++
pin += 1234 // simulates the PIN typed on each attempt
println("attempt $attempts: PIN $pin")
} while (pin != 3702)
println("got it right after $attempts attempts")
}
// Loops in Rust: for with ranges and loop with a value
fn main() {
// Repeat 3 times: 0..3 goes from 0 to 2 (the 3 is left out)
for _ in 0..3 {
print!("Knock! ");
}
println!("Who is it?");
// Count from 5 down to 1: 1..=5 includes the 5, and rev() reverses the order
for i in (1..=5).rev() {
print!("{i} ");
}
println!("Liftoff!");
// Repeat until it's right: loop is the endless loop, and break hands back a value
let mut lap = 0;
let mut pin = 0;
let attempts = loop {
lap += 1;
pin += 1234; // simulates the PIN typed on each attempt
println!("attempt {lap}: PIN {pin}");
if pin == 3702 {
break lap;
}
};
println!("got it right after {attempts} attempts");
}
# Loops in Ruby: times, downto and until
# Repeat 3 times: times is a method of the number 3
3.times do
print "Knock! "
end
puts "Who is it?"
# Count from 5 down to 1: downto, another method of the number
5.downto(1) do |i|
print i, " "
end
puts "Liftoff!"
# Repeat until it's right: until repeats while the condition is false
attempts = 0
pin = 0
until pin == 3702
attempts += 1
pin += 1234 # simulates the PIN typed on each attempt
puts "attempt #{attempts}: PIN #{pin}"
end
puts "got it right after #{attempts} attempts"
' Loops in Visual Basic: For ... Next and Do ... Loop
Module Loops
Sub Main()
' Repeat 3 times: For ... To ... Next
For i As Integer = 1 To 3
Console.Write("Knock! ")
Next
Console.WriteLine("Who is it?")
' Count from 5 down to 1: Step -1 makes the counter go down
For i As Integer = 5 To 1 Step -1
Console.Write(i & " ")
Next
Console.WriteLine("Liftoff!")
' Repeat until it's right: Loop Until tests at the end, like do-while
Dim attempts As Integer = 0
Dim pin As Integer = 0
Do
attempts = attempts + 1
pin = pin + 1234 ' simulates the PIN typed on each attempt
Console.WriteLine("attempt " & attempts & ": PIN " & pin)
Loop Until pin = 3702
Console.WriteLine("got it right after " & attempts & " attempts")
End Sub
End Module
// Loops in Delphi: for ... downto and repeat ... until
program Loops;
var
i, attempts, pin: Integer;
begin
// Repeat 3 times: for ... to ... do
for i := 1 to 3 do
Write('Knock! ');
WriteLn('Who is it?');
// Count from 5 down to 1: downto makes the counter go down
for i := 5 downto 1 do
Write(i, ' ');
WriteLn('Liftoff!');
// Repeat until it's right: repeat ... until tests at the end
attempts := 0;
pin := 0;
repeat
attempts := attempts + 1;
pin := pin + 1234; // simulates the PIN typed on each attempt
WriteLn('attempt ', attempts, ': PIN ', pin);
until pin = 3702;
WriteLn('got it right after ', attempts, ' attempts');
end.
* Loops in COBOL: the PERFORM verb
IDENTIFICATION DIVISION.
PROGRAM-ID. LOOPS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 9.
01 ATTEMPTS PIC 9 VALUE 0.
01 PIN PIC 9(4) VALUE 0.
PROCEDURE DIVISION.
* Repeat 3 times: PERFORM ... TIMES, with no counter
PERFORM 3 TIMES
DISPLAY "Knock! " WITH NO ADVANCING
END-PERFORM
DISPLAY "Who is it?"
* Count from 5 down to 1: VARYING ... BY -1 goes down by 1
PERFORM VARYING I FROM 5 BY -1 UNTIL I < 1
DISPLAY I " " WITH NO ADVANCING
END-PERFORM
DISPLAY "Liftoff!"
* Repeat until it's right: WITH TEST AFTER tests at the end
PERFORM WITH TEST AFTER UNTIL PIN = 3702
ADD 1 TO ATTEMPTS
ADD 1234 TO PIN
DISPLAY "attempt " ATTEMPTS ": PIN " PIN
END-PERFORM
DISPLAY "got it right after " ATTEMPTS " attempts"
STOP RUN.
Output:
Knock! Knock! Knock! Who is it? 5 4 3 2 1 Liftoff! attempt 1: PIN 1234 attempt 2: PIN 2468 attempt 3: PIN 3702 got it right after 3 attempts
Same output in all seven languages. Focus on the concept, not the language!
What changes is the name of each idea:
- Repeat a fixed number of times:
repeat(3)in Kotlin,3.timesin Ruby andPERFORM 3 TIMESin COBOL, with no counter variable. In Kotlin, repeat is a function from the standard library, and in Ruby, times is a method of the number itself. Go started acceptingfor range 3in version 1.22. - One name for everything: Go has neither while nor do-while. The for with only the condition plays the role of while, and the for with no condition at all repeats forever, until a break.
- Count backward:
5 downTo 1in Kotlin,5.downto(1)in Ruby,(1..=5).rev()in Rust,Step -1in Visual Basic,downtoin Delphi andBY -1in COBOL. - Repeat until: Ruby’s until, Visual Basic’s Loop Until, Delphi’s repeat … until and COBOL’s UNTIL repeat until the condition becomes true. Loop Until, repeat … until and WITH TEST AFTER test at the end, like do-while. Ruby’s until tests at the beginning, like while.
- A loop that hands back a value: in Rust, loop repeats forever, and break can carry a value out. In the program, the number of attempts comes out of the loop itself.
IMPORTANT: until inverts the condition. In C’s do-while, pin != 3702 says when to keep going. In until, the condition says when to stop: when the PIN is 3702. Copy C’s condition without inverting it and the program goes wrong without any warning. In Visual Basic, Loop Until pin <> 3702 stops after the first attempt and prints “got it right after 1 attempts” with the wrong PIN. In Ruby, until pin != 3702 doesn’t even enter the loop and prints “got it right after 0 attempts”.
IMPORTANT: the same 1..5 doesn’t give the same number of laps everywhere. In Kotlin and in Ruby, 1..5 goes from 1 to 5: that’s 5 laps. In Rust, 1..5 stops at 4: that’s 4 laps, and to include the 5 you write 1..=5, as in the program’s countdown. To leave the last one out, Kotlin uses 1..<5 and Ruby uses three dots, 1...5. Got it? Whoever switches languages without checking this ends up off by one.
Now you ask: which loop should I use?
- for: when you know how many laps there will be, or when you’re going to go through a list from beginning to end.
- while: when the number of laps depends on what happens while the program runs, and the test needs to be done before the first lap.
- do-while: when the block needs to run once before the test makes sense.
A for with a counter can be rewritten as a while. Section 1 of the program is a for written by hand: the start before the loop, the condition in the while and the step on the last line of the block.
What is an infinite loop?
It’s a loop whose condition never becomes false. The program enters the repetition and never gets out. IMPORTANT: something inside the block has to be able to change the result of the condition. In section 1, it’s the line i = i + 1. Delete that line and the program will print “lap 1” nonstop.
In C there’s a trap: the semicolon right after the condition, as in while (a < 10); followed by the block. The semicolon ends the command right there, the loop is left without a body and the variable never changes.
Not every endless loop is a mistake. The while True in section 4 is on purpose, and the way out is guaranteed by the break. The problem is the infinite loop you didn’t plan.
What are the most common mistakes with loops?
- Forgetting to update the variable in the condition. That’s how an infinite loop is born.
- Being off by one. Swapping
<=for<makes the loop do one lap less. In Python, forgetting that range doesn’t include the end point gives the same result. - Not giving the counter or the accumulator an initial value. The total has to start at 0.
- Resetting the accumulator inside the loop. If
total = 0is inside the block, the total starts over on every lap. - Putting a semicolon after the while or the for in C. The loop is left without a body.
- Mixing up break and continue. break leaves the loop. continue only skips one lap.
- Using continue before updating the counter in a while. The lap is skipped, the counter doesn’t change and the loop gets stuck.
Now it’s your turn!
On paper:
- Make the table of n and total for the loop that adds the numbers from 1 to 6. The total should be 21.
- How many times does the message show up in
for (i = 0; i < 10; i = i + 2)? List the values of i. - In the while loop of section 1, what changes in the output if the condition is
i < 5?
On the computer:
- Show the multiplication table of 7, from 7 x 1 to 7 x 10.
- Add up only the even numbers from 1 to 100. The result should be 2550.
- Using the article’s list of grades, calculate the average with an accumulator and a counter.
Try it on your own, without asking anyone for the ready-made answer, not even AI!
See you in the next article!
Stay confident!!!
Sources:
- PHP, official manual. while, with the condition checked at the beginning of each iteration and the case in which the block doesn’t run even once.
- PHP, official manual. for, with the role of the three expressions of the for and the moment each one is evaluated.
- PHP, official manual. do-while, with the condition checked at the end of each iteration, so the first one always runs.
- PHP, official manual. continue, with the skip of the rest of the current iteration.
- Python, official documentation. Compound statements, with the while and for statements and the break and continue statements inside them.
- Stanford University (Nick Parlante). Python range() Function, with
range(n)going up to, but not including, n. - Runestone Academy, How to Think Like a Computer Scientist: Interactive Edition. Iteration Revisited, with computers used to automate repetitive tasks and the repeated execution of statements called iteration.
- GNU, The GNU C Language Manual. Loop Statements, with the while, do-while and for loops of C, and the break and continue statements.
- East Carolina University, CSCI 2530. Pitfalls with Loops, with the loop that never stops because its variable never changes, and the semicolon after the while heading that leaves the loop without a body.
- Stack Overflow. Developer Survey 2025, Technology, with Go, Kotlin, Rust, Ruby, Visual Basic (.Net), VBA, Delphi and COBOL in the list of languages used by the respondents.
- Android Developers. Android’s Kotlin-first approach, with the recommendation to start an Android app in Kotlin.
- Microsoft Learn, Office VBA. Using For…Next statements, with VBA’s For … Next and the negative Step that makes the counter go down.
- Microsoft Learn, Office VBA. Do…Loop statement, with VBA’s Do … Loop and the While and Until conditions.
- Go, official documentation. The Go Programming Language Specification, with the forms of the for statement and the absent condition that is equivalent to true.
- Go, official documentation. Go 1.22 Release Notes, with for loops that can range over integers, as in
for range 3. - Kotlin, standard library. repeat, with repeat as a function that runs the given action a specified number of times.
- Kotlin, official documentation. Ranges and progressions, with the
..and..<ranges, downTo and step. - The Rust Programming Language. Control Flow, with loop, which repeats until a break, and break returning a value from the loop.
- The Rust Reference. Range expressions, with the
..range, which leaves the end out, and..=, which includes it. - Rust, standard library. Rev, with rev, which inverts the direction of an iterator.
- Ruby 3.3. Integer, with the times and downto methods.
- Ruby, official documentation. Control Expressions, with until, which keeps running while the condition is false and checks it when entering the loop.
- Ruby 3.3. Range, with
.., which includes the end, and the three dots, which leave it out. - Microsoft Learn. For…Next Statement (Visual Basic), with the negative step that makes the counter go down.
- Microsoft Learn. Do…Loop Statement (Visual Basic), with While and Until and the test at the start or at the end of the loop.
- Embarcadero DocWiki. Declarations and Statements (Delphi), with for … downto and repeat … until, which tests the condition after each lap.
- IBM, Enterprise COBOL. Coding a loop, with PERFORM … TIMES and PERFORM … WITH TEST AFTER … UNTIL.
- IBM, Enterprise COBOL. PERFORM with VARYING phrase, with VARYING, which increases or decreases the counter, and TEST BEFORE as the default.
- The examples were run on Python 3.13, PHP 8.3, GCC 13, Go 1.24, Kotlin 2.4, Rust 1.97, Ruby 3.3, Visual Basic on .NET 8, Free Pascal 3.2 (in Delphi mode) and GnuCOBOL 3.1.

Continue the conversation