As you have seen in some of the preceding examples, one loop can be nested inside of another. Nested loops are used to solve a wide variety of programming problems and are an essential part of programming. So, before leaving the topic of Java’s loop statements, let’s look at one more nested loop example. The following program uses a nested for loop to find the factors of the numbers from 2 to 100.
/*
Use nested loops to find factors of numbers between 2 and 100.
*/
class FindFac
{
public static void main(String args[])
{
for(int i=2; i <= 100; i++)
{
System.out.print("Factors of " + i + ": ");
for(int j = 2; j < i; j++)
if((i%j) == 0)
System.out.print(j + " ");
System.out.println();
}
Friday, December 14, 2018
Nested Loops
December 14, 2018
No comments
}
}
Here is a portion of the output produced by the program:
Factors of 2:
Factors of 3:
Factors of 4: 2
Factors of 5:
Factors of 6: 2 3
Factors of 7:
Factors of 8: 2 4
Factors of 9: 3
Factors of 10: 2 5
Factors of 11:
Factors of 12: 2 3 4 6
Factors of 13:
Factors of 14: 2 7
Factors of 15: 3 5
Factors of 16: 2 4 8
Factors of 17:
Factors of 18: 2 3 6 9
Factors of 19:
Factors of 20: 2 4 5 10
In the program, the outer loop runs i from 2 through 100. The inner loop successively tests all numbers from 2 up to i, printing those that evenly divide i. Extra challenge: The preceding program can be made more efficient.
Can you see how?
(Hint: the number of iterations in the inner loop can be reduced.)
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment