C++ newbie here. Anything wrong or complicated with this code? The main question I have is whether I can use v1 and v2 inside while (val <= v2)?
int main ()
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
int sum = 0, val = v1;
while (val <= v2)
sum += val;
std::cout << "The sum of " << v1 << " through " << v2 << " inclusive is " << sum << std::endl;
Yes, you can, they're local variables in
main() so they're in scope until
main() returns (i. e. the whole lifetime of the program).
Of course you can. The statement inside the
while-loop needs to evaluate to a boolean expression, i.e.
false. And as you can state that either it is true that
val <= v2 or not, this is perfectly fine.