patternjavaMinor
pyramid numbers in alternative reverse order
Viewed 0 times
orderalternativereversenumberspyramid
Problem
I was asked to write code for the below structure:
And I tried the below code, which works, yet I'm wondering if there is any better approach than this:
Is there any better implementation or am I doing it right?
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15And 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
If you need a comment to explain the intent of an variable, then something went wrong. You should just rename the variable to
Also variable names which aren't loop iteration variables shouldn't have single letter names.
E.g
Space
Help you code to breath and add some space
is easier to read.
Indention
wouldn't the above be easier to read if coded like
int n=5; // no of rowsIf 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 rowsfor(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.