C++ Loop - Need variable to accumulate sum
Posted
by
user1780064
on Stack Overflow
See other posts from Stack Overflow
or by user1780064
Published on 2012-10-28T22:49:04Z
Indexed on
2012/10/28
23:01 UTC
Read the original article
Hit count: 194
I'm writing a program to ask the user to enter a value between 5 and 21 (inclusive). If the number entered is not in this range, it prints, "Please try again". If the number is within the range, I need to take that number, and print the sum of all the numbers from 1 to the value entered. So if the user entered "7", the sum would be "28". I successfully wrote the first loop, in the case of the number not being within the range, but cannot figure out how to run the second loop- whether to use a while, do-while, or for loop. Please advise.
#include <iostream>
int main () {
int uservalue;
int count;
int sum;
//Prompt user for input
do {
cout << "Enter a value from 5 to 21: ";
cin >> uservalue;
if (uservalue < 5 || uservalue > 21)
cout << "Value out of range. Try again..." << endl;
} while (uservalue < 5 || uservalue > 21);
cout << endl;
//Loop to accumulate sum
for (count = 1, count < uservalue, count++;) {
sum = uservalue + count;
if (uservalue <= 5 || uservalue <= 21)
cout << the sum is " << sum << endl;
}
return 0;
}
© Stack Overflow or respective owner