Programming Fundamentals in Java

Module [103] - Iterative Statements

The previous module introduced you to controlling the flow of execution of a program by using conditional statements. We are now going to study iterative statements and learn to solve problems with programs which use one or several loops in various arrangements with respect to one another;

  • Serial arrangement - i.e. one after the other
  • Nested arrangement - i.e. one inside the other
Once again we will use the Raptor flowchart interpreter to write programs of increasing complexity.

  • Textbook Reading Assignments
  • The following sections of the textbook are assigned for this module.
    • This module does not use the textbook
  • Lecture - Video
  • File Link: YouTube
  • As is usual for longer videos, here are links to the main parts;
  • Lecture - Slides
  • File Link: 103-lecture.ppt
  • These are the slides used in the above video lecture
  • Wrapup Session - Video
  • File Link: YouTube
  • As is usual for longer videos, here are links to the main parts; Please note that around the 45 minutes mark, the table on screen shows a condition "N = 10" but it is a typo as the condition we actually implemented in the Raptor flowchart is "N = 70". A big thank you to Emily for spotting this mistake!

Module Learning Outcomes

In this module, you will develop further your programming skills as follows;

Tracing
Ability to read and trace Raptor programs leveraging conditional expressions and Iterative statement.
Implementing
Ability to write Raptor programs leveraging conditional expressions and Iterative statements.
Testing
Ability to develop tests, on paper for now, that are going to allow us to ensure Raptor programs leveraging Iterative statements and conditional expressions computes the results expected by requirements.
Debugging
Ability to troubleshoot Raptor programs leveraging conditional expression and Iterative statements.
Designing
Ability to design Raptor programs leveraging conditional expressions and Iterative statements.

Let us start by some relevant resources;

  • Raptor Syntax Slides
  • PDF Link: raptor-2.pdf
  • These slides summarize the main syntax used by Raptor; e.g. random
  • Raptor Control Structures
  • PDF Link: raptor-3.pdf
  • Another hand-out from Dr. Wayne Brown. Now you may look at both types of control-flow structures.

