The logical operators && (and) and || (or) are used to join two simple Boolean expressions to form more complex Boolean expressions. For example, if you wanted to construct a Boolean expression which would be true if an integer variable num had a value in the range 0-10 (inclusive) you could write (num >= 0) && (num <= 10)
A complex Boolean expression using && is true if and only if both simple Boolean expressions it joins are true, otherwise the expression is false.
As an example using the or operator ||, suppose you wanted to construct a Boolean expression that would be true if the value of an integer variable
x is either 1 or 2. For this you could write (x == 1) || (x == 2)A complex Boolean expression using || is true if either or both simple Boolean expressions it joins are true. The expression is false only if both simple Boolean expressions are false.
The logical operator ! (not) is used to reverse the value of the Boolean expression it precedes. So, for example, if an integer variable
num has the value 100, the expression !(num > 0) is false.Complex Boolean expressions can be used in both if and while statements. The complete expression must be enclosed in parentheses as required by the syntax for either the if or while statements. For example,
Part 1: Practice with Decision Statements
Write a short program that asks the user for their GPA (a double) and outputs a message based on the following chart:
3.7 <= GPA <= 4.0 message should be Excellent!
3.0 <= GPA < 3.7 message should be Pretty good
2.0 <= GPA < 3.0 message should be Not too bad
GPA < 2.0 message should be Needs work
If their GPA falls outside this range, you should output "Invalid GPA"
Note: Complex Decision Statements will yield a more compact, clean solution.
Part 2: Practice with looping
Write a short program that will read in a list of grades. The program will continue to read in values until a sentinel value of -1 is inputted.
From this list, your program should compute the mean (average) grade, as well as output the highest and lowest.
Test this program using this input file. You can copy this to your current directory using the following command.
cp ~cfischer/public_html/data.txt .
Note this line carefully, especially the space and the dot at the end. The cp command uses the form of
cp <source> <target>
The ~cfischer part references my home directory, then uses gets a file called data.txt from the public_html directory. The single dot
basically says "copy to my current directory", which you can see using the 'pwd' command.