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

Number pyramid in Java

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

Problem

The function func(int m,int n) outputs (for m = 3, n = 5):

3

34

345

34

3


I came up with this code:

void func(int m,int n)
{
  for(int i=1;i0)
  {
    System.out.print(j);
     k--;j++;
   }
 System.out.println("");

}

for(int i=n-m;i>0;i--)
{  int k=i;
  int j=m;

  while(k>0)
  {
  System.out.print(j);
     k--;j++;
   }
System.out.println("");

    }

}


Is there an alternate, better way to do it? Can it be more efficient?

Solution

You can do it recursively:

void func(int m,int n) {
  if (m == n) {
    System.out.println(m);
  } else {
    func(m, n - 1);
    for (int i = m; i <= n; i++) {
      System.out.print(i);
    }
    System.out.println("");
    func(m, n - 1);
  }
}

Code Snippets

void func(int m,int n) {
  if (m == n) {
    System.out.println(m);
  } else {
    func(m, n - 1);
    for (int i = m; i <= n; i++) {
      System.out.print(i);
    }
    System.out.println("");
    func(m, n - 1);
  }
}

Context

StackExchange Code Review Q#25587, answer score: 4

Revisions (0)

No revisions yet.