C if else Statement

if else in C is a selection statement that used to select statements depending on the value of a controlling expression.

Syntax:

if ( expression )
statement1 ;
else
statement2;

In the above scenario, the statement1 will only be executed if the expression is non-zero. if the expression is zero, then statement2 will be executed.

Let see an example,

The below program check even number and odd number. If a number is divided by 2, it means it is an even number. If the number is not divided by 2, then it is an odd number.

How the above program works:

1 Case: When you entered even number:

We know that the modular division of an even number by 2 is 0. So expression (data % 2) return 0, as we know expression ( 0 == 0) return 1.

Now if((data % 2) == 0) become if(1), as per C standard if the controlling expression is non-zero then body associated with if will be execute. So statement printf(“\n Number is Even.\n\n”) will be execute and skip the statement printf(“\n Number is Odd.\n\n”).

2 Case: When you entered odd number:

For odd number expression (data % 2) return 1, so expression ( 1== 0) return 0. Now if((data % 2) == 0) become if(0), so body of if will be skip and else will be executed. So statement printf(“\n Number is Odd.\n\n”) will be execute.

Let see one more example,

The below code find the greatest number from the two given number.

Note: An else is always associated with an if statement.

If…else if…else Statements

If more than one conditions occur in the program, then we should use if…else if…else statements. In if…else if…else statement each condition is checked until not get the true condition.

In if… else if statement, when the condition is found to be true, then statements that attached with the true condition is only executed and all other conditions will be skipped and program control comes out of if… else if statement.

Syntax,

The basic formula to convert Fahrenheit and Celsius to each other.

Celsius to Fahrenheit: (°C × 9/5) + 32 = °F
Fahrenheit to Celsius: (°F − 32) x 5/9 = °C