TakamuraM
TakamuraM

Reputation: 3

Program that sums things to an array

This book requires me to answer '' What output do you expect from the following program?''

After reading it many times I dont seem to fully understand its inner workings.

From what I get:

  1. First For loop stablishes that this process is going to repeat for 10 times. Variable j is assigned to start at 0.
  2. Second for loop starts the variable i at 0 and stablishes the condition i < j and does the operations written after it.

What is going on exactly? j starts at 0 and so does i, therefore numbers[j] += numbers[i] equals 2?

What happens after this operation is completed?

If i and j equal to 0 then why is this condition i < j True?

int main (void)
{
    int numbers[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int i, j;

    for ( j = 0; j < 10; ++j )
        for ( i = 0; i < j; ++i )
            numbers[j] += numbers[i];

    for ( j = 0; j < 10; ++j )
        printf ("%i ", numbers[j]);

    printf ("\n");
    return 0;
}

Upvotes: 0

Views: 50

Answers (1)

Paul92
Paul92

Reputation: 9062

The first thing you have to notice is that you have the outer loop, which runs from 0 to 10 and you to something to numbers[j]. This indicates that you take each element and modify it somehow. In order to find how, by inspecting the second loop and the right hand side of the assignment, you can notice that it adds to numbers[j] all elements with indices smaller than j. Now let's see what happens in a few steps:

j = 0 : 1 0 0 0 0 0 0 0 0 0
j = 1 : 1 1 0 0 0 0 0 0 0 0
j = 2 : 1 1 2 0 0 0 0 0 0 0
j = 3 : 1 1 2 4 0 0 0 0 0 0
j = 4 : 1 1 2 4 8 0 0 0 0 0

At the end, you will get an array with the property that each element a[j] is equal to a[0] + a[1] + ... + a[j] and a[0] = 1.

Now, taking a closer look at the beginning of the process, you have j = 0 and i = 0. The second for loop runs for as long as i < j. Since this comparison is false, the loop is not executed and we go to the next iteration of the outer loop, with j = 1.

Upvotes: 6

Related Questions