I have been writing a program which asks you to input two integers, which then lists all integers from the smaller of the two integers entered to the larger of the two integers entered (inclusive). I want the program to put a period after the last integer in the output, and I have found ways to do this without using a for loop, but I want to understand why this code doesn’t work (it just outputs the larger integer with a period after it).
#include <iostream>
int main()
{
std::cout << "Enter two integers, pressing <ENTER> after each integer." << std::endl;
int num1, num2, lower, upper;
std::cin >> num1 >> num2;
if (num1 > num2)
{
upper = num1;
lower = num2;
}
else
if (num1 < num2)
{
upper = num2;
lower = num1;
}
else
if (num1 = num2)
{
upper = num1;
lower = num1;
}
std::cout << "All integers between " << lower << " and " << upper << " are:" << std::endl;
for (int val = lower; val <= upper; ++val)
{
if (val = upper)
{
std::cout << val << "." << std::endl;
++val;
}
else
{
std::cout << val << std::endl;
++val;
}
}
return 0;
}
If the two integers entered are 1 and 5, why does this output
5. instead of 1 2 3 4 5.?
First, you are using the assignment operator
=where you should use the comparison operator==. Second, the for loop already incrementsvaldue to the third statement of the for loop (for (...; ...; ++val)). As such, there is no need to incrementvalfrom within the body of the loop.Also, considering that you want to print all results in a single line, you should output a space after each iteration rather than
std::endl. Note that the last iteration is an exception as you will want to output a period rather than a space. In the fixed version below, I have used the ternary operator in the loop body to accomplish this.