The answers given for exercies 1-5 are examples only. Any program that
a) uses a for
loop and b) produces the correct output is
correct.
1 class Ex31 { 2 3 // Model answer to Exercise 3.1 4 public static void main(String[] args) { 5 for (int i = -10; i < 9; i = i + 3) { 6 System.out.println(i); 7 } 8 } 9 }
1 class Ex32 { 2 3 // Model answer to Exercise 3.2 4 public static void main(String[] args) { 5 for (int i = 1; i < 8; i = i + 1) { 6 System.out.println(i * 3); 7 } 8 } 9 }
1 class Ex33 { 2 3 // Model answer to Exercise 3.3 4 public static void main(String[] args) { 5 for (int i = 128; i > 0; i = i / 2) { 6 System.out.println(i); 7 } 8 } 9 }
1 class Ex34 { 2 3 // Model answer to Exercise 3.4 4 public static void main(String[] args) { 5 for (int i = 1, j = 0, k = 0; i < 22; k = i, i = i + j, j = k) { 6 System.out.println(i); 7 } 8 } 9 }
1 import java.io.*; 2 3 class Ex35 { 4 5 // Model answer to Exercuse 3.5 6 public static void main(String[] args) throws IOException, NumberFormatException { 7 int x; 8 String num; 9 BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 10 11 System.out.print("Please enter an integer: "); 12 num = in.readLine(); 13 x = Integer.parseInt(num); 14 15 for (int i = 0; i <= 2 * x; i = i + 1) { 16 System.out.println(i); 17 } 18 } 19 }