Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


5.4 Find the error in each of the following. [Note: There may be more than one error.]

  1. For ( x = 100, x >= 1, x++ )
      System.out.println( x );
  2. The following code should print whether integer value is odd or even:
    switch ( value % 2 ) {
      case 0:
        System.out.println( "Even integer" );
      case 1:
        System.out.println( "Odd integer" );
    }
  3. The following code should output the odd integers from 19 to 1:
    for ( x = 19; x >= 1; x += 2 )
      System.out.println( x );
  4. The following code should output the even integers from 2 to 100:
    counter = 2;
    do {
      System.out.println( counter );
      counter += 2;
    } While ( counter < 100 );

5.5 What does the following program do?

public class Printing {
  public static void main( String args[] )
  {
    for ( int i = 1; i <= 10; i++ ) {

      for ( int j = 1; j <= 5; j++ )
        System.out.print( ’@’ );

    System.out.println();
    }
  }
}

5.6 Write an application that finds the smallest of several integers. Assume that the first value read specifies the number of values to input from the user.

5.7 Write an application that calculates the product of the odd integers from 1 to 15, then displays the results in a message dialog.

5.8 The factorial method is used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n. Write an application that evaluates the factorials of the integers from 1 to 5. Display the results in tabular format in a JTextArea that is displayed on a message dialog. What difficulty might prevent you from calculating the factorial of 20?

5.9 Modify the compound interest program of Fig. 5.6 to repeat its steps for interest rates of 5, 6, 7, 8, 9 and 10%. Use a for loop to vary the interest rate. Add scrolling functionality to the JTextArea so you can scroll through all the output.

5.10 Write an application that displays the following patterns separately one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( '*' ); (this causes the asterisks to print side by side). A statement of the form System.out.println(); can be used to position to the next line. A statement of the form System.out.print( ' ' ); can be used display a space for the last two patterns. There should be no other output statements in the program. (Hint: The last two patterns require that each line begin with an appropriate number of blanks.)

(A) (B) (C) (D)
* **********
**********
*
** *********
*********
**
*** ********
********
***
**** *******
*******
****
***** ******
******
*****
****** *****
*****
******
******* ****
****
*******
******** ***
***
********
********* **
**
*********
********** *
*
**********

5.11 One interesting application of computers is drawing graphs and bar charts (sometimes called "histograms"). Write an applet that reads five numbers (each between 1 and 30). For each number read, your program should draw a line containing that number of adjacent asterisks. For example, if your program reads the number seven, it should print *******.

5.12 Modify the applet of Fig. 5.11 to draw filled rectangles instead of lines of asterisks. Method fillRect of class Graphics requires the same arguments as method drawRect. Multiply each number entered by the user by 10 to determine the width of the rectangle.

5.13 A mail order house sells five different products whose retail prices are: product 1 – $2.98, product 2–$4.50, product 3–$9.98, product 4–$4.49, and product 5–$6.87. Write an application that reads a series of pairs of numbers as follows:

  1. Product number
  2. Quantity sold for one day

Your program should use a switch structure to help determine the retail price for each product. Your program should calculate and display the total retail value of all products sold last week. Use a TextField to obtain the product number from the user. Use a sentinel-controlled loop to determine when the program should stop looping and display the final results.

5.14 Modify the program in Fig. 5.6 to use only integers to calculate the compound interest. (Hint: Treat all monetary amounts as integral numbers of pennies. Then "break" the result into its dollar portion and cents portion by using the division and modulus operations, respectively. Insert a period.)

5.15 Assume i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? Are the parentheses necessary in each case?

  1. System.out.println( i == 1 );
  2. System.out.println( j == 3 );
  3. System.out.println( i >= 1 && j < 4 );
  4. System.out.println( m <= 99 & k < m );
  5. System.out.println( j >= i || k == m );
  6. System.out.println( k + m < j | 3 - j >= k );
  7. System.out.println( !( k > m ) );

5.16 Write an application that prints a table of the binary, octal, and hexadecimal equivalents of the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix E, first. Place the results in a JTextArea with scrolling functionality. Display the JTextArea in a message dialog.

