My program should perform a calculation to get the sum of every number in the range specified with startVal and endVal. I've looked at other somewhat similar questions, but I haven't pulled much from them. Can somebody please tell me what I'm doing wrong in the for loop, so I can fix it?
#include <iostream>
using namespace std;
main() {
//Declare variables
int startVal;
int endVal;
int newVal;
int sum;
cout << "Enter starting value for loop (1 - 500): ";
cin >> startVal;
while (startVal<=1 || startVal>=500) {
cout << "Invalid starting value.\n";
}
while(startVal>=1 && startVal<=500) {
cout << "Enter ending value for loop (" << startVal+1 << " - 1000): ";
cin >> endVal;
if(endVal<startVal+1 || endVal>1000) {
cout << "Invalid ending value.\n";
}
}
for(startVal=newVal; newVal==endVal; ++newVal) {
sum = newVal+1;
}
cout << "The sum of the integers from " << startVal << " through " << endVal << " is " << sum << endl;
return 0;
}
Try changing for
loop to this (as noted by comments):
sum = 0;
for( newVal=startVal; newVal<=endVal; ++newVal ) {
sum += newVal;
}
As for the second while()
loop add some break
condition. E.g.:
if( (endVal<startVal+1) || (endVal>1000) ) {
cout << "Invalid ending value.\n";
}else{
break;
}