Saturday, December 11, 2010

Example Of If Else Statement

Here is a full C++ program as an example:
//include this file for cout
#include <iostream.h>

int main() {
  // define two integers
  int x = 3;
  int y = 4;

  //print out a message telling which is bigger
  if (x > y) {
    cout << "x is bigger than y" << endl;
  }
  else {
    cout << "x is smaller than y" << endl;
  }
  return 0;
}
In this case condition is equal to "(x > y)" which is equal to "(3 > 4)" which is a false statement. So the code within the else clause will be executed. The output of this program will be:
x is smaller than y
If instead the value for x was 6 and the value for y was 2, then condition would be "(6 > 2)" which is a true statement and the output of the program would be:
x is bigger than y

No comments:

Post a Comment