For loop facts for kids
A for-loop is a special instruction in computer programming that tells a computer to repeat a task a certain number of times. Imagine you want to say "Hello!" ten times. Instead of writing "Hello!" ten separate times, you can use a for-loop to do it for you!
For-loops are very useful when you know exactly how many times you need to repeat something. They are made of two main parts:
- A header: This part sets up the loop. It often tells the computer how many times to repeat the task.
- A body: This part contains the actual instructions (lines of code) that will be repeated.
Here's an example of a for-loop in a programming language called Python:
for i in range(10):
print('Hello, world!')
This simple for-loop will make the computer print the words "Hello, world!" ten times. The `range(10)` part tells the loop to run ten times.
The name "for-loop" comes from the English word "for," which is a direct translation of the German word für. This word was used by Heinz Rutishauser, an important person who helped create early programming languages like ALGOL 58 and ALGOL 60.
How For-Loops Work
For-loops are available in almost all popular programming languages. While they all do the same job—repeating code—they might look a little different depending on the language.
Loop Counter
Inside a for-loop, there's often a special variable called a loop counter. This variable helps the computer keep track of how many times the loop has run.
- The loop counter is usually a whole number.
- It often starts at zero or one and goes up by one each time the loop repeats.
- Sometimes, it can also count down or go up by more than one.
- The loop counter changes with each repetition.
- It helps the loop know when to stop and move on to the next part of the program.
Common names for loop counters are `i`, `j`, and `k`. These are just short names that programmers often use.
Images for kids
See also
In Spanish: Bucle for para niños