HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Creating number pattern (triangle numbers) in C++ with minimum loops

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbercreatingwithnumbersloopsminimumtrianglepattern

Problem

We were asked to make a triangular number pattern in C++ with minimum loops:

____1_____
___2__3____
__4__5__6__
7__8__9__10


Code:

#include 

using namespace std;
int main() {
    int n=0, r=0, i=0;
    cout > r;

    for( n=1; n<=r; n++) {
        for( i=1; i<=r-n; i++) {
            cout << "  ";
        }
        for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
            if( i<10 )
                cout << " " << i << "  ";
            else
                cout << i << "  ";
        }
        cout << "\n";
    }
    return 0;
}


Output:

Here's what I'd like reviewed:

  • Is it wise to use pattern-generating formulas? For example, for putting value of i in the last loop, I used the formula for the pattern \$1,2,4,7\$... as \$\frac{n*(n-1)}{2}+1\$. Is it efficient? This involves four operations in each iteration, and it's fairly slow.



  • Is it possible to reduce the number of loops? Is it better to reduce variables or reduce loops?

Solution

Spacing

Use as much whitespace as needed, it makes it easier to read code, especially formulas or expressions with a lot of operators.

using namespace std;


This is discouraged, I don't think it makes much difference in a program of this size, but it can be a bad habit to rely on.

int n=0, r=0, i=0;


Try and only declare variables in the smallest scope possible, as in right when you need them. Since n and i are only ever used inside the loops, only declare them there.

I would avoid assigning 0 to r, as then if later the program crashes, and I see r no value, it makes the bug much easier to spot than if r has a valid value.

for( n=1; n<=r; n++) {
    for( i=1; i<=r-n; i++) {
        cout << "  ";
    }


This is completely up to you, but I would start the loops at 0, and go until n
#include
#include

int main() {
int r;
std::cout > r;

int count = 1;
for(int n = 1; n

The padding works well up until 45 rows are entered, after that, it was too wide for my screen to properly read.

Code Snippets

using namespace std;
int n=0, r=0, i=0;
for( n=1; n<=r; n++) {
    for( i=1; i<=r-n; i++) {
        cout << "  ";
    }
for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
if( i<10 )
        cout << " " << i << "  ";
    else
        cout << i << "  ";
}

Context

StackExchange Code Review Q#104037, answer score: 3

Revisions (0)

No revisions yet.