patternjavaMinor
Number pyramid in Java
Viewed 0 times
numberpyramidjava
Problem
The function
I came up with this code:
Is there an alternate, better way to do it? Can it be more efficient?
func(int m,int n) outputs (for m = 3, n = 5):3
34
345
34
3I 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.