JMU JMU - Department of Computer Science
Help Tools
Lab: Gaining Experience with Nested and Sequential Loops


Instructions: Answer the following questions one at a time. After answering each question, check your answer (by clicking on the check-mark icon if it is available) before proceeding to the next question.

Getting Ready: Before going any further, you should:

  1. Depending on your development environment, create either a directory or a project for this lab.
  2. Setup your development environment.
  3. Download the following files:
    to an appropriate directory/folder. (In most browsers/OSs, the easiest way to do this is by right-clicking/control-clicking on each of the links above.)

1. Review: This part of the lab will help you remember some things that we have covered previously.
  1. In lecture we discussed the following code fragment for printing an addition table:
        int      column, row, sum;
      
        JMUConsole.open();
        // Print an addition table
        //
        for (row=0; row<5; row++)
        {
            for (column=0; column<5; column++) 
            {
                sum = row + column;
                JMUConsole.printf(" %2d ", sum);
            }
            JMUConsole.printf("\n");
        }
        JMUConsole.close();
        

    Review this code fragment and make sure you understand it.

  2. Create a class named AdditionTable that includes this fragment in main().
  3. Compile and execute AdditionTable.
  4. Modify AdditionTable so that the size of the table can be changed. Specifically, modify it so that the user can set the size of the table (which will always be square) by passing main() a command-line argument. You may assume that the size will always be less than 15. If no command-line argument is given, the table must be of size 10.
2. Producing Tables: This part of the lab will give you some experience using nested loops to produce formatted tables.
  1. Modify AdditionTable so that it can be used to generate an addition table that is formatted as follows:
       + | 0   1   2   3   4
     ------------------------
       0 | 0   1   2   3   4
       1 | 1   2   3   4   5
       2 | 2   3   4   5   6
       3 | 3   4   5   6   7
       4 | 4   5   6   7   8
        

    Suggestion: Do not work on the whole problem at once. First write the loop that will print the column headers. Then modify the nested loops that will print the body of the table.


    AdditionTable.java
    import java.lang.reflect.*;
    
    /**
     * An application that prints addition tables
     *
     * @author  Prof. David Bernstein, James Madison University
     * @version 1.0
     */
    public class AdditionTable
    {
        /**
         * The entry point
         *
         * @param args   The command-line arguments
         */
        public static void main(String[] args)
        {
           int      column, row, size, sum;
    
           JMUConsole.open();
           
           if (Array.getLength(args) < 1) size = 10;
           else size = Text.toNonnegativeInt(args[0]);
    
           // Print the column headers
           JMUConsole.printf(" %2s |","+");
           for (column=0; column<size; column++)
           {
              JMUConsole.printf(" %2d ", column);
           }
           JMUConsole.printf("\n");
    
    
    
           // Print the horizontal line
           JMUConsole.printf("-%2s--", "--");
           for (column=0; column<size; column++)
           {
              JMUConsole.printf("-%2s-", "--");
           }
           JMUConsole.printf("\n");
    
    
    
           // Print the table
           for (row=0; row<size; row++)
           {
              JMUConsole.printf(" %2d |", row);
    
              for (column=0; column<size; column++) 
              {
                 sum = row + column;
                 JMUConsole.printf(" %2d ", sum);
              }
              JMUConsole.printf("\n");
           }
    
           JMUConsole.close();
        }
    }
            
    Expand
