CMPSC 201 - Ch. 4 Notes
Objective #1: Understand how decisions are made in programs.
Objective #2: Use relational operators.
== equal to NOTE:
this is two equals symbols next to each other, not to be confused with the
assignment operator, =
> greater than
< less than
>= greater than or equal to
<= less than or equal to
!= not equal to
Objective #4: Use logical operators.
&& which means "and"
|| which means "or". You type the | symbol by holding down the shift key and pressing the backspace key on the keyboard.
! which means "not"
AND | OR | NOT | |||||||
A | B | A && B | A | B | A || B | A | !A | ||
0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | ||
0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | ||
1 | 0 | 0 | 1 | 0 | 1 | ||||
1 | 1 | 1 | 1 | 1 | 1 |
Example: inRange = ( i > 0 && i < 11); if i is not greater than zero, the program doesn't even worry about checking whether i < 11 or not (since the whole right-hand expression can never be TRUE if i <= 0 ).
Objective #5: Use the if statement.
if (number == 3)
{
cout
<< "The value of number is 3";
}
if (num > 0)
cout << "num is positive" <<
endl;
cout << "num is not zero"
<< endl;
the body of the if statement is only considered to be the first cout statement according to the C++ compiler. The second statement would execute even if num is equal to zero. The indentation of the second statement has no effect on the way the compiler interprets this code.
Always use the "double equals" symbol (i.e. comparison operator) rather than the assignment operator in control expressions:
int num = 0:
if (num == 5)
{
cout << "hello world" << endl;
}
which would not display "hello world" rather than:
int num = 0;
if (num = 5)
{
cout << "hello world" << endl;
}
which would assign the value 5 to the variable num and then display "hello world"
Avoid using an unnecessary semicolon after a control expression:
if (num > 0);
{
cout << "num is positive" <<
endl;
}
which would cause the phrase "num is positive" to be displayed
even if num is negative.
Objective #6: Use the if/else statement.
if ( number < 0)
{
cout << "The number
is negative.";
}
else
{
cout << "The number
is zero or positive.";
}
Objective #7: Use nested if statements.