Need program to repeat, and end if 0 is entered

Here is my code.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` `````` // compute the sum of even numbers between 1 and n #include using namespace std; int main() { int n = 0; int j = 0; int sum = 0; char again = ' '; sum = 0; j = 2; cout << "Enter a number: " ; cin >> n; while (j <= n && n != 0) { if (j%2==0) { sum = sum + j; j = j+2; } } cout << "the sum of even numbers from 1 to " << n << " is " << sum << endl; cout << "Do you want to do this again (Y/N)?"; cin >> again; again = toupper(again); if (again == 'Y') { cout << "Enter a number: " ; cin >> n; while (j <= n && n != 0) { if (j%2==0) { sum = sum + j; j = j+2; } } } cout << "the sum of even numbers from 1 to " << n << " is " << sum << endl; system("pause"); return 0; }``````

I need my program to repeat, and also need it to end if 0 is entered. I am unable to get it to continue repeating. And I don't know what I am doing wrong with this for it to continue even after 0 is entered.
Use a outer do loop. You also have the same code repeated twice which you don't need. I simplified your for loop also.

 ``1234567891011121314151617181920`` ``````int n = 0; int sum = 0; char again = ' '; do { sum = 0; cout << "Enter a number: " ; cin >> n; for( int j=2; j <= n; j += 2 ) sum += j; cout << "the sum of even numbers from 1 to " << n << " is " << sum << endl; cout << "Do you want to do this again (Y/N)?"; cin >> again; again = toupper(again); } while (again == 'Y');``````
Topic archived. No new replies allowed.