Re: C++ Primer 4/e exercise 1.19
On Jul 12, 9:21 am, arnuld <geek.arn...@gmail.com> wrote:
STATEMENT: Write a program that prompts the user for two numbers and
writes each number in the range specified by the two numbers to the
standard output. Revise the program so that it never prints more than
10 numbers per line.
i have written the 1st part of it which prints the range:
#include <iostream>
int main()
{
std::cout << "Enter 2 numbers: ";
int v1, v2;
std::cin >> v1 >> v2;
int lower,upper;
if(v1 <= v2)
{
lower = v1;
upper = v2;
}
else
{
lower = v2;
upper = v1;
}
Just a nit, but I'd replace the above with something like:
int upper ;
int lower ;
std::cin >> lower >> upper ;
// Check for errors here!!!
if ( upper < lower ) {
std::swap( upper, lower ) ;
}
No need for the extra variables.
for(int i=lower; i <= upper; ++i)
std::cout << i
<<" "; // space between two numbers
std:: cout << "\nThank you ;-)" << std::endl;
}
it works but i am not able to print 10 numbers per line. i tried to
embed a for loop within the original for loop i used in the programme
but that does not work.
It's possible to use a nested loop, with the outer loop
outputting each line, and the inner loop the elements.
Something like:
for ( int i = lower ; i <= upper ; i += 10 ) {
for ( int j = i ; j < i + 10 && j <= upper ; ++ j ) {
...
}
std::cout << '\n' ;
}
(Note the condition on the inner loop.)
That actually works well for this simple example, but generally,
I like to manage the line length separately, using a variable
just for it:
int inLineCount = 0 ;
for ( ... ) {
if ( inLineCount == 0 ) {
// Output start of line, etc.
} else {
// Output separator between values.
}
// Output value
++ inLineCount ;
if ( inLineCount >= N ) {
// Output end of line data, etc., and new line.
inLineCount = 0 ;
}
}
if ( inLineCount != 0 ) {
// Output end of line data, etc., and new line.
// In some cases, you might want to treat an
// incomplete last line differently.
}
It's a little bit more complicated, but is the most adaptable.
It's become a pattern in my code.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34