×
Back to all chapters

# Loops

When you need to do a repetitive task, like working through all elements in a list to find a prime or searching a map until you've found all of the gold, loops are a go-to tool.

# For

What will be the output for the pseudocode shown below?

 1 2 3 4 for rows 1 to 7 for k 1 to rows Display "*" end line 

$$A)$$

 1 2 3 4 5 6 7  x xx xxx xxxx xxxxx xxxxxx xxxxxxx 

$$B)$$

 1 2 3 4 5 6 7 xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx 

$$C)$$

 1 2 3 4 5 6 7 x xx xxx xxxx xxxxx xxxxxx xxxxxxx 

$$D)$$

 1 2 3 4 5 6 7  x xxx xxxxx xxxxxxx xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxx 

Details and Assumption

-The for loop increments by $$1$$ unit.

-The range of the for loop includes the first and last numbers

What will be the output for the pseudocode shown below?

 1 2 3 4 5 6 7 8 9 for i (1 to 5) for j (5 to i+1) Display " " for k (i to 1) Display k for h (2 to i) if i > 1 Display h end line 

$$A)$$

 1 2 3 4 5 1 12 123 1234 12345 

$$B)$$

 1 2 3 4 5  1 212 32123 4321234 543212345 

$$C)$$

 1 2 3 4 5  1 222 33333 4444444 555555555 

$$D)$$

 1 2 3 4 5  1 121 13231 1432341 154323451 

Details and Assumption

-The for loop increments by $$1$$ unit.

-The range of the for loop includes the first and last numbers.

What will be the output for the pseudocode shown below?

 1 2 3 4 5 6 7 for height 1 to 5 for width 1 to 11 if height % 2 == 0 and width % 2==0 Display "0" else Display "x" end line 

$$A)$$

 1 2 3 4 5 xxxxxxxxxxx x0x0x0x0x0x xxxxxxxxxxx x0x0x0x0x0x xxxxxxxxxxx 

$$B)$$

 1 2 3 4 5 xxxxxxxxxxx 00000000000 xxxxxxxxxxx 00000000000 xxxxxxxxxxx 

$$C)$$

 1 2 3 4 5 x0x0x0x0x0x x0x0x0x0x0x x0x0x0x0x0x x0x0x0x0x0x x0x0x0x0x0x 

$$D)$$

 1 2 3 4 5 00000000000 xxxxxxxxxxx 00000000000 xxxxxxxxxxx 00000000000 

Details and Assumption

-The for loop increments by $$1$$ unit.

-The range of the for loop includes the first and last numbers

×