| 1. | P1. Simple Loops
 Often it is necessary to repeat a portion of coding several times in a program. A simple loop can automate the repetition. Here is a program that computes the number of digits needed to represent a number in base 10.
 
 
 /*
 Count number of digits needed to express an integer in base 10
 using multiple if statements
 */
 public static void main(String[] args)
 {
 String input = JOptionPane.showInputDialog(
 "Input an integer between 1 and 9999");
 int n = Integer.parseInt(n):
 if (n < 1 || n > 9999) return;
 
 int temp = n;
 int d = 1;
 
 if (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 if (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 if (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 if (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 System.out.println(input + " can be expressed in " + d + " digits");
 System.exit(0);
 }
 
 
 Repeating the section below four times, even using copy/paste, is tedious, and the coding works only for input <= 9999.
 
 if (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 It is helpful to have a way of testing that the input is greater than 1, and to execute the succeeding control block if it is. Replacing if with while does this.
 
 
 /*
 Count number of digits needed to express an integer in base 10
 using while loop
 */
 public static void main(String[] args)
 {
 String input = JOptionPane.showInputDialog(
 "Input an integer between 1 and 9999:");
 int n = Integer.parseInt(n):
 if (n < 1 || n > 9999) return;
 
 int d = 1;
 int temp = n;
 
 while (temp > 9)
 {
 temp = temp / 10;
 d++;
 }
 
 System.out.println(input + " can be expressed in " + d + " digits");
 System.exit(0);
 }
 
 
 The fractions 1/2, 1/4, 1/8 get closer and closer to 0 as they are divided by two. Change the previous program to count the number of divisions by two needed to be within 0.0001 of zero.
 
 
 
 Answer:
 
 |