3. Different Kinds of Loops: This part of the lab will give you some experience with do-while loops.
  1. Write an application named AndTable that can be used to generate a "truth table" for the && operator that is formatted as follows:
        true  false
        false false
        

    Your solution must use nested do-while loops. (Hint: Think carefully about the initialization and update statements in the do-while loop.)


    See the answer to the next question in this section.
    Expand
  2. Modify your answer to the previous question in such a way that the "truth table" will be formatted as follows:
       &&   | true  false
     ----------------------
      true  | true  false
      false | false false
        

    Again, your solution must use only do-while loops.


    I could have made use of the fact there are just two boolean values and used an int to control the loop. But, it's much more instructive to use a boolean value and "increment" it.
    AndTable.java
    /**
     * An application that prints the truth table for logical AND
     *
     * @author  Prof. David bernstein, James Madison University
     * @version 1.0
     */
    public class AndTable
    {
        /**
         * The entry point
         *
         * @param args   The command-line arguments
         */
        public static void main(String[] args)
        {
           boolean      and, column, row;
            
           JMUConsole.open();
           
           // Print the column headers
           JMUConsole.printf(" %5s |","&&");
    
           column=true;
           do
           {
              JMUConsole.printf(" %5s ", column);
              column = !column;
    
           } while (!column);
    
           JMUConsole.printf("\n");
    
    
    
    
           // Print the horizontal line
           JMUConsole.printf("-%5s--", "-----");
    
           column = true;
           do
           {
              JMUConsole.printf("-%5s-", "-----");
              column = !column;
    
           } while (!column);
    
           JMUConsole.printf("\n");
    
    
    
    
           // Print the table
           row = true;
           do
           {
              JMUConsole.printf(" %5s |", row);
    
              column = true;
              do
              {
                 and = row && column;
                 JMUConsole.printf(" %5s ", and);
                 column = !column;
    
              } while (!column);
    
              JMUConsole.printf("\n");
    
              row = !row;
    
           } while (!row);
    
           JMUConsole.close();
        }
    }
            
    Expand
4. Different Kinds of Truth Tables: This part of the lab will give you some experience with if statements inside of loops.
  1. Rename AndTable to LogicalOpTable and modify the code appropriately.
  2. Modify LogicalOpTable so that it can be passed a String representation of an operator (i.e., "&&" or "||") to use and will generate the appropriate "truth table" for that operator.

    Your solution must again use nested do-while loops. (Hint: Recall that the Text class has a charAt() function that is passed a String and an int and returns the char that is in that String at that position. For example, Text.charAt("CS", 0) will return 'C'.)


    LogicalOpTable.java
    import java.lang.reflect.*;
    
    
    /**
     * An application that prints a truth table
     *
     * @author  Prof. David bernstein, James Madison University
     * @version 1.0
     */
    public class LogicalOpTable
    {
        /**
         * The entry point
         *
         * args[0] should be "&&" to create an AND table and
         * "||" to create a logical OR table
         *
         * @param args   The command-line arguments
         */
        public static void main(String[] args)
        {
           boolean      result, column, row;
           char         op;
    
           JMUConsole.open();
            
           if (Array.getLength(args) == 0) op = '&';
           else                            op = '|';
    
           // Print the column headers
           JMUConsole.printf(" %4s%1s |",op,op);
    
           column=true;
           do
           {
              JMUConsole.printf(" %5s ", column);
              column = !column;
    
           } while (!column);
    
           JMUConsole.printf("\n");
    
    
    
    
           // Print the horizontal line
           JMUConsole.printf("-%5s--", "-----");
    
           column = true;
           do
           {
              JMUConsole.printf("-%5s-", "-----");
              column = !column;
    
           } while (!column);
    
           JMUConsole.printf("\n");
    
    
    
    
           // Print the table
           row = true;
           do
           {
              JMUConsole.printf(" %5s |", row);
    
              column = true;
              do
              {
                 if (op == '&') result = row && column;
                 else           result = row || column;
                 
                 JMUConsole.printf(" %5s ", result);
                 column = !column;
    
              } while (!column);
    
              JMUConsole.printf("\n");
    
              row = !row;
    
           } while (!row);
    
           JMUConsole.close();
        }
    }
            
    Expand
Note: This part of the lab allows you to "go further" on this material. It is neither required nor for extra credit. It will, however, help you gain a deeper understanding of the material.
5. Using Other Kinds of Loops:
  1. Modify your answer to the "addition table" question so that it uses while loops instead of for loops.
  2. Modify your answer to the "truth table" question so that it uses while loops instead of do-while loops.

Copyright 2020