Loop

A loop is a control structure that repeats a block of code multiple times until a condition is met. It allows programs to perform repetitive tasks automatically.

Why loops are important

Many tasks require repetition.

For example:

  • Display numbers from 1 to 100
  • Process every item in a list
  • Repeat an action until the user quits

Without loops, you would have to write the same code many times.

How a loop works

A loop usually has:

  1. A starting point
  2. A condition
  3. A repeating action
  4. A stopping point

The loop continues running while the condition is true.

Common Types of Loops

1. For Loop

Used when the number of repetitions is known.

 

Example:

for (i = 1; i <= 5; i++) { print(i) }

2. While Loop

Used when repetition depends on a condition.

 

Example:

while (score < 100) { score = score + 10 }

The loop runs until the condition becomes false.

 

3. Do-While Loop

Executes the code at least once before checking the condition.

 

Example:

do { print("Hello") } while (condition)

Infinite Loop

If the stopping condition never becomes false, the loop runs forever.

 

Example:

while (true) { print("Running") }

This is called an infinite loop.

Why learning loops matters

Variables represent locations in computer memory.

Loops help you:

  • Automate repetitive tasks
  • Work with large data sets
  • Improve code efficiency
  • Build dynamic programs

They are essential for real-world programming.

Simple example

Think of brushing your teeth:

Repeat brushing until your teeth are clean.

That is a loop controlled by a condition.

Related terms

Source

Simplified from general programming documentation and Wikipedia.

Nach oben scrollen