I feel like I might be missing something here, but something is telling me that I might just be making this more difficult that it has to be, but from the book, "C++ Primer, 5th ed.," I'm stuck on this problem:
Exercise 1.11: Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
Up until this time in the book, the only loop being used is the while
loop, and no conditional expressions, like if
, have been introduced. The problem would be simple if it were not for the fact that a user could put the values into the integers asked for in ascending or descending order, so simple subtraction WOULD find the difference, but without testing which way to increment.
How could I absolutely print the range between the numbers, guaranteeing not to just increment towards infinity without testing the outcome of such math and/or without comparing the two numbers? This is what I have; it works when the first value: v1
is less than or equal to the second: v2
, but not otherwise:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): "
<< endl;
std::cin >> v1 >> v2;
while (v1 <= v2)
{
std::cout << v1;
++ v1;
}
return 0;
}
Any help would be greatly appreciated!
cin>>v1>>v2;
std::min
to find the lower one and count that many numbers up.0.5
will likely ruin the whole thing.>>
or integer division.