Conditional Instruction In C
if (condition) {
// code to execute if condition is true
}
For example, the following code checks if the variable x is greater than y, and if it is, prints "x is greater than y".
int x = 10;
int y = 5;
if (x > y) {
printf("x is greater than y");
}
In addition to the if statement, C also has the if-else statement, which allows the program to execute one block of code if a condition is true and another 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, the following code checks if the variable x is greater than y, and if it is, prints "x is greater than y", otherwise, it prints "x is not greater than y".".
int x = 10;
int y = 5;
if (x > y) {
printf("x is greater than y");
} else {
printf("x is not greater than y");
}
C also has the switch statement, which allows the program to check the value of a variable against multiple cases. The syntax for a switch statement is as follows:
switch (variable) {
case value1:
// code to execute if variable is equal to value1
break;
case value2:
// code to execute if variable is equal to value2
break;
// additional cases as needed
default:
// code to execute if variable does not match any of the cases
}
For example, the following code checks the value of the variable x and prints a message based on its value:
int x = 2;
switch (x) {
case 1:
printf("x is 1");
break;
case 2:
printf("x is 2");
break;
case 3:
printf("x is 3");
break;
default:
printf("x is not 1, 2, or 3");
}
In this example, since x is 2, the code will print "x is 2".
In conclusion, conditional instructions in C (if, if-else, switch) are used to control the flow of a program by allowing it to make decisions based on certain conditions and execute different code based on the outcome of those conditions. They are fundamental for programming and you can use them in many different scenarios.