5.17 Calculate the value of p from the infinite series

Print a table that shows the value of p approximated by one term of this series, by two terms, by three terms, etc. How many terms of this series do you have to use before you first get 3.14? 3.141? 3.1415? 3.14159?

5.18 (Pythagorean Triples) A right triangle can have sides that are all integers. The set of three integer values for the sides of a right triangle is called a Pythagorean triple. These three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse. Write an application to find all Pythagorean triples for side1, side2 and the hypotenuse all no larger than 500. Use a triple-nested for loop that tries all possibilities. This is an example of "brute force" computing. You will learn in more advanced computer science courses that there are large numbers of interesting problems for which there is no known algorithmic approach other than using sheer brute force.

5.19 Modify Exercise 5.10 to combine your code from the four separate triangles of asterisks into a single application that prints all four patterns side by side making clever use of nested for loops.

* **********
**********
*
** *********
*********
**
*** ********
********
***
**** *******
*******
****
***** ******
******
*****
****** *****
*****
******
******* ****
****
*******
******** ***
***
********
********* **
**
*********
********** *
*
**********

 

5.20 (De Morgan’s Laws) In this chapter, we discussed the logical operators &&, &, ||, |, ^ and !. De Morgan’s Laws can sometimes make it more convenient for us to express a logical expression. These laws state that the expression !(condition1 && condition2) is logically equivalent to the expression (!condition1 || !condition2). Also, the expression !(condition1 || condition2) is logically equivalent to the expression (!condition1 && !condition2). Use De Morgan’s Laws to write equivalent expressions for each of the following, and then write a program to show that both the original expression and the new expression in each case are equivalent:

  1. !( x < 5 ) && !( y >= 7 )
  2. !( a == b ) || !( g != 5 )
  3. !( ( x <= 8 ) && ( y > 4 ) )
  4. !( ( i > 4 ) || ( j <= 6 ) )

5.21 Write an application that prints the following diamond shape. You may use output statements that print a single asterisk (*), a single space or a single newline character. Maximize your use of repetition (with nested for structures) and minimize the number of output statements.

*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*

 

5.22 Modify the program you wrote in Exercise 5.21 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond. Your program should then display a diamond of the appropriate size.

5.23 A criticism of the break statement and the continue statement is that each is unstructured. Actually, break statements and continue statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you would remove any break statement from a loop in a program and replace that statement with some structured equivalent. (Hint: The break statement leaves a loop from within the body of the loop. The other way to leave is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates "early exit because of a ‘break’ condition.") Use the technique you developed here to remove the break statement from the program of Fig. 5.11.

5.24 What does the following program segment do?

for ( i = 1; i <= 5; i++ ) {

  for ( j = 1; j <= 3; j++ ) {

    for ( k = 1; k <= 4; k++ )
      System.out.print( '*' );

    System.out.println();
  }

  System.out.println();
}

5.25 Describe in general how you would remove any continue statement from a loop in a program and replace that statement with some structured equivalent. Use the technique you developed here to remove the continue statement from the program of Fig. 5.12.

5.26 ("The Twelve Days of Christmas" Song) Write an application that uses repetition and switch structures to print the song "The Twelve Days of Christmas." One switch structure should be used to print the day (i.e., "First," "Second," etc.). A separate switch structure should be used to print the remainder of each verse.


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


5.4 Find the error in each of the following. [Note: There may be more than one error.]

  1. For ( x = 100, x >= 1, x++ )
      System.out.println( x );

    ANS: The F in for should be lowercase. Semicolons should be used in the for header instead of commas. ++ should be --.
  2. The following code should print whether integer value is odd or even:
    switch ( value % 2 ) {
      case 0:
        System.out.println( "Even integer" );
      case 1:
        System.out.println( "Odd integer" );
    }

    ANS: A break statement should be placed in case 0.
  3. The following code should output the odd integers from 19 to 1:
    for ( x = 19; x >= 1; x += 2 )
      System.out.println( x );

    ANS: += should be -=.
  4. The following code should output the even integers from 2 to 100:
    counter = 2;
    do {
      System.out.println( counter );
      counter += 2;
    } While ( counter < 100 );

    ANS: The W in While should be lowercase. < should be <=.

