Loops
This page shows you how to control the flow of your code to reapeatly perform a task by using different kind of loops in Cambo.
There are 3 types of loops:
whilelooprepeat whileloopforloop
While Loop
A while loop is a control-flow construct that repeatedly executes a line of block of code as long as a specified boolean condition evaluates to true. The loop begins with an initial evaluation of the condition to determine whether execution should proceed. After each iteration, the condition is re-evaluated, and the cycle repeats accordingly.
while(condition){
# code ...
}
Example:
while(2 < 4){
print("always true");
}
always true will be repeatedly printed infinite times because the condition 2 < 4 is always true.
Repeat While Loop
Unlike while loop, repeat while loop executes the block of code once before evaulating the condition to determine whether the cycle should continue or terminate immediately.
repeat {
#code ...
}while(condition);
Example:
int i = 0;
repeat{
print("hello, new world\n");
i++;
} while(i < 10);
repeat-while loop is entirely the same as do-while loop in most other programming languages, the difference is just the keyword do is changed to repeat.For Loop
for loop is another control flow that repeatedly executes based on a header that consists of 3 different functional parts.
- Initialization: executed once before the loop begins, this part typically defines a loop control variable.
- Condition: a boolean expression evaluated before each iteration to determine whether the iteration should continue or not.
- Updation: executed at the end of each iteration, this part modifies the loop control variable, usually to move the loop closer to its termination state.
for(initialization; condition; updation){
# code ...
}
Example:
for(int i = 0; i < 10; i++){
print("hello, world!");
}
In the typical while loop you normally write:
int i = 0;
while(i < 10){
print("hello, world\n");
i++;
}
for loop is simply like a shortcut that you can write your while loop in fewer lines of code!
condition must be a valid boolean expression, others such as assignment is not allowed and shall result in compilation error.