Control Structures Tutorial
Introduction to Control Structures
Control structures are constructs that dictate the flow of control in a program. They allow you to make decisions, repeat actions, and control the execution of different blocks of code based on certain conditions. Understanding control structures is essential for writing effective programs.
Types of Control Structures
There are three primary types of control structures: sequential, selection, and repetition.
- Sequential: The default mode where statements are executed in order.
- Selection: Allows branching in the code based on conditions (e.g., if-else statements).
- Repetition: Enables the execution of a block of code multiple times (e.g., loops).
Selection Control Structures
Selection control structures allow the program to choose different paths of execution based on specific conditions.
If Statement
The basic syntax of an if statement is as follows:
// code to execute
}
Example:
Check if a number is positive:
print("Positive number");
}
If-Else Statement
Allows you to define an alternative path if the condition is false:
// code if true
} else {
// code if false
}
Example:
Check if a number is positive or negative:
print("Positive number");
} else {
print("Negative number");
}
Repetition Control Structures
Repetition control structures allow code blocks to be executed multiple times based on a condition.
For Loop
A for loop is used to execute a block of code a specific number of times:
// code to execute
}
Example:
Print numbers from 1 to 5:
print(i);
}
While Loop
A while loop executes as long as the specified condition is true:
// code to execute
}
Example:
Print numbers from 1 to 5 using a while loop:
while (i <= 5) {
print(i);
i++;
}
Conclusion
Control structures are fundamental to programming as they enable you to dictate how your code executes based on conditions and loops. Mastering these constructs will enhance your programming skills and allow you to write more complex and efficient code.