// compute the sum of even numbers between 1 and n
#include <iostream>
usingnamespace 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.
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');