Reputation: 73
for i = 1 to n do
for j = 1 to i do
print “hello world”
end for
end for
I don't understand what to
and do
mean and what exactly this code does. The question was, how often is "hello world" printed out when n = 4
. Is the answer 10? How do I work this out?
Upvotes: 0
Views: 370
Reputation: 130
Outer Loop:
for i = 1 to n do
(initially i
will be assigned to 1)
this loop is saying that something has to be done n times (meaning of to). What has to be done is written in your inner loop (meaning of do).
for j = 1 to i do
print “hello world”
For each value of i, the inner loop will be executed i
times (this is because each time when i
changes, your inner loop will be executed i
times (for j = 1 to i do)
). Here, it will print hello world
each time.
Hope it helps you
Upvotes: 1
Reputation: 3755
This is what is called nested loops:
Upvotes: 0
Reputation: 47784
Lets break down for innermost loop j = 1 to i
i = 1
you will see only one hello world
i =2
2 hello world
i = 3
3 hello world
i =4
4 hello world
So total 1 + 2 + 3 + 4 = 10
hello worlds
For n = 10
1 + 2 + 3 .... = 10 = 55 hello worlds
for n = k
Sum of Arithmetic Progression: k * (k + 1 ) /2 hello worlds printed
Upvotes: 3
Reputation: 1182
This means that at the first iteration of the outer loop,the inner loop gets executed one time , then at the second iteration two times and so forth.So 1+2+3+4 = 10
Upvotes: 0