Determine the sum of the even numbers between 1 and n. n is specified by the user. Allow the user to repeat the process terminate if the user enters zero (0)
Example:
If the user enters 16, compute the sum of 2 + 4 + 6 + …16
If the user enters 21, compute the sum of 2 + 4 + 6 + …18 + 20
if the user enters 0 stop
#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)
{
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);
while (toupper(again) == 'Y')
{
;
}
system("pause");
return 0;
}
This is as far as I have gotten. I have tried several things to make it work and can't seem to get it figured out.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int n = 0;
int j = 0;
int sum = 0;
char again = 'Y';
sum = 0;
j = 2;
// Loop 1: if again is y or Y then you want you go through this loop (remember or is designated ||)
{ // opening bracket of first loop
cout << "Enter a number: " ;
cin >> n;
sum=0;
//Loop 2: Calculate sum of the even's. Start with j at 2 and increment it by 2 until it equals or is less than the number chosen by the user
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; //if they put in y or Y for this statement then the original loop will repeat
}//closing bracket of first loop
return 0;
}
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int n = 0;
int j = 0;
int sum = 0;
char again = 'Y';
sum = 0;
j = 2;
while (again=='y' || again=='Y')
{
cout << "Enter a number: " ;
cin >> n;
sum=0;
for(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;
}
return 0;
}