Strange behavior when looking for a range of values ​​between two numbers

I recently started working through the "C ++ primer 5th Edition". I am currently performing the following exercise:

Exercise 1.11: Write a program that asks the user for two integers. Print each number in the range indicated by these two integers.

As a solution, I wrote the following code:

#include <iostream>

int main(){
    int num1 = 0, num2 = 0;
    std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
    std::cin >> num1 >> num2; 


    if (num1 < num2)
        while (num1 <= num2){
            std::cout << std::endl << num1;
            ++num1;
        }

    if (num2 < num1)
        while (num2 <= num1){
            std::cout << std::endl << num2;
            ++num2;
        }

    if (num1 == num2)
        std::cout << std::endl << num1;

    std::cout << std::endl;

However, when I enter the numbers, the output is not entirely correct;

Input Example:

Please enter two numbers to find a range betweem
>> 1 5

Output Example:

1
2
3
4
5
5
6    

I do not understand that if the first input of the number I am larger than the first (for example, num1> num2), then the program produces the desired result, for example:

Please enter two numbers to find a range between
>> 5 1


1
2
3
4
5

What is particularly confusing is that when I replace the order of conditional statements, the first example will work correctly, and the second will produce the wrong output.

, , . , .

!

+4
3

. "else" , "1", "if"

+5

num1 , while if condition, true, if ( num1 <= num2), , , 5 6.

if , if, , ,

+1

As Technoid said, add more instructions. Your code should now look like this:

#include <iostream>

int main(){
    int num1 = 0, num2 = 0;
    std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
    std::cin >> num1 >> num2; 


    if (num1 < num2)
        while (num1 <= num2){
            std::cout << std::endl << num1;
            ++num1;
        }

    else if (num2 < num1)
        while (num2 <= num1){
            std::cout << std::endl << num2;
            ++num2;
        }

    else if (num1 == num2)
        std::cout << std::endl << num1;

    /* Alternatively for (num1 ==num2) use:

    else
        std::cout << std::endl << num1;     

    */

    std::cout << std::endl;
}
+1
source

All Articles