if
The if statement in C is used to execute a block of code conditionally, based on the value of a Boolean expression. The Boolean expression is evaluated, and if it is true, the code block is executed. If the expression is false, the code block is skipped.
Here is an example of using an if statement in a C program:
#include <stdio.h>
int main()
{
int a = 10;
int b = 5;
if (a > b) {
printf("a is greater than b\n");
}
return 0;
}
In this example, we have two variables, a and b, and we are using an if statement to check if a is greater than b. If it is, the message "a is greater than b" is printed to the console. If a is not greater than b, the code block is skipped and nothing is printed.
You can also use an else clause with an if statement to specify a block of code to be executed if the Boolean expression is false. For example:
#include <stdio.h>
int main()
{
int a = 10;
int b = 5;
if (a > b) {
printf("a is greater than b\n");
} else {
printf("a is not greater than b\n");
}
return 0;
}
In this example, if a is greater than b, the message "a is greater than b" is printed. If a is not greater than b, the message "a is not greater than b" is printed.
You can also use multiple if statements with else if clauses to create more complex conditional logic. For example:
#include <stdio.h>
int main()
{
int a = 10;
int b = 5;
if (a > b) {
printf("a is greater than b\n");
} else if (a == b) {
printf("a is equal to b\n");
} else {
printf("a is less than b\n");
}
return 0;
}
In this example, if a is greater than b, the message "a is greater than b" is printed. If a is equal to b, the message "a is equal to b" is printed. If neither of these conditions are true, the message "a is less than b" is printed.