Control structures are programming constructs that allow you to control the flow of execution in your Carbon code. They enable you to make decisions, repeat code blocks, and jump to specific parts of your program.
Conditional Statements
Conditional statements are used to execute different code blocks based on certain conditions. Carbon supports the following conditional statements:
if
Statement: Executes a block of code if a condition is true.else
Statement: Executes a block of code if the condition in theif
statement is false.else if
Statement: Provides additional conditions to check if the previousif
orelse if
conditions are false.
Example:
Code snippet
var age: int = 25;
if age >= 18 {
print("You are an adult.");
} else {
print("You are a minor.");
}
Looping Constructs
Looping constructs allow you to repeat code blocks multiple times. Carbon provides the following looping constructs:
for
Loop: Executes a block of code a specified number of times.while
Loop: Executes a block of code as long as a condition is true.do-while
Loop: Executes a block of code at least once, then repeats as long as a condition is true.
Example:
Code snippet
for i in 0...5 {
print(i);
}
var count: int = 0;
while count < 10 {
print(count);
count += 1;
}
Switch Statement
The switch
statement is used to select one of several code blocks to execute based on the value of an expression.
Example:
Code snippet
var day: string = "Monday";
switch day {
case "Monday":
print("It's Monday!")
case "Tuesday":
print("It's Tuesday!")
default:
print("It's another day!")
}
Break and Continue Statements
The break
statement is used to exit a loop or a switch
statement. The continue
statement is used to skip the current iteration of a loop and proceed to the next iteration.
Control structures are essential for writing efficient and flexible Carbon programs. By understanding and using them effectively, you can create more complex and powerful applications.