Rouge Documentation Help

Repeating Computations

Previously, we have learned how to make computations reusable by using functions. In this chapter we will learn how to repeat computations using loops. Loops allow you to repeat computations based on a condition that needs to be met in order for the repetition to continue.

In the following example, a loop is defined using the while keyword. Syntactically, a loop is very similar to a condition. The while keyword is followed by the condition that needs to be met in order for the repetition to continue. That actual code that is repeated is contained in the following curly braces, the so-called body of the loop.

Loops become easy to understand when you try to read the line of the while keyword out loud. For the following example, it would read "While the counter variable stays below 5, we continuously execute the code inside the curly braces".

counter = 1 while (counter < 5) { print("Counter: ${counter}") counter = counter + 1 }

Output:

1 2 3 4

The condition is not the only important part of the loop. The body is just as important as it is the only part of the code that can change the state of the program at the time the loop is executed. Changing the state of the program is also the only way to change the outcome of the condition that controls the loop. In the above example, the body accomplishes two things. First, we print the current value stored in the counter variable to the screen. Next, we increment the counter variable by one, which, after four iterations, will stop the loop because the condition will no longer be met. An iteration refers to one execution of the loop's body.

The above example allows us to iterate a fixed number of times. However, you can make your condition depend on any state you would like, possibly making the number of iterations dynamic.

Last modified: 07 January 2026