0

how and what statement is compiled by compiler. want to check step by step so that i can understand the logic of a program
for example in nested for loop when and how many time inner loop will execute and when outer loop execute. hope understand my question

2
Contributors
1
Reply
15
Views
3 Years
Discussion Span
Last Post by NathanOliver
1

All of your code is compiled by the compiler. As far as you loop question is concerned look at this:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 5; j++)
    {
        std::cout << j * i << std::endl
    }
}

The above cout statement will execute 50 times. The inner loop executes 5 times for every loop of the outer loop. Since the outer loop runs 10 times that gives you 10 * 5 = 50. So when calculating how many times the code in the inner loop will run you take the number of times the outer loop runs and multiply it ny the number of times the inner loop runs. This holds true when adding any number of nested loops. If you have this:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 5; j++)
    {
        for (int k = 0; k < 20; k++)
        {
            for (int l = 0; l < 15; l++)
            {
                std::cout << "inner most loop executed" << std::endl
            }
        }
    }
}

The cout statement will run 15,000 times. You multiply all of the numbers of times each loop runs and you get 10 * 5 * 20 * 15 = 15,000

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.