Nested For-loop confusing, how does program proceed?

In summary: I don't really understand what you're asking. Can you please clarify?In summary, the triple nested loop with a simple thought exercise is confusing. I was having trouble following the logic of the C-loop.
  • #1
late347
301
15
I was thinking about triple nested for loop with a simple thought exercise on my own. I was little bit confused about that third nested loop (print c loop)

With simple case of double nested loop, I think I understood how the program works. (only one nesting).
But I'm having some trouble imagining exactly what letters and how many of them will be printed in this exercise. I'm having trouble with following the logic of the triple nested loop.

In simple nested loop, with only two loops:

  1. the first loop takes one step. Then the program proceeds to the second loop and fulfilles the entire second loop.
  2. And then it returns to the second step, of the first loop, then it proceeds to fulfill the entire second loop.
  3. And then the program returns to the third step of the first loop, then the program proceeds to fulfill the entire second loop.
But it becomes little bit confusing for the third loop which is the C-loop.
Python:
for a in range(3):
    print("a",end="")
    for b in range(3):
        print("b",end="")
        for c in range(3):
            print("c",end="")
 
Technology news on Phys.org
  • #2
Print a, b and c in the innermost loop where youre printing just c now and it should make more sense

Youll see something like counting In base 3.
 
  • #3
I edited the code little bit and removed the end="", and I added "abc" into the c loop printout

Python:
for a in range(3):
    print("a")
    for b in range(3):
        print("b")
        for c in range(3):
            print("abc")

my understanding is that the program proceeds as follows:
  • 0-eth iteration of a loop, -->0eth iteration of b loop, 0eth,1st,2nd iterations of "abc" are printed (fair enough)
  • for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?)
  • why doesn't the program revert back into the 1st iteration of a loop instead?

here is the actual printout from the program also for your benefit
Python:
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
 
  • #4
You want to print the value of a, b and c. Not the strings "a", "b", "abc"
 
  • #5
It might help to make things clear if you use different ranges for the three loops, e.g. 3, 4, 5 instead of 3, 3, 3.
 
  • Like
Likes jedishrfu
  • #6
BvU said:
You want to print the value of a, b and c. Not the strings "a", "b", "abc"
Why would I want to print the values instead of the strings
 
  • #7
late347 said:
for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?

The b loop is within the a loop. Why are you expecting the program to go to the next iteration of the a loop before the enclosed b loop has been completed?
 
  • #8
The c-loop is acting within each b-loop step exactly the way the b-loop is acting within each a-loop step. The Python mandatory indentation is very helpful in keeping nested loops straight. You can see that in your printout. It might help to indent the prints the same way you have indented the code.
 
  • #9
late347 said:
Why would I want to print the values instead of the strings
Because then you can see directly how the variables controlling the looping are changing. It's not obligatory, but I agree with @BvU that it's a good way to see what's going on here.
 
  • Like
Likes jedishrfu
  • #10
It might help you understand better if you used different variables for your loop control variables. Here is a modification of your code from post #1. (
Python:
for i in range(3):
    print("a",end="")
    for j in range(3):
        print("b",end="")
        for k in range(3):
            print("c",end="")
Having loop control variables named a, b, and c, and loops that print "a", "b", and "c" makes it harder to understand, IMO. Now i, j, and k each take on the values 0, 1, and 2.

The outer loop runs 3 times. Each iteration of the outer loop causes the middle loop to run three times. Each iteration of the middle loop causes the innermost loop to run three time. So when the program is finished, the outer loop will have run three times; the middle loop will have run nine times; the innermost loop will have run twenty-seven times.
 
  • #11
you can also try to make a tree with that? it can help you imagine what goes on... it would look like this
Screenshot from 2016-08-27 18-09-56.png
 
  • #12
late347 said:
for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?)

I guess the easiest way to understand this is by having in your mind that once the program sees a "for" it goes all about finishing whatever is within it before returning and going to the next step of iteration or leaving out... you go into a-loop - you have to iterate and finish everything within... when you enter you see the b-loop - again you have to iterate and finish everything within... when you enter you see the c-loop - you finish everything and iterate over it... c-loop finishes iterations and goes out, b loop can continue iterating...and so on and so on.
For that reason you don't return to the 1st for, but to the 2nd... (because the 2nd is met within the 1st and it is not over yet)... that's why sketching it as a tree can help you (move up only once you finished everything in a line, starting from the top left to finish on the bottom right as I sketched it)

For loops help you save effort for writing hundrends of repeative unnecessary lines...
in particular you could have done exactly the same thing by writing the following code:
Python:
for i in range(3):
    print("a")
    for j in range(3):
        print("b")
        print("c")
        print("c")
        print("c")
in expense of extra lines of code...and well three chars are easy to handle by typing, but for example if the ranges were going up to 100 I don't think it'd be clever to write 100 lines of code just for that (or just say print("bcccc...ccc") with 100 c's)
 
Last edited:
  • #13
I will look into this matter maybe tomorrow. I feel down now because we had a tough exam today.

I ran out of time because I didnt manage time optimally in that exam.

I did too many math and physics prob even though I had some homework credit in the bag which helps the grade in math and physics. Where as in the exam compartments about programming&databases and the second compartment webdesign&text editing I didnt have homework credit opportunity.

I suppose it would not matter if:

You never make mistakes in math, therefore no need for double checking. (I usually double check my work...if possible and if it seems sensible to the situation)

You always calculate physics and math super fast. (Sometimes yes sometimes no...)
Especially in physics it probably helps to identify easy probs and finish them first.
 
Last edited by a moderator:

What is a nested for-loop?

A nested for-loop is a type of loop structure in programming that allows for the execution of a loop inside another loop. This means that the inner loop will be executed for each iteration of the outer loop.

How does a nested for-loop work?

A nested for-loop works by first executing the outer loop, which then triggers the inner loop to execute. Each time the inner loop completes, the outer loop moves on to the next iteration, triggering the inner loop again.

How do I write a nested for-loop?

To write a nested for-loop, you will need to include one for-loop inside another for-loop. The syntax typically involves two sets of parentheses, with the inner loop inside the outer loop. It is important to make sure that the loop conditions and the loop control variables are properly set to avoid an infinite loop.

Why is a nested for-loop useful?

A nested for-loop is useful when you need to iterate through multiple levels of data or when you need to perform a task that requires multiple iterations. It can also be helpful in situations where you need to perform a task on a two-dimensional array or matrix.

How do I avoid confusion with nested for-loops?

To avoid confusion with nested for-loops, it is important to carefully plan and structure your code. Make sure to use descriptive variable names and to indent your code properly to clearly show the loop structures. It can also be helpful to use comments to explain the purpose of each loop.

Similar threads

  • Programming and Computer Science
Replies
3
Views
720
  • Programming and Computer Science
Replies
16
Views
1K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
2
Replies
66
Views
4K
  • Programming and Computer Science
Replies
1
Views
945
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
19
Views
979
  • Programming and Computer Science
Replies
6
Views
2K
Back
Top