-1

I'm having trouble on how to calculate the sum while outputting the total end result as 1+2+3+4+5=sum. How can I output both correctly using for loops?

main()
{

    int num, i, sum;


    cout<<"Input a number -> ";
    cin>>num;


    for(i=1;i<=num;i++)
    {
        cout<<i<<" + ";

    }

}
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
Thrylin
  • 1
  • 2
  • What would you do with paper and pen to sum a set of numbers? My second hint is you need to set `sum` to zero at some point. And finally the variable `i` need not be declared at the top. You only need it in the for loop. – drescherjm Oct 07 '19 at 02:18
  • You need to start with `sum` value of 0 and add each value of `i` to `sum`. Does that sound logical? – lurker Oct 07 '19 at 02:21

1 Answers1

0
int main()
{
    int num, i, sum = 0;


    cout<<"Input a number -> ";
    cin>>num;


    for(i=1;i<=num;i++)
    {
        cout << i << ((i == num) ? " = " : " + ");
        sum +=i;
    }
    cout<<sum;
    return 0;
}

You can run it here: https://www.onlinegdb.com/online_c++_compiler

CedricYao
  • 167
  • 1
  • 12
  • 1
    You also forgot to set sum to 0. local variables in a function are not initialized to 0. – drescherjm Oct 07 '19 at 02:26
  • Did you know that in c++ when initializing an int, its value-initialized is 0? https://stackoverflow.com/questions/3803153/what-are-primitive-types-default-initialized-to-in-c – CedricYao Oct 07 '19 at 02:28
  • 1
    I think it would be a little clearer to write: `cout << i << ((i == num) ? " = " : " + ")` – lurker Oct 07 '19 at 02:29
  • 1
    Your link is about a different thing. This was class member which was initialized in the constructor. – drescherjm Oct 07 '19 at 02:31