Mojibar Homan
Mojibar Homan

Reputation: 73

can someone please explain this pseudocode for me?

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

Answers (4)

KAMLESH KUMAR
KAMLESH KUMAR

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

Saeed Entezari
Saeed Entezari

Reputation: 3755

This is what is called nested loops:

  • Assign with i = 1 and loop (in every iteration add 1 to i so it becomes 2,3,4,..n) and in every iteration do these steps:
    • Assign j = 1 and loop (in every iteration add 1 to j so it becomes 2,3,4,..i until it is equal to i) and in every iteration do these steps:
    • => print hello

Upvotes: 0

P0W
P0W

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

Parsa Mousavi
Parsa Mousavi

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

Related Questions