C – If else Statement with Examples
The if else statement is used to express decisions and the syntax as per below,
if (expression) statement 1 else statement 2
where the else part is optional. The expression is evaluated; if it is true {that is, if>expression has a non-zero value}, statement 1 is executed. If it is false {expression is zero} and if there is an else part, statement 2 is executed instead.
Since an if simply tests the numeric value of an expression, certain coding shortcuts are possible. The most obvious writing as below with easy example.
if (expression)
instead of
if (expression 1= 0)
Sometimes this is natural and clear; at other times it can be cryptic. Because the else part of an if-else is optional, there is an ambiguity when an else is omitted from a nested if sequence. This is resolved by associating the else with the closest previous else-less if. For example, in
if (n > 0) if (a > b) z = a; else z = b;
the else goes with the inner if, as we have shown by indentation. If that isn’t what you want, braces must be used to force the proper association
If (n > 0) { If (a > b) Z =a; } Else Z = b;
The ambiguity is especially pernicious in situations like this:
if (n >= 0) for (i = 0; i < n; i++) if (s [ i] > 0) { printf( "... n); return i; else /*wrong*/ printf("error -- n is neqative\n");
The indentation shows unequivocally what you want, but the compiler doesn’t get the message, and associates the else with the inner if. This kind of bug can be hard to find; it’s a good idea to use braces when there are nested ifs.
if else statement
Here an Example shows how to calculate gross salary for the firm,
/* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee’s salary is input through the keyboard write a program to find his gross salary.
Please write your comments if you find anything incorrect OR need to explain in detail, or you want to share more information about the topic discussed above.