Need program to repeat, and end if 0 is entered

Here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    
// compute the sum of even numbers between 1 and n

    #include <iostream>
    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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.