Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior when finding range of values between two numbers

Tags:

c++

I've recently started working through the "c++ primer 5th Edition". I'm currently on the following exercise:

Exercise 1.11: Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.

I have written the following code as a solution :

#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 input the numbers, the output is not quite correct;

Sample input:

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

Sample output:

1
2
3
4
5
5
6    

What I don't understand, is that if the first number i input is larger than the first (e.g. num1 > num2), then the program produces the desired result, eg:

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


1
2
3
4
5

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

Just to be clear, I'm aware of a cleaner, correct solution to this exercise. I would just like to know the reason that my program functions this way.

I'd very much appreciate an explanation!

like image 773
b_dobres Avatar asked Feb 09 '23 18:02

b_dobres


1 Answers

Its so simple. Just add 'else' for the bottom two if loops Basically you need to go through only 1 'if' loop, but your program goes through each 'if' loop

like image 154
Technoid Avatar answered Feb 13 '23 02:02

Technoid