As we have seen so far, the default execution flow (the order in which the code is executed) is sequential. This means that the code runs from top to bottom.
We can change the execution flow of the program by using constructs (control structures). There are two types of constructs:
- Conditional constructs
- Iterative constructs
Conditional constructs
These are used to execute sections of code when certain conditions are fulfilled. There are 3 conditional constructs in C:
- if statement
if (condition){
do something;
}
- if-else statement
if (condition){
do this when condition is fulfilled;
}else{
do this when condition is not fulfilled;
}
- switch-case statement
switch (variable){
case first_case:
do something;
break;
case second_case;
do something_else;
break;
default:
do default_action;
}
Iterative constructs
These are used to execute sections of code multiple times. There are 3 conditional constructs in C:
- for
for (int i=0;i<n;i++){
something to do n times;
}
- while loop
while (condition){
do this as long as condition is fulfilled;
}
- do-while loop
do {
do this as long as condition is fulfilled;
} while (condition);