Rami Raghfan
Rami Raghfan

Reputation: 163

Why does variable value reach 5050 after increment through two loops? (loop till 100)

I'm reading a beginners book on C programming and it has some exercises. This is one of them, the question asked what would be the result of the following loop...

int main()
{
    int result = 0;

    for (int i = 1; i <= 100; i++)
    {
        for (int j = 1; j <= i; j++)
        {        
            result++;
        }
    }      

    printf("%d", result);

    return 0;
}

my 'rational' answer would have been 1000, but why is the correct answer 5050?

Upvotes: 2

Views: 80

Answers (2)

wizzwizz4
wizzwizz4

Reputation: 6426

The first time, the inner loop will run once because i is 1, adding 1 to result. The second time, it will run twice because i is 2, adding 2 to result The third time, the inner loop will run thrice because i is 3, adding 3 to result. And so on, until 100.

Ultimately, this adds 1 + 2 + 3 + 4 + … + 97 + 98 + 99 + 100 to result. This value is 5050: the 100th triangle number.

If your compiler is smart (e.g. gcc -O2), it'll pick up on the fact that the innermost loop is simply an increment, and compile:

for (int i = 1; i <= 100; i++)
{
    for (int j = 1; j <= i; j++)
    {        
        result++;
    }
}

to:

for (int i = 1; i <= 100; i++)
{
    result += j;
}

If your compiler's really smart (e.g. clang -O2), it'll compile it to a simple result = 5050;, but such optimisations can end up being really slow to compile (it has to run the code beforehand to calculate what the value is meant to be, unless it special-cases specific examples which makes the compiler take up more space).

Upvotes: 4

Hogstrom
Hogstrom

Reputation: 3761

@wizzwiss34's answer is correct ... adding a little more context. In maths this is referred to as a finite series and what you are doing is implementing this mathematical function using C.

A finite series is a summation of a finite number of terms. An infinite series has an infinite number of terms and an upper limit of infinity. This tutorial will deal with finite series. Infinite series will be covered in the calculus tutorials.

In this case the sequence is 100+99+98+97...+1 = 5050

For the total number of i's you add i-1 each time.

Upvotes: 0

Related Questions