5.6

// Exercise 5.6 Solution
// Small.java
// Program finds the smallest of several letters
import javax.swing.JOptionPane;

public class Small {

   public static void main( String args[] )
   {
      int smallest = 0, temp = 0, number;
      String input;

      input = JOptionPane.showInputDialog(
         "Enter number of integers:" );
      number = Integer.parseInt( input );

      if ( number == 0 )
         System.exit( 0 ); 
        
      for ( int x = 1; x <= number; x++ ) {         
         input = JOptionPane.showInputDialog(
            "Enter integer:" );
         temp = Integer.parseInt( input );
         
         if ( x == 1 ) 
            smallest = temp; 
         else if ( temp < smallest )
            smallest = temp;
      }
     
      JOptionPane.showMessageDialog(
         null, "Smallest Integer is: " + smallest,
         "Result", JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

5.8

// Exercise 5.8 Solution
// Factorial.java
// Program calculates factorials
import javax.swing.*;

public class Factorial {
   public static void main( String args[] )
   {
      JTextArea outputArea = new JTextArea( 5, 10 );
      int fact;
      String output = "X\tX!\n";
      
      for ( int z = 1; z <= 5; z++ ) {
         fact = 1;

         for ( int w = 1; w <= z; w++ )
            fact *= w;

         output += "\n" + z + "\t" + fact;
      }

      outputArea.setText( output );
      JOptionPane.showMessageDialog(
            null, outputArea, "Factorial", 
            JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

5.11

// Exercise 5.11 Solution
// Graphs.java
// Program prints histograms
import javax.swing.*;
import java.awt.Graphics;

public class Graphs extends JApplet {   
   int num1, num2, num3;
   int num4, num5;

   public void init()
   {
      String input;
      int temp;

      for( int i = 1; i <= 5; i++ ) {
         input = JOptionPane.showInputDialog( "Enter number:" );
         temp = Integer.parseInt( input );

         if ( temp >= 1 && temp <= 30 ) {

            switch ( i ) {
               case 1:
                  num1 = temp;
                  break;
               case 2:
                  num2 = temp;
                  break;
               case 3:
                  num3 = temp;
                  break;
               case 4:
                  num4 = temp;
                  break;
               case 5:
                  num5 = temp;
                  break;
            }
         }         
         else 
            JOptionPane.showMessageDialog(
                null, "Must be between 1 and 30",
                "Error", JOptionPane.ERROR_MESSAGE );
      }
   }

   public void paint( Graphics g )
   {
      int x, y = 0, value = 0;

      for ( int i = 1; i <= 5; i++ ) {
         x = 5;

         switch ( i ) {
            case 1:
               y = 50;
               value = num1;
               break;
            case 2:
               y = 60;
               value = num2;
               break;
            case 3:
               y = 70;
               value = num3;
               break;
            case 4:
               y = 80;
               value = num4;
               break;
            case 5:
               y = 90;
               value = num5;
               break;
         }

         for ( int j = 1; j <= value; j++ )
             g.drawString( "*", x += 5, y );
      }
   }
}

5.15 Assume i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? Are the parentheses necessary in each case?

  1. System.out.println( i == 1 );
    ANS: True.
  2. System.out.println( j == 3 );
    ANS: False.
  3. System.out.println( i >= 1 && j < 4 );
    ANS: True.
  4. System.out.println( m <= 99 & k < m );
    ANS: False.
  5. System.out.println( j >= i || k == m );
    ANS: True.
  6. System.out.println( k + m < j | 3 - j >= k );
    ANS: False.
  7. System.out.println( !( k > m ) );
    ANS: False.

5.17

// Execise 5.17 Solution
// Pi.java
// Program calculates Pi
import javax.swing.*;

public class Pi { 
   public static void main( String args[] )
   {
      double piValue = 0, num = 4.0, denom = 1.0;
      int accuracy = 400000;
       
      JTextArea outputArea = new JTextArea( 17, 40 );
      JScrollPane scroller = new JScrollPane( outputArea );
      String output = "Accuracy: " + accuracy;
      output += "\nTerm\t\tPi\n";
      
      for ( int term = 1; term <= accuracy; term++ ) {

         if ( term % 2 != 0 )
            piValue += num / denom;
         else
            piValue -= num / denom;

         output += "\n" + term + "\t\t" + piValue;
         denom += 2.0;
      }

      outputArea.setText( output );
      JOptionPane.showMessageDialog(
            null, scroller, "PI", 
            JOptionPane.INFORMATION_MESSAGE );
      System.exit( 0 );
   }
}

5.20

// Exercise 5.20 Solution
// DeMorgan.java
// Program tests DeMorgan's laws
import javax.swing.JOptionPane;

public class DeMorgan {

   public static void main( String args[] )
   {
      int x = 6, y = 0;
      String result = "";
      // part a
      if ( !( x < 5 ) && !( y >= 7 ) )
         result += "\n!( x < 5 ) && !( y >= 7 )";

      if ( !( ( x < 5 ) || ( y >= 7 ) ) )
         result += "\n!( ( x < 5 ) || ( y >= 7 )";

      int a = 8, b = 22, g = 88;

      // part b
      if ( !( a == b ) || !( g != 5 ) )
         result += "\n!( a == b ) || !( g != 5 )";

      if ( !( ( a == b ) && ( g != 5 ) ) )
         result += "\n!( ( a == b ) && ( g != 5 ) )";

      x = 8;
      y = 2;

      // part c
      if ( !( ( x <= 8 ) && ( y > 4 ) ) )
         result += "\n!( ( x <= 8 ) && ( y > 4 ) )";

      if ( !( x <= 8 ) || !( y > 4 ) )
         result += "\n!( x <= 8 ) || !( y > 4 )";

      int i = 0, j = 7;

      // part d
      if ( !( ( i > 4 ) || ( j <= 6 ) ) )
         result += "\n!( ( i > 4 ) || ( j <= 6 ) )";

      if ( !( i > 4 ) && !( j <= 6 ) )
         result += "\n!( i > 4 ) && !( j <= 6 )";

      JOptionPane.showMessageDialog(
            null, result, "DeMorgan's Laws", 
            JOptionPane.INFORMATION_MESSAGE );
      System.exit( 0 );
   }
}

5.26

// Exercise 5.26 Solution
// Twelve.java
// Program prints the 12 days of Christmas song
import javax.swing.*;

public class Twelve {

   public static void main( String args[] )
   {
      String result = "";
      JTextArea outputArea = new JTextArea( 17, 40 );
      JScrollPane scroller = new JScrollPane( outputArea );

      for ( int day = 1; day <= 12; day++ ) {
          result += "\nOn the " + day;

          switch( day ) {
             case 1:
                result += "st";
                break;            
             case 2:
                result += "nd";
                break;  
             case 3:
                result += "rd";
                break;  
             default: 
                result += "th";
                break;
          }
          result += " day of Christmas, my true love gave to me: ";

          switch( day ) {
             case 12:
                result += "   Twelve lords-a-leaping, ";
             case 11:
                result += "   Eleven pipers piping, ";
             case 10:
                result += "   Ten drummers drumming, ";
             case 9:
                result += "   Nine ladies dancing, ";
             case 8:
                result += "   Eight maids-a-milking, ";
             case 7:
                result += "   Seven swans-a-swimming, ";
             case 6:
                result += "   Six geese-a-laying, ";
             case 5:
                result += "   Five golden rings.";
             case 4:
                result += "   Four calling birds, ";
             case 3:
                result += "   Three French hens, ";
             case 2:
                result += "   Two turtle doves, and ";
             case 1:
                result += "   a Partridge in pear tree.";          
          }
      }

      outputArea.setText( result );
      JOptionPane.showMessageDialog(
            null, scroller, "Twelve Days of Christmas", 
            JOptionPane.INFORMATION_MESSAGE );
      System.exit( 0 );
   }
}