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

pyramid numbers in alternative reverse order

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

Problem

I was asked to write code for the below structure:

1
    3 2
   4 5 6
  10 9 8 7
11 12 13 14 15


And I tried the below code, which works, yet I'm wondering if there is any better approach than this:

public static void main(String[] args) {

    int n=5; // no of rows
    int c=0;

    for(int i=1;i=0;j--){
               System.out.print(a[j]+" ");
            }
        }

        System.out.println("");
    }
}


Is there any better implementation or am I doing it right?

Solution

Naming

int n=5; // no of rows


If you need a comment to explain the intent of an variable, then something went wrong. You should just rename the variable to numberOfRows.

Also variable names which aren't loop iteration variables shouldn't have single letter names.

E.g c should better be currentNumber.

Space

for(int i=1;i<=n;i++){


Help you code to breath and add some space

for(int i = 1; i <= n; i++){


is easier to read.

Indention

if(i%2!=0){
    for(int j=0;j<i;j++){
        c++;
        System.out.print(c +" ");
    }
    }


wouldn't the above be easier to read if coded like

if(i%2 != 0){
        for(int j = 0; j < i; j++){
            c++;
            System.out.print(c +" ");
        }
    }

Code Snippets

int n=5; // no of rows
for(int i=1;i<=n;i++){
for(int i = 1; i <= n; i++){
if(i%2!=0){
    for(int j=0;j<i;j++){
        c++;
        System.out.print(c +" ");
    }
    }
if(i%2 != 0){
        for(int j = 0; j < i; j++){
            c++;
            System.out.print(c +" ");
        }
    }

Context

StackExchange Code Review Q#66484, answer score: 7

Revisions (0)

No revisions yet.