Asked by akash

Q 7: What is the number of `Hello's printed by the pseudo code below? (for i from lo to hi
exhaust i between lo and hi inclusive, and is a empty loop when lo is greater than hi)
(b) for i from 1 to 10
for j from i to 10
for k from i to j
print `Hello'

Answers

Answered by plumpycat
Try some samples to see:
i = 1, j = 1: k from 1 to 1 --> 1 Hello
i = 1, j = 2: k from 1 to 2 --> 2 Hellos
i = 1, j = 3: k from 1 to 3 --> 3 Hellos
.
.
.
i = 1, j = 10: k from 1 to 10 --> 10 Hellos
So for i = 1, sum the numbers from 1 to 10 (triangular formula): (10)(10 + 1)/2 = 55 Hellos

Now try for i = 2:
i = 2, j = 1: k from 2 to 1 --> lo greater than hi, so no Hellos
i = 2, j = 2: k from 2 to 2 --> 1 Hello
i = 2, j = 3: k from 2 to 3 --> 2 Hellos
.
.
.
i = 2, j = 10: k from 2 to 10 --> 9 Hellos
So for i = 2, sum the numbers from 1 to 9 (triangular formula again): (9)(9 + 1)/2 = 45 Hellos

Now try for i = 3:
(Can you see the pattern emerging, by looking at the results of i = 1 and i = 2? This time, you should end up summing the numbers 1 to 8 for the number of Hellos.)

Etc.
At the end, sum up your sums to get the total number of Hellos.
There are no AI answers yet. The ability to request AI answers is coming soon!

Related Questions