Now, you should be ready to jump in our apprenticeship exercises;

  • A01 - Iterative Hello World
  • File Link: YouTube
  • Write a Raptor program which uses a loop statement to display 9 times the message "hello there" in the master console. You will use a variable counter which will be assigned the value 1 before the loop statement. During the loop statement, you will display the above-message, increment counter by 1 and then keep looping until counter becomes greater strict than 9.
  • A02 - Improvement - Display counter values
  • File Link: YouTube
  • Modify the previous program so that the value of the variable counter is displayed, during each iteration, along with the message itself. Modify again your code so that the counter variable is incremented by 2 instead of 1 during each iteration. Run it again and verify that it is working by looking at the output.
  • A03 - Improvement - Serially arranged Loops
  • File Link: YouTube
  • Add a second loop to the previous program right after where the first one finishes. This second loop will count down from the current value of the variable counter to 0. At each iteration, the value of the variable counter will again be displayed to allow us to verify the program runs as expected. Both loops therefore use the same variable.
  • A04 - Guess the number
  • File Link: YouTube
  • The "guess the number" game consists in having someone ("player #1") pick a number between 1 and 100 and someone else ("player #2") try to guess it. For each guess, the first player responds by telling whether the secret number is bigger or smaller than the guess. Once the guess is equal to the secret number, the game is over and the second player won. Implement a program which asks the user (that will have to be player #1) for a secret number and store it in the variable secret. Then, you will keep accepting guesses from another user (player #2) and store them in a variable guess. After each guess attempt, you will compare guess to secret and display a message indicating whether the guess is "too big", "too small" or "equal". You will stop iterating when the latter case is met and display a "you just won" message. Test your program to ensure that this new feature is working.
  • A05 - Improvement - Keeping Scores
  • File Link: YouTube
  • Modify the previous program so that you display the number of trials that were necessary for player #2 to guess the secret number. You will use a counter variable named nbtrials to keep track of the number of guess attempts made by player #2. Test your program to ensure that this new feature is working.
  • A06 - Improvement - Give-up Option
  • File Link: YouTube
  • Modify your previous program so that now the player #2 can give up at any time by entering a value of -1 as guess. This will cause the loop to terminate and you will display "you lost after N trials" instead of the winning message. Test your program to ensure that this new feature is working.
  • A07 - Improvement - Max number of trials
  • File Link: YouTube
  • Modify the previous program so that it asks player #1 for a maximum number of trials (store it in variable maxtrials) before to even ask player #1 for the secret number. You will make sure that player #2 is not allowed more than maxtrials guesses. Also, your program must display after each guess "you have N guesses left". If player #2 uses up all his/her maxtrials number of guesses, you will display the message indicating that they lost. Test your program to ensure that this new feature is working.
  • A08 - Nested Loops
  • File Link: YouTube
  • Write a program which uses nested loops to displays the multiplication tables from 1 to 9. Here's a sample of what the output should look like:
    Multiplication table for 1:
    
    1 times 1 equals 1
    1 times 2 equals 2
    1 times 3 equals 3
    ...lines of output are omitted here...
    
    Multiplication table for 9:
    
    9 times 1 equals 9
    9 times 2 equals 18
    9 times 3 equals 27
    ...lines of output are omitted here...
    
    Test your program to ensure that this new feature is working.
  • A09 - More Nested Loops
  • File Link: YouTube
  • Write a program which prompts the user for a positive integer x between 1 and 10 and display on the screen a line of x stars. You will keep doing so until the user enters the value 0, meaning the program has to stop. If any other value is entered, you will display an error message. Hint - In order to display a line consisting of as many * than the user specified, you will need an inner counter-based iteration. Test your program to ensure that this new feature is working.
  • B01 - x to the y power
  • Write a Raptor program which prompts the user for two positive, non-null integer values (x and y). It will then compute & display x to the power of y. You will use the following pseudo code:
    • Step #1 tmp is assigned 1
    • Step #2 Repeat y times: tmp = tmp * x
    • Step #3 Display tmp
    Test your program to ensure it is working properly
  • B02 - Displaying a Powers Table
  • How would you reuse the program you previously developed along with the program from exercise 103-A08 in order to display a "table of powers" instead of a multiplication table? The output should look something like;
    Power table for 1: 
    
    1 power 1 equals 1
    1 power 2 equals 1 
    1 power 3 equals 1
    ...Some Lines of output are omitted here...
    
    Power table for 9:
    
    9 power 1 equals 9
    9 power 2 equals 81
    9 power 3 equals 729 
    
    ...Lines of output are omitted here...
    
    Test your program to ensure it is working properly.
  • B03 - Sentinel Controlled Iterations
  • Write a program which prompts the user for an integer between -10 and +10 (positive, negative or null) until 0 is entered at which point you will output;
    • The total number of integers that were entered by the user (not including the sentinel value)
    • How many of them were positive
    • How many of them were negative.
    To keep track of how many positive and negative numbers were entered; use two counter variables POS and NEG which you will increment appropriately depending on the sign of the integer you just read from the user. Test your program to ensure it is working properly.
  • B04 - Improvement - Min & Max
  • Improve the previous program so that you also keep track of (and display at the end of your program) the smallest value entered in a variable min_num and the largest one in a variable max_num. Each time an integer is entered, compare it to your current max_num and min_num values and replace them as appropriate. At the beginning of your program, max_num will be assigned a small number (-99) so that the first integer entered by the user will become the max_num. Similarly, min_num will be initialized with +99 so that the first integer entered by the user will be the new min_num. Test your program to ensure it is working properly.
  • B05 - Integer Division
  • Write a program which starts by asking two positive, non-zero, integer values from the user and store them in two variables. You will then use a loop and as many variables as needed to count how many times the smallest number fits inside of the largest. To do so you will repeatedly subtract the smallest integer from the largest one until the result is negative. This program will pretty much simulate an integer division and display the result on the screen. Test your program to ensure it is working properly. Here are some examples of expected results;
     
    ____________________________________________________________________
    | Value for   | Value for | Expected | Observed | Test Successful? |
    | 1st number  | 2nd number| outcome  | outcome  |                  |
    |_____________|___________|__________|__________|__________________|
    |     5       |   10      |    2     |          |                  |
    |_____________|___________|__________|__________|__________________|
    |     10      |    5      |    2     |          |                  |
    |_____________|___________|__________|__________|__________________|
    |     10      |    4      |    2     |          |                  |
    |_____________|___________|__________|__________|__________________|
    |     10      |    3      |    3     |          |                  |
    |_____________|___________|__________|__________|__________________|
    
  • B06 - Improved BlackJack
  • This exercise was suggested by Colton Lancsarics in Summer 2015
    We want to extend the "Blackjack or not?" Homework [102-B03] & [102-B04]. Instead of just testing whether two numbers give us blackjack or not, we want to write a program which will repeat the following actions;
    • Generate a random card value, i.e. between [1:11]
    • Add it to a variable representing the total points value of our hand, which was initialized to 0 to start off with
    • Increment a counter representing our hand size by one. This counter was also initialized to 0 to start off with
    • Display the value we just drew, the current total, and the handsize
    These actions will be repeated as long as we do not exceed the maximal hand-size of 5 cards, do not reach or exceed a total number of points of 21 for our hand. When the loop is over, we will use IF statements to figure out why we broke out of the loop;
    • Exceeded 21 points
    • Reached exactly 21 points
    • Exceeded the maximal hand-size
    We will then display an appropriate message to let the user know what happened.
    Test your program to ensure it is working properly.

For the above homework exercise, you will need to be able to generate a random number. Raptor provides you with a keyword named Random that you may use in any expression wherever you would use a variable. Raptor will automatically generate a random floating point number between 0 (included) and 1 (excluded). This number will be used wherever you inserted Random in your expression.

Since Random is replaced by a random floating point number in the range [0:1), you may add a constant to it in order to shift the range. Consider the following example;

 
n <-- Random + 3

The variable n is assigned a random floating point number in the range [3:4). We simply added 3 to the boundaries of the initial range [0+3 : 1+3).

In the above example, the floating point random number is generated between two different values but the difference between the smallest and largest random number is the same than in the initial range.

Similarly, we may extend the range by multiplying Random as illustrated in the example below;

n <-- Random * 5

The variable n will now be assigned a random floating point number in the range [0:5).

You may combine both tricks to both extend and shift the range. The following illustrates how we may get a random floating point number between 20 and 30;

n <-- Random * 10 + 20

So, to summarize, if you want to obtain a random floating point number in the range [X:y), you will do the following;

n <-- Random * X + Y

If you need a random integer value in the range [X:Y) instead, you will simply have to apply the floor function as follows;

n <-- floor( Random * X + Y )