The if-else statement is used to carry out a logical test and then take one of two possible actions, depending on whether the outcome of the test is true or false. The else portion of the statement is optional. Thus, the simplest possible if-else statement takes the form:
if (expression) statement
The expression must be placed in parenthesis, as shown. In this form, the statement will only be executed if the expression has a nonzero value (i.e., if expression if true). If the expression has a value of zero (i.e., if expression is false) then the statement will be ignored. The statement can be either simple or compound.
The general form of an if-else statement, which includes the else clause, is
if (expression) statement 1 else statement 2
If the expression has a non-zero value (i.e., if expression is true) then statement1 is executed. Otherwise, statement2 is executed.
Example : 1 Program to illustrate if / else syntax
#include<stdio.h> /************************************** * This program uses if / else syntax * **************************************/ int main() { char letter; printf("Enter a letter: from A to F "); scanf("%c", letter); if (letter == 'A' || letter == 'a') printf("A is for America.\n"); else if (letter == 'B' || letter == 'b') printf("B is for Brazil.\n); else if (letter == 'C' || letter == 'c') printf("C is for Canada.\n"); else if (letter == 'D' || letter == 'd') printf("D is for Denmark.\n); else if (letter == 'E' || letter == 'e') printf("E is for Egypt.\n); else if (letter == 'F' || letter == 'f') printf("F is for France.\n); /* Put the rest of the letters here */ else printf("Sorry, %c is not a valid required input.\n", letter); return 0; }
Example 2 : Grade program illustrate if else statement
/* Grade program illustrate if else statement */ #include int main ( ) { int mark ; printf ("enter your test mark >") ; scanf ("%d", &mark) ; if (mark >= 90) printf ("Your mark of %d is a A\n", mark) ; else if (mark >= 80 && mark < 90) printf ("Your mark of %d is a B\n", mark) ; else if (mark >= 70) printf ("Your mark of %d is a C\n", mark) ; else if (mark >= 60) printf ("Your mark of %d is a D\n", mark) ; else printf ("Your mark of %d is an E\n", mark) ; }