Home > database >  Getting incorrect sum while using a recursive function and a do-while loop
Getting incorrect sum while using a recursive function and a do-while loop

Time:11-30

I just finished coding a small function for a school project and got the right answer. However, after adding a do-while loop (as it is required), I started running into issues. The first loop works just fine and I get the right answer (i.e., if I input 20 into the function, it outputs 210 which is correct), but if I input that same number or a different one, the number adds ON to the previous total (so if I added 1, then the "total" for that would be 211). I want each loop to find the total, output that total, and then when a new loop occurs, starts fresh. How do I fix this?

#include <iostream>
using namespace std;

int n, total = 0; /* Global variables since I only have to declare it once rather than two times! */

int sum(int n);
// Recursive version to calculate the sum of
// 1   2   ....   n


int main()
{
    char choice;
    do {
        cout << "Enter a positive integer:";
        cin >> n;
        sum(n);
        cout << "The sum of 1 ... " << n << " is: " << total << endl;
        cout << "Would you like to try another entry (Y/N): ";
        cin >> choice;
    }while(choice == 'Y' || choice == 'y');
    cout << "Goodbye!" << endl;
    return 0;
}


int sum(int n){
    if(n == 0) 
    {
      return total;
    }
    else
    {
      total = total   n;
      return sum(n-1);
    }
}

CodePudding user response:

You could try the following code for sum:

int sum(int n) {
    if (n == 1) {
        return 1;
    } else {
        return n   sum(n - 1);
    }
}
  • Related