sideway number pattern

I need to print the following

1
12
123
1234
12345
1234
123
12
1

I did the following and was wondering if there was a better way to do it.

int q, r, s = 1;
for (q = 1; q >= 1; q += s)
{
for (r = 1; r < q; r++ )
cout << setw(4) << r;
cout << "\n";
if ( q == 6 )
s = -1;
Your loop won't do anything for q=1 (except print a blank line), because with the initial values (r=1 and q=1) you cannot satisfy r < q. Maybe change it to r <= q?

Your use of the "magic number" 6 at which to change the step s from ascending to descending hardwires the code to do one case only.

Apart from that, your method looks fine, except that you are missing all the code that will make it runnable (and, in particular, the closing brace for the q loop). Use code tags so that we can see your indentation and include the complete code.

You could limit the scope of variables q, r, s by declaring and initialising them in the "for" statements: q and s in the outer one, r in the inner one.


Here's a "generalised" version FWIW
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
using namespace std;

string triangle( const string &line, int nmax = 0, int n = 1 )
{
   if ( nmax == 0 ) nmax = line.size();
   string result = line.substr( 0, n ) + '\n';
   if ( n < nmax ) result = result + triangle( line, nmax, n + 1 ) + result;
   return result;
}

int main()
{
   cout << triangle( "12345" ) << '\n';
   cout << triangle( "ABCDEFGH" );
}
Last edited on
a better way

I’d go with the double loop (an inner loop inside another one) as you did, but, if you want to avoid the double loop, perhaps you could:
1) follow lastchance’s directions (probably the most general solution);

2) inside your (now unique) loop, at every iteration multiply the number to be shown by 10 and add the last digit (works only with digits) - later you need to divede by 10, of course;

3) fill a std::vector<int> by means of std::iota() and show an increasing (and later decreasing) number of elements - probably the best performing method :-) (ok, just kidding);

I haven’t written the codes, just clues.
Topic archived. No new replies allowed.