Understanding this code snippet

Looking for a bit of help stepping through this code and how the answer (22360) is achieved? Nothing like this to snap a beginner programming student back to reality.

I am able to get some of it but if someone can explain the steps I would be much appreciative. Thanks for the help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
  
  int main()
  {
  for(int j = 0; j < 5; ++j) //pre increment
    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;
}
@allendks45

The program does print out 22360, but it ISN'T 22360 in reality. It is actually three numbers, which are 2 23 and 60.

Run this and see..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
	int a[5], sum = 0,i; // Initialize variables
	for(int j = 0; j < 5; ++j) //pre increment
		a[j] = 2*j-3;
	i = 0;
	while(i < 4)
	{
		sum+=a[i];
		if(a[i] > 0)
			std::cout<< i << " " << 2*a[i]; // Added the space between the i variable and the a[] array
		i++;
	}
	std::cout<<sum << std::endl; // print third number, 60
	return 0;
}
Thanks....wish I truly understood what the code is doing but it still appears foreign. Rather than just find the answer I want to understand what is happening in the loops while the code is running. Having a difficult time comprehending how 22360 is displayed at compile. Hopefully someone will explain each pass of these loops
Okay allendks45

I added to the program to help you understand the results, and the program itself.

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

int main()
{
int a[5], sum = 0,i;
for(int j = 0; j < 5; ++j) //pre increment
{
	a[j] = 2*j-3;
	std::cout << "a[" << j << "] = " << a[j] << std::endl;
}

i = 0;
while(i < 4) // Should be <5 if you want ALL of array a[] used
	// Last value read is in a[3], which is a three
{
sum+=a[i]; // sum will equal sum plus value in a[i]
			// If it's a negative, value will be subtracted from sum
std::cout << "Sum equals " << sum << " and i = " << i << std::endl;
if(a[i] > 0)
	std::cout<< std::endl << "i = " << i << " and 2*a[" << i << "] equals " << 2*a[i] << std::endl;
i++;
}
std::cout << std::endl << "And the sum is equal to " << sum << std::endl;
return 0;
}
Topic archived. No new replies allowed.