Control flow statements allow you to execute certain parts of your code if specific conditions are met. In C++, there are three main control flow statements:`if-else`, `switch`, and `goto`.
Branching statements allow you to conditionally or unconditionally execute different parts of your code. The branching statements that will be covered are`if-else`, `switch`, and `goto`.
## if-else
The `if-else` statement is a fundamental control flow statement that allows you to execute one of two blocks of code depending on whether a condition is satisfied. This statement is useful for complex comparisons. The syntax for the `if-else` statement is:
The `if-else` statement is a conditional branching statement that allows you to execute one of two blocks of code depending on whether a condition is satisfied. This statement is useful for making decisions based on a boolean expression. The syntax for the `if-else` statement is:
```cpp
if (condition) {
@ -30,7 +30,7 @@ int main() {
```
## switch
The `switch` statement allows you to execute different blocks of code based on the value of a `control variable`. It uses `cases` to define code blocks that run when a specific value matches. A `default` case is executed if none of the other cases match. Each `case` must end with a `break` statement; otherwise, all following cases will execute. `Switch` is useful when you want to compare `constant values`. The syntax for the `switch` statement is:
The `switch` statement allows you to execute different blocks of code based on the value of a `control variable`. It uses `cases` to define code blocks that run when a specific value matches. A `default` case is executed if none of the other cases match. Each `case` must end with a `break` statement; otherwise, all following cases will execute. `switch` is useful when you want to compare a `control variable` to multiple constant values. The syntax for the `switch` statement is:
```cpp
switch (control_variable) {
@ -77,13 +77,13 @@ int main() {
```
## goto
The `goto` statement allows you to jump to different parts of your program using `labels` as location points. The syntax for `goto` is:
The `goto` statement allows you to unconditionally jump to different parts of your program using `labels` as location points. The syntax for `goto` is:
```cpp
goto label_name;
```
For example:
For example:
```cpp
#include<iostream>
@ -93,16 +93,14 @@ int main() {
cout << "This is line 1";
goto line_3;
// This line will be skipped
cout << "This line will be skipped";
line_3:
cout << "This is line 3";
line_3:
cout << "This is line 3";
}
```
Learn more from the following resources:
- [@article@C++ if else](https://www.w3schools.com/cpp/cpp_conditions.asp)