Decision making is a common requirement in programming, and the C programming language provides several constructs for making decisions in your code.
The if statement: The if statement is used to execute a block of code if a condition is true. The syntax for an if statement is as follows:
if (condition) {
// code to execute if condition is true
}
For example:
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
}
In this example, the code block inside the if statement will be executed because the condition (x > 5) is true.
The if-else statement: The if-else statement is used to execute a block of code if a condition is true, and a different block of code if the condition is false. The syntax for an if-else statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
For example:
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
In this example, the code inside the first block will be executed because the condition (x > 5) is true.
The switch statement: The switch statement is used to execute a block of code based on the value of a variable. The syntax for a switch statement is as follows:
switch (expression) {
case value1:
// code to execute if expression is value1
break;
case value2:
// code to execute if expression is value2
break;
...
default:
// code to execute if expression is none of the values
}
The switch statement evaluates the expression and compares it to the values in the case statements. If a match is found, the corresponding code block is executed. The “break” statement is used to exit the switch statement and prevent further execution of the code blocks. If no match is found, the code in the default case is executed.
For example:
int x = 2;
switch (x) {
case 1:
printf("x is 1\n");
break;
case 2:
printf("x is 2\n");
break;
case 3:
printf("x is 3\n");
break;
default:
printf("x is not 1, 2, or 3\n");
}
In this example, the code inside the second case block will be executed because the value of x (2) matches the value in the second case.