Computer Program Reading Comprehension Project
U of T Computer Program Reading Comprehension Project
For Loops 102
Executes a complex loop structure that has many nested loops. This program will challenge your analytical skills in programming.

Download files: ForLoops102.java
Areas: Nested loops.


ForLoops102.java
1import java.io.*;
2
3
4/**
5 * A good for loop example.
6 */
7public class ForLoops102 {
8
9  public static void doSomething(int n) {
10    int count = 1;
Displaying 10 of 39 lines
View full source


Question 1
What will be printed if doSomething(1) is called?
Hints Solution

Question 2
Suppose that doSomething(7) is called and the first loop begins to execute for the first time (so that i is 1). How many iterations will the second loop make before i is changed again?
Hints Solution

Question 3
Suppose that doSomething(13) is called and the first loop begins to execute for the first time (so that i is 1). How many times will line 22 be executed before i is changed again?
Hints Solution

Question 4
How many times is the expression count += 5 executed when doSomething( (m+1) * m ) is called?
Hints Solution

Question 5
How many nested for loops are there in the function doSomething(int n)?
Hints Solution

Question 6
Look at each of the 4 for loops. Work out a formula for the number of times the loop body is executed before the loop terminates, for any value of n >= 2.
Hints Solution

Question 7
Out of the four for loops, which loop will always make at most one iteration?
Hints Solution

Question 8
Which for loop can be replaced by its loop body such that the function will perform the same calculations as before.
Hints Solution