This blog is under construction

Saturday, 14 April 2012

Control statements - if statement

Syntax for if statement:

if (expression) {
     statement;
}

Here, the truth value of the expression is evaluated to be true, then the statement present inside the parenthesis will get executed.

Example C program using if statement:
 
  /* Example 1 */
  #include <stdio.h>
  int main() {
        int year = 2012;
        if (year == 2012) {  // checks whether the value of year is 2012
                printf("Happy New Year 2012\n");
        }
        printf("Program going to terminate\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/cpgms$ ./a.out
  Happy New Year 2012
  Program going to terminate


Let us see another example that demonstrates the behavior of if statement.  Here, I have assigned the variable year with value 2000 and checking whether the value of year is 2012.  The condition would fail obviously and the statement inside if block won't get executed.
 
  /* Example 2 */
  #include <stdio.h>
  int main() {
        int year = 2000;
        if (year == 2012) {  // checks whether the value of year is 2012
                /* execute below statement if the above expression is true */
                printf("Happy New Year 2012\n");
        }
        printf("Program going to terminate\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/cpgms$ ./a.out
  Program going to terminate



No comments:

Post a Comment