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

Printing a diamond of numbers

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

Problem

If you input the number 3 from the keyboard, the program will show this:

0
    0 1 0
  0 1 2 1 0
0 1 2 3 2 1 0
  0 1 2 1 0
    0 1 0
      0


Here is my code:

#include 

using namespace std;

int main()
{
    unsigned i,k=0,n;
    cout>n;

    while(k0;i--)
                cout0;i--)
                cout<<i-1;
            cout<<endl;

        }
}


I have two questions:

-
Is there a better/easier/clever way to do this?

-
How to deal with spaces? How to show them? (because my code is working but it doesn't show spaces to make this diamond look)

Solution

-
using namespace std is not preferred, although not that bad for small programs.

-
Each variable should be declared/initialized on separate lines. This improves readability and also makes it easier to add any necessary comments.

unsigned i;
unsigned k = 0;
unsigned n;


Same with this:

cout > n;


-
Prefer "\n" to std::endl here (the latter flushes the buffer, which takes longer). It's still okay to use the latter where both flushing and newlining are needed.

-
Always use descriptive names for variables. Single-characters are best for loop counters (such as i). This will vastly improve readability as you won't need comments to describe them.

-
It looks like you could use recursion instead of all these loops. It may take longer (if you input a large number), but it should at least simplify the logic.

Code Snippets

unsigned i;
unsigned k = 0;
unsigned n;
cout << "n= ";
cin >> n;

Context

StackExchange Code Review Q#33088, answer score: 10

Revisions (0)

No revisions yet.