So my program is running just fine and doing what it should beside one little thing. That thing is when I run the formula on the for loop. What it does is when I put in 5 and select the for loop operation it gives me the right answer. But when the program asks if I want to try again and I do the 5 again in the for loop it adds those two together so it gives me 30. How do I go about clearing that variable? My formula case works just fine doesnt add or anything when I do it over.

#include <iostream>
using namespace std;

int num;
int total = 0;
char c;
int counter;

int main(){

        cout <<"\n---------------------------------------" << endl;
        cout <<"Enter a Number (Natural/Whole/Integer)" << endl;
        cout <<"---------------------------------------" << endl;
        cin >> num;

        cout << "\nHow would you like to calculate the sum?\n" << endl;
        cout << "1. For-Loop" << endl;
        cout << "2. Formula" << endl;

        cout << "\nSelect an operation: ";
        cin >> c;


        case '1':

            for (counter = 1; counter <= num; counter++){

                total += counter;

            cout <<"Your sum using For-Loop is: "<< total;

        case '2':

            total = num * (num + 1) / 2;
            cout <<"Your sum using formula is: " << total << endl;


        cout << "\nWould you like to try again? (y/n): ";
        cin >> c;


    while(c == 'y' || c == 'Y');

    return 0;
5 Years
Discussion Span
Last Post by Prysm[VA]

First off. I suggest adding a


at the end of the do-while loop. Otherwise it'll just clutter the screen if it's run multiple times.
The problem with you code is the brackets. You're missing a few brackets and others aren't correctly placed. If you can't figure it out feel free to PM me and I'll help you out
Have fun :D

Edited by Prysm[VA]: Added more information


The only thing you'll need to do here is to reset total to zero at the beginning of your loop. That action alone will fix your code.

You're missing a few brackets and others aren't correctly placed.

There are no missing brackets here, and the brackets aren't placed incorrectly at all. What he's using is an indentation style known as K&R styling, which is a fairly common way of writing C, C++, and even Java code.


Oh you're right about resetting total to 0. I totally missed that haha.
And I know about the different ways of indenting, it just looked to me like there are some missing. Plus when I ran it after adding what I thought needed to be fixed it worked fine. - besides it not resetting haha

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.