This blog is under construction

Saturday, 21 April 2012

Control statements - else if statement

Syntax for else if statement:

if (expression) {
     <if block>
} else if  (expression) {
     <else if block>
} else {
    <else block> 
}

First, the truth value of the expression in if statement is evaluated.  If it is true, then the statement present inside the if block will get executed.  Otherwise, the truth value of the expression in else if statement is evaluated.  If the else if expression evaluates to be true, then the statements present inside the else if block will get executed.  Otherwise, the statement present inside the else block will get executed.

Example C program using else if statement:
 
  #include <stdio.h>
  int main() {
        int mark;
        printf("Enter Your mark: ");
        scanf("%d", &mark);
        if (mark > 80) {  // expression for if statement => mark > 80
                printf("Outstanding Student\n");  // if block
        } else if (mark > 60) {  // expression for else if statement => mark > 60
                printf("Average Student\n");  // else if block
        } else {
                printf("Below Average Student\n");  // else block
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/cpgms/posts$ ./a.out
  Enter Your mark:  90
  Outstanding Student



No comments:

Post a Comment