// Mr. Minich
// CMPSC 201
// Ch. 4 Demo Program #3
// January 30, 2000 // Purpose - to illustrate the use of the if statement
#include <iostream.h> int main() { int num1 = 1; // used in if statement examples int num2 = 0; // used in if statement examples if (num1 == 1) { cout << "num1 is equal to 1" << endl;
}
// Notice the use of blank lines above and below the if statement for the sake of readability.
num1 = 5; if (num1 = 1) {
cout << "num1 is equal to " << num1 << endl;
}
// This prints "num1 is equal to 1". The programmer // incorrectly used the assignment operator (=) in the // control expression instead of the relational operator // (==). This is a very common mistake and C++ yields a // TRUE to the result of the expression (num1 = 1). num1 = 1; num2 = 1; if ((num1 == 1) && (num2 == 1)) { cout << "num1 AND num2 are both equal to 1" << endl;
} else {
cout << "num1 AND num2 are not both equal to 1" << endl;
} num1 = 4; num2 = 5; if (num1 == 99 || num1 == 4 && num2 == 99) {
cout << "The control expression is TRUE." << endl;
} else {
cout << "The control expression is FALSE." << endl;
} // This prints "The control expression is FALSE." Remember the // order of operations when evaluating logical operators. if (num1)
{ cout << "num1 is a nonzero value." << endl;
}
// As long as the variable num1 is a positive value, the control // expression (num1) yields a TRUE.
return 0; }// end of main