• Home
  • If Statement in C with example

If Statement in C with example

The if statement is a control flow statement in the C programming language that allows you to execute a block of code if a certain condition is true. The syntax for an if statement is as follows:

if (condition) {
// code to execute if condition is true
}

For example, consider the following code:

int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
}

In this example, the condition is (x > 5), which is true because the value of x (10) is greater than 5. Therefore, the code inside the if statement will be executed and the message “x is greater than 5” will be printed to the console.

You can also include an optional else clause to execute a different block of code if the condition is false. For example:

int x = 10;
if (x > 15) {
printf("x is greater than 15\n");
} else {
printf("x is not greater than 15\n");
}

In this example, the condition (x > 15) is false, so the code inside the else block will be executed and the message “x is not greater than 15” will be printed to the console.

You can use multiple if statements in sequence to check multiple conditions. For example:

int x = 10;
if (x > 15) {
printf("x is greater than 15\n");
} else if (x > 5) {
printf("x is greater than 5 but not greater than 15\n");
} else {
printf("x is not greater than 5\n");
}

In this example, the first condition (x > 15) is false, so the code inside the first if statement is not executed. The second condition (x > 5) is true, so the code inside the second if statement is executed and the message “x is greater than 5 but not greater than 15” is printed to the console.