Search code examples
c++mathwhile-looprangecout

Print numbers in range of two user-input values with while loop


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!


Solution

  • Here is a simple rewrite where you use min and max to determine the range you want to iterate on:

    #include <iostream>
    
    int main()  
    {  
        int v1 = 0, v2 = 0;  
        std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;  
        std::cin >> v1 >> v2;  
        int current =  std::min(v1, v2);
        int max = std::max(v1, v2);
        while (current <= max)  
        {  
            std::cout << current << std::endl;  
            ++ current;  
        }  
        return 0;  
    }
    

    This also allows you to keep the two inputs "intact", because you're using another variable to iterate on the values.

    Also note that the ++current could be done on the exact same line it is printed if it was replaced by current++. The later would return the current value of current and THEN increment it.

    Edit

    Here's what Michael suggested I believe, in working code:

    #include <iostream>
    
    int main()  
    {  
        int v1 = 0, v2 = 0;  
        std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;  
        std::cin >> v1 >> v2;  
        int increment = (v2 - v1) / std::abs(v2 - v1);
        int current = v1;
        int max = v2 + increment;
        while (current != max)  
        {  
            std::cout << current << std::endl;  
            current += increment;  
        }  
        return 0;  
    }