For Loop, confused

The request is "Write a C++ program that allows a user to enter a start value and end value (where the start value is smaller than the end value) and print all the numbers from start to end using a for loop. If the end value is smaller than or equal to the start value the user must re-enter the end value until the appropriate value is entered."

But I can't seem to understand how contrast the two values like for(num1;num2;num1 < num2) sort of? Really confused here
Last edited on
Do you know how to ask the user to enter two integer values? Write the code for that.

Do you know how to check two values to determine if the first value is smaller than the second? Or the second is larger than the first? Add that code to the above.

If the end value is smaller than or equal to the start value the user must re-enter the end value until the appropriate value is entered.

A while or do-while loop would be the flow control you want for this:
https://www.learncpp.com/cpp-tutorial/55-while-statements/
https://www.learncpp.com/cpp-tutorial/56-do-while-statements/

When the two numbers are correct entered according to the instructions "break" out of the data entry loop:
https://www.learncpp.com/cpp-tutorial/58-break-and-continue/

A refresher on the how a for loop works:
https://www.learncpp.com/cpp-tutorial/57-for-statements/

Can you now use the two values to give the required output?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    int start{}, end{};
    std::cout << "Enter a start value: \n";
    std::cin >> start;
    std::cout << "Enter an end value: \n";
    std::cin >> end;

    if(start > end)
    {
        std::cout << "Oh noes! Start value is bigger than end value!";
        return 0;
    }
     else for(;start <= end; ++start) std::cout << start << " ";
}
Topic archived. No new replies allowed.