Students who complete this lab will demonstrate that they can:
if
statements
The text discusses logical expressions in Chapter 3, Section 3.3.4, but we’ve deferred their use until now. You will use them to specify the conditions for selection statements. Remember that you can find the value of an expression by printing it out to the console.
Record your answers to the following questions in a text file called Exercise51
What is the return value of the following expressions (if any)?
Explain your results.true true == "true" false || !false !!true (1/0 == 1) || true true || (1/0 == 1)
What is the return value of the following expressions (if any)?
Explain your results.5 = 5 5 == 5 4 != 5 4 <> 5
Declare an integer variable
i
, initialize it to 5 and then try computing the value of the following expression:
1 <= i <= 100
Record what happens and why. If there is a problem, rewrite the expression so that it performs as intended.
Test your expression by verifying that you get the right answer when
i
is set to different values covering the following cases:
i
is too small;i
is too large;i
is nicely in the range;i
is on the border of the range.Save your answers and submit them with the rest of your lab exercise programs.
if
Statements
Introducing selection statements allows us to greatly expand the range of programs we’re able to program.
Create an animated program called
We suggest that you proceed iteratively as follows:
|
There are, of course, situations in which we would like to choose between two alternatives.
Make a copy of your program from the previous exercise and name it
For this one, you should implement the following, somewhat different algorithm:
Notice that in this algorithm, you always draw a point, but the color is chosen selectively. |
if
Statements
All control statements can be used recursively, and the selection statement is no exception. If you need more than two alternatives, use a selection statement inside another selection statement.
Create a copy of the previous program and call it
Create your own algorithm for this one, and proceed iteratively as follows:
As you complete this exercise, try to create and implement efficient algorithms, i.e., algorithms with no unnecessary elements. |
The following exercise is optional and offers extra credit.
Create a program called
Checkerboard
that implements something like the sample output shown below. The three images show the same animation over time. At
first, it’s not at all clear what’s happening, but the checker-board structure soon becomes apparent.
→ →
This program is a rather straightforward use of the selection statements used in the previous exercises, but the trick it so get the condition expression(s) done just right. The use of integer division and of modulus are critical here.
Submit all the code and supporting files for the exercises in this lab. We will grade this exercise according to the following criteria: