Don't understand the output

I am having trouble understanding why the output is the way it is on this program. This is an example for probably a similar question on my final and I figure if I can't understand this I'm in trouble.

The answer output is 22360.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>

int main()
{
  int a[5];
  int sum=0;

  for(int j = 0; j < 5; ++j)
    a[j] = 2 * j - 3;

  int i = 0;
  while(i < 4)
  {
    sum += a[i];
    if(a[i] > 0)
      cout << i << 2 * a[i];
    i++;
  }

  cout << sum;

  return 0;
}


I don't have much trouble with the for loop but rather the while loop.
for loop:
j = 0
a[0] = 2 * 0 - 3
a[0] = -3

j = 1
a[1] = 2 * 1 - 3
a[1] = -1

j = 2
a[2] = 2 * 2 - 3
a[2] = 1

j = 3
a[3] = 2 * 3 - 3
a[3] = 3

j = 4
a[4] = 2 * 4 - 3
a[4] = 5

a = {-3, -1, 1, 3, 5}

while loop:

sum = 0
i = 0

sum = sum + a[0]
sum = 0 + (-3)
sum = -3

is -3 more than 0?
No, don't print anything.

i = i + 1
i = 0 + 1
i = 1

sum = sum + a[1]
sum = -3 + (-1)
sum = -4

is -1 more than 0?
No, don't print anything.

i = i + 1
i = 1 + 1
i = 2

sum = sum + a[2]
sum = -4 + 1
sum = -3

is 1 more than 0?
Yes
Print i (2)
Print 2 * a[2] (2)


i = i + 1
i = 2 + 1
i = 3

sum = sum + a[3]
sum = -3 + 3
sum = 0

is 3 more than 0?
Yes
Print i (3)
Print 2 * a[3] (6)


i = i + 1
i = 3 + 1
i = 4

while loop end

print sum (0)

Things that we're printed: 2, 2, 3, 6, 0
Last edited on
Thank you very much that helps immensely! It's a lot easier to visualize now.
Topic archived. No new replies allowed.