#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[]) // declaration of main
function
{
int limit, // a user entered limit for a loop
step, // a user entered step value
x; // control variable for the loop
cout << "Counting up from 1 to 10\n";
// The control variable x takes on values from 1 to 10
for (x = 1; x <= 10; x++) // for loop to count from 1 to 10
values incremented by 1
cout << x << " "; // print the "x" value
cout << "\n\nCounting down from 10 to 1\n";
for (x = 10; x >= 1; x--) // for loop to count from 10 to 1
values decremented by 1
cout << x << " "; // prints x value
cout << "\n\nEnter a top counting value: ";
cin >> limit; // reads the limit value from user
cout << "\n\nCounting up from 1 to " << limit <<
"\n";
for (x = 1; x <= limit; x++) // for loop to count from 1 to
given limit value incremented by 1
cout << x << " "; // prints x value
cout << "\n\nCounting up from 1 to " << limit <<
" by 2\n";
for (x = 1; x <= limit; x+=2) // for loop to count from 1 to
given limit value incremented by 2
cout << x << " "; // prints x value
cout << "\n\nEnter a step value for counting: ";
cin >> step; // reads step value
cout << "\n\nCounting up from 1 to " << limit <<
" by "
<< step << "\n";
for (x = 1; x <= limit; x+=step) // for loop to count values
from 1 to limit and incremented by the given step value
cout << x << " "; // prints x value
cout << "\n\n";
system("PAUSE");
return EXIT_SUCCESS;
}
limit: step:
limit: step:
d. What does the above tell you about using a less than/greater than relation for Boolean expressions in loops vs. using an equality/inequality relation?
Answer a
When a negative number is entered for the top counting value, for loop initial condition (1 <= limit) becomes false. So it does not print anything.
When a negative value is entered for the step value, for loop condition will always be true (x <= limit). it will become infinite loop. For example limit = 45 and step = -2 so every time x is reduced by 2 and it will make condition (x<=limit) as true. Infinite loop
Limit = 9 and step = 2 this will work.
Answer b
When Limit = 10 and step = 2 This will not work.
Answer c
This will go into infinite loop.
Answer d
LessThan/GreaterThan condition stops the execution of loop when it reaches the limit. But Equality/Inequality condition might skip the limit value and get program into infinite loop.
Get Answers For Free
Most questions answered within 1 hours.