Repetition

Updated: 03/12/2022 by Computer Hope
infinity symbol indicating a Loop

In general, repetition is repeating an action or event. For example, a computer program could be developed to repeat the same message over and over using a loop.

Example of repetition

Below is an example of how repetition could be used in a computer program.

my $count = 0;
do {
 print "$count\n";
 $count++;
} until ($count == 100);

In this example, the $count variable starts as zero and performs a do loop that prints the current value and adds one until the value equals 100.

Using these five lines of code, the program could print 0 to 100 to the screen without the programmer having to write 100 print statements.

Why is repetition important in programming?

Repetition in programming is important because it helps simplify the software by reducing the number of steps a developer needs to write in a program or algorithm. In our earlier example, we wrote a program that could write 0 to 100 with five lines of code. If we wanted to print 0 to 1,000,000, we'd only need to add four more 0's to the until line. Without repetition the program would need to write a million lines of code to print each number.

In another example, repetition could be added to several pictures to show an animation of a character walking. As the user holds down an arrow key, the program uses repetition to give the appearance of a character walking without having to program each step.

Iteration, Loop, Programming terms, Repeat counter, Repeat loop, Repetitive strain injury