# Recursion

**807569**Sep 17, 2006 4:15 PM

Hi,

I'm a second semester cs student and I am having difficulty finishing my recursion program. The problem is to: write a recursive method that takes as a parameter a non-negative integer and generatesthe following pattern of stars. If the non-negative integer is 4, then the pattern generated is:

****

***

**

*

*

**

***

****

Seems simple and after awhile I was able to generate a method that generated the above (top half) of the pattern. Here's what I have so far:

import java.util.*;

public class Exercise1Chapt14 {

static Scanner console = new Scanner(System.in);

static int n = 0;

public static void main(String[] args) {

System.out.print("Please enter a non-negative integer: ");

n = console.nextInt();

genStarPattern(n);

}

public static void genStarPattern(int x) {

if (x == 1) {

System.out.println("*");

}

else {

for (int i = 1; i <= x; i++)

System.out.print("*");

System.out.println();

genStarPattern(x - 1);

}

}

}

The problem I am having is generating the remaining (bottom) half. How do I reverse the above so it generates the bottom half? I was thinking along the lines of this formula: x-(x-1) to give me the value 1 less than the input value...but I'm stuck!

Can someone point me in the right direction? Please?

aiki

I'm a second semester cs student and I am having difficulty finishing my recursion program. The problem is to: write a recursive method that takes as a parameter a non-negative integer and generatesthe following pattern of stars. If the non-negative integer is 4, then the pattern generated is:

****

***

**

*

*

**

***

****

Seems simple and after awhile I was able to generate a method that generated the above (top half) of the pattern. Here's what I have so far:

import java.util.*;

public class Exercise1Chapt14 {

static Scanner console = new Scanner(System.in);

static int n = 0;

public static void main(String[] args) {

System.out.print("Please enter a non-negative integer: ");

n = console.nextInt();

genStarPattern(n);

}

public static void genStarPattern(int x) {

if (x == 1) {

System.out.println("*");

}

else {

for (int i = 1; i <= x; i++)

System.out.print("*");

System.out.println();

genStarPattern(x - 1);

}

}

}

The problem I am having is generating the remaining (bottom) half. How do I reverse the above so it generates the bottom half? I was thinking along the lines of this formula: x-(x-1) to give me the value 1 less than the input value...but I'm stuck!

Can someone point me in the right direction? Please?

aiki

- 269 Views
- Tags: none (add)