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;
}
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
#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;
}