Getting wrong output for my program in C++

  • You are throwing away what is calculated by previous iterations.
  • You are not returning what is calculated.

To fix, get the declaration and initialization of i out of the loop and return the result.

#include <iostream>
using namespace std;

int num(int n){
    int sum=0;
    for(int i= 1 ; i<=n ; i++){

        sum += i;
        cout<<sum;

    }
    return sum;
}

Leave a Comment