For loops

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

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 <cstdlib>
#include <iostream>

using namespace 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.
Ok thank you very much. I got it to work correctly with your help. Do you mind helping me with the output. How do I get it to display all the numbers?
Depends on where/when you want the output.

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.
Topic archived. No new replies allowed.