user2860326
user2860326

Reputation: 33

Counting iterations

I am working on a homework problem and it is asking how many times this code displays the word "Message" in the console. I don't understand how to solve this.

For i As Integer = 1 To 10 Step 1
  For j As Integer = i To 10 Step 1
    Console.WriteLine("Message")
  Next
Next

Upvotes: 0

Views: 111

Answers (3)

NoChance
NoChance

Reputation: 5752

As has been shown by other answers, the number of iterations is 34 * (78/2) = 1326. To gain more understanding of what is going on, I suggest you write your code as below and watch how the values if i, j, k change - Here K is showing the current iteration number - Pay special attention to the last line:

Dim k As Integer = 1
For i As Integer = 1 To 34
    For j As Integer = 1 To 78 Step 2
        Console.WriteLine("Message" & " i:" & i.ToString() & " j:" & j.ToString() & " k:" & k.ToString())
        k += 1
    Next
Next

You will see output like:

Message i:1 j:1 k:1

Message i:1 j:3 k:2

Message i:1 j:5 k:3

Message i:1 j:7 k:4

Message i:1 j:9 k:5

...

Message i:34 j:75 k:1325

Message i:34 j:77 k:1326

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34846

The outer loop executes 34 times, because it starts at 1 and increments by 1 each time stopping at 34, because the 35th iteration will exceed the upper limit on the loop of 34.

The inner loop executes 39 times, because it starts at 1 and increments by 2 each time (1, 3, 5, 7, etc.), stopping when the value is greater than 78, but since 40th iteration will equal a value of 79, which is greater than 78 it will not execute the 40th iteration.

34 times 39 = 1,326, so you will see the message Message written 1,326 times in the console.

In general terms, you can break it down to this:

i * (j / 2)

where i equals outer loop iterations (34) and j equals inner loop iterations (78 / 2 = 39).

Upvotes: 1

Michael Yaworski
Michael Yaworski

Reputation: 13483

1326 times

The inner loop iterates 39 times (78 numbers / 2 step), and the outer loop iterates 34 times (34 numbers / 1 step). The outer loop will iterate 34 times, and each time, the inner loop will also iterate. So:

34 outer loop iterations * 39 inner loop iterations (each time) = 1326.

Upvotes: 0

Related Questions