Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

How many different loops can be nested inside one another?

+10 votes
I can't imagine the answer would be infinite. For example, one of the Practice-It exercises (2.14) requires 3 different loops. In what scenario would a fourth one be necessary?
asked Sep 7, 2016 in CSC 211 (F16) by Jordan Peklo (100 points)

2 Answers

+2 votes
You can definitely include any number of loops inside a loop you want. For 4 nested loops, I would say that there are not much scenarios that you need to apply that, because:

Ideally, you shouldn't have to much nested loops inside nested loops, because it would take a very long time for your program to run.

For example, your program will be fast if you have only 2 loops, like:
for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        <inner statements>
    }
}
Because the computer only have to run the inner statement for 3 * 3 = 9 times.

But what if you do this:
for (int i = 1; i <= 10; i++)
{
    for (int j = 1; j <= 10; j++)
    {
        for (int k = 1; k <= 10; k++)
        {
            <inner statements>
        }
    }
}
the computer has to run the statements 10 * 10 * 10 = 1000 times. So later on when you have a bunch of code to deal with, try to solve the problem with other approaches rather than using nested loops, and it is usually easier to come up with other approaches than to use the for loops four times in a row.

Have fun!
answered Sep 7, 2016 by Minh Ta (1,045 points)
+1 vote
I am just guessing here, but I think unlimited.
answered Sep 7, 2016 by Trenton Jackson (100 points)
...