In C, the control flows from one instruction to the next instruction until now in all programs. This control flow from one command to the next is called sequential control flow. Nonetheless, in most C programs the programmer may want to skip instructions or repeat a set of instructions repeatedly when writing logic. This can be referred to as sequential control flow. The declarations in C let programmers make such decisions which are called decision-making or control declarations.
Types of control statements:
1. If statement:
The if statement evaluates the test expression inside the parenthesis () . If the test expression is evaluated to true, statements inside the body of if are executed. If the test expression is evaluated to false, statements inside the body of if are not executed.
Syntax:
if (condition){
//Block of C statements here
//These statements will only execute if the condition is true
}
2. Switch statement:
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.
Syntax:
switch (n){
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
3. Conditional operator:
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.
Syntax:
expression1? expression2: expression3;
4. goto statement:
The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.
Syntax:
Syntax1 | Syntax2----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
5. Loop statement:
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iterations.
Three main types of loops:
- for
- do-while loops
- while loops.
Syntax of for loop:
for (initialization statement; test expression; update statement)
Syntax of do-while loop:
do {
statement(s);
}
while( condition );
Syntax of while loop: