Iteration control structures are programming constructs that allow you to repeat code blocks multiple times. They are essential for performing repetitive tasks and processing data efficiently.
for Loop
The for loop is a simple and versatile iteration construct. It executes a block of code a specified number of times.
Code snippet
for i in 0...5 {
print(i);
}
while Loop
The while loop continues to execute a block of code as long as a specified condition remains true.
Code snippet
var count: int = 0;
while count < 10 {
print(count);
count += 1;
}
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once before the condition is checked.
Code snippet
var input: string = "";
do {
print("Enter a number:");
input = readLine();
} while input.isEmpty();
Nested Loops
You can nest loops within each other to perform more complex iterations.
Code snippet
for i in 0...3 {
for j in 0...2 {
print("i = \(i), j = \(j)");
}
}
break and continue Statements
The break statement can be used to exit a loop prematurely. The continue statement can be used to skip the current iteration of a loop and proceed to the next iteration.
Code snippet
for i in 0...10 {
if i == 5 {
break; // Exits the loop
}
print(i);
}
for i in 0...5 {
if i == 2 {
continue; // Skips the current iteration
}
print(i);
}
Iterating Over Collections
Carbon provides convenient ways to iterate over collections like arrays and ranges.
Code snippet
var numbers: [int] = [1, 2, 3, 4, 5];
for number in numbers {
print(number);
}
Iteration control structures are essential for writing efficient and concise Carbon programs. By understanding and using them effectively, you can perform repetitive tasks, process data, and create more powerful applications.
