Loops
Objective:
In this assignment, you will create a Java program. Requirements are given below. This assignment will test your knowledge of Control Flow (Conditional) Statements and loops in Java.
Tasks:
1: Print a Multiplication Table
Write a program that uses nested for loops to print a multiplication table.
2
4
6
8
10
12
14
16
18
20
22
24
3
6
9
12
15
18
21
24
27
30
33
36
4
8
12
16
20
24
28
32
36
40
44
48
5
10
15
20
25
30
35
40
45
50
55
60
6
12
18
24
30
36
42
48
54
60
66
72
7
14
21
28
35
42
49
56
63
70
77
84
8
16
24
32
40
48
56
64
72
80
88
96
9
18
27
36
45
54
63
72
81
90
99
108
10
20
30
40
50
60
70
80
90
100
110
120
11
22
33
44
55
66
77
88
99
110
121
132
12
24
36
48
60
72
84
96
108
120
132
144
2: Find the Greatest Common Divisor
Write a program that prompts the user to enter two positive integers, and find their greatest common divisor (GCD).
Examples:
Enter 2 and 4. The gcd is 2.
Enter 16 and 24. The gcd is 8.
How do you find the gcd?
Name the two input integers n1 and n2.
You know number 1 is a common divisor, but it may not be the gcd.
Check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2.
3: Predict Future Tuition
Suppose the tuition for a university is $10,000 for the current year and increases by 7 percent every year. In how many years will the tuition be doubled?
0
$10,000
1
tuition = 1.07 * tuition
...
tuition = 1.07 * tuition
...
tuition = 1.07 * tuition
...
...
$20,000 or more
package PracticeAssignment;
import java.util.Scanner;
public class Loops {
public static void main(String[] args) {
// Print a Multiplication Table
for (int i = 1; i <= 12; i++) {
for (int j = 1; j <= 12; j++) {
System.out.print((i * j) + " ");
}
System.out.println();
}
// Find the Greatest Common Divisor
Scanner input = new Scanner(System.in);
System.out.print("Enter n1: ");
int n1 = input.nextInt();
System.out.print("Enter n2: ");
int n2 = input.nextInt();
int commonDivisor = 1;
int k = 2;
while (true) {
if (k > n1 || k > n2) {
break;
}
if (n1 % k == 0 && n2 % k == 0) {
commonDivisor = k;
}
k ++;
}
System.out.println("The gcd is " + commonDivisor);
// Predict Future Tuition
double tuition = 10000;
int year = 0;
while (true) {
if (tuition >= 20000) {
break;
}
tuition = 1.07 * tuition;
year++;
}
System.out.println("Year " + year);
}
}
Last updated