Ok so I am trying to write a program that will take a integer input like 8 and output "you ran the loops eight times 8=+7+6+5+4+3+2+1=35"
so far I have
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main(int argc, char *argv[])
{
int n, result , value;
cout << "Please enter a positive number\n";
cin >> value;
for ( n = 1; n <= value; n++ )
{
result = value + (n - 1);
}
cout << "You ran the loop " << value << " times\n";
cout << result << "\n";
system("PAUSE");
return EXIT_SUCCESS;
}
If I input 8 I get I get 15, I need to figure out how to get it to output the numbers and not only add n-1. Any help is greatly appreciated.
At every iteration, you're overwriting the "result" variable with "8+(n-1)". Value never changes and n increases until 8, so at the last iteration, it simply does "result = 8 + 7".
To have a total sum, replace "result = ..." by "result += ...". Do mind that you'll have to initialize result by setting it to 0, and that 'value' no longer has to be added.
The easiest way is to output during the for loop. Alternatively, if you want all numbers printed afterwards, you'll have to save them first. The best way to do this is by saving them in an array (http://www.cplusplus.com/doc/tutorial/arrays/) or vector (http://www.cplusplus.com/reference/stl/vector/) and then access them again at the end. You'll need a second loop to access the elements though.