Sportsman319
Sportsman319

Reputation: 13

Nested for loops but with a twist

So recently I am having trouble understanding nested for loops. For example, one question asks: The following nested loop structure will execute the inner most statement (x++) how many times?

for (int j = 0; j < 100; j++)
{
    for (int k = 100; k > 0; k--)
    {
        x++;
    }
}

Can you keep it in simple terms, as I am fairly new to programming? Thanks!

Upvotes: 0

Views: 272

Answers (4)

Avinash
Avinash

Reputation: 2191

for(int j = 0; j < 100; j++)     //j -> 0~99 =>total=100
{
    for(int k = 100; k > 0; k--) //k -> 100~1 =>total=1oo
    {
       x++;
    }
}

System.out.println(x);           //should print 10000 bcz of 100*100

Upvotes: 0

Lakshmikant Deshpande
Lakshmikant Deshpande

Reputation: 844

You just have to understand how many times each loop executes.

Note that first loop runs 100 times. So, everything inside it will repeat 100 times. The inner loop also runs 100 times. So x++ will execute 100 * 100 = 10000 times.

for (int j = 0; j < 100; j++)      // 100 times
{
    for (int k = 100; k > 0; k--)  // 100 * 100 times
    {
        x++;                       // 100 * 100 times
    }
}

System.out.println("x = " + x);    // This should print 10000 (assuming that x is zero initially)

Upvotes: 0

Ozair Kafray
Ozair Kafray

Reputation: 13549

For each j, the k loop executes a 100 times hence incrementing x by 100. See illustration below:

for j=0; k=100, k=99, k=98 .... k=2, k=1; x is now 100

for j=1; k=100, k=99, k=98 .... k=2, k=1; x is now 200

.............................................

.............................................

for j=98; k=100, k=99, k=98 .... k=2, k=1; x is now 9900

for j=99; k=100, k=99, k=98 .... k=2, k=1; x is now 10000

The result would have been the same, had the code been modified as:

for(int j = 0; j < 100; j++) {
    for(int k = 0; k < 100; k++) // NOTE: reversal of k here.
    {
        x++;
    } 
}

The inner k loop is just being executed in reverse order (from 100 to 0) just to confuse the newbies.

Upvotes: 1

Zel
Zel

Reputation: 98

For every inner loop, the for loop will execute x++ 100 times. You will also run the inner for loop 100 times. So in total you will run x++ 100 x 100 = 10000 times.

Upvotes: 1

Related Questions