# Thread: Creating Palindromes Using Recursion

1. Member Join Date
Apr 2014
Posts
6
Rep Power
0

## Creating Palindromes Using Recursion

Hello, I need help.
I just started studying recursion and I wanted to know how to create a palindrome number going up from 1 to n then back to 1 like this: "12345...n...54321".
I've done one going downwards and then upwards like this: "n...4321234...n".

Here's my code:

Java Code:
```import java.util.*;
public class PalindromeTest
{
public static void downPalindrome(int n)
{
if(n>0)
{
System.out.print(n);
downPalindrome(n-1);
if(n!=1)
System.out.print(n);
}
}
public static void main(String args[])
{
Scanner in = new Scanner (System.in);
int x=in.nextInt();
downPalindrome(x);
}
}```
If my input is 5, the output would be: "543212345".
Can anyone help?

Thanks a lot!  Reply With Quote

2. ## Re: Creating Palindromes Using Recursion

Let's do the first type of palindromes first (the other one is similar): assume a current number i and a maximum number n; if i == n, the inner part of the palindrome is just n; otherwise, the inner part of the palindome is P(i+1, n) surrounded by i, both on the left and the right part, i.e. P(i, n) == if (i == n) then n else i P(i+1, n) i. An example: n == 3, so P(1, 3) == 1 P(2, 3) 1 == 1 2 P(3, 3) 2 1 == 1 2 3 2 1. It doesn't take much to turn this to working Java code.

kind regards,

Jos  Reply With Quote

3. Member Join Date
Apr 2014
Posts
6
Rep Power
0

## Re: Creating Palindromes Using Recursion

Thanks! Although I was trying to create it using only 1 perimeter.  Reply With Quote

4. ## Re: Creating Palindromes Using Recursion Originally Posted by Ben Bublil Thanks! Although I was trying to create it using only 1 perimeter.
But then you have to create two methods: one for the left part and one for the right part of the palindrome and both can be recursive. You can hide one parameter from the world by doing this:
P(n) == P(1,n), where the second method does all the work and the first method is just a convenience method for the user.

kind regards,

Jos  Reply With Quote

5. ## Re: Creating Palindromes Using Recursion

p.s. you can do the second type of palindrome with a one parameter method. In general: if the sentinel value (either 0 or n) can be considered some constant value, both palindrome types can be done with a one parameter method.

kind regards,

Jos  Reply With Quote

#### Tags for this Thread

java, palindrome, recursion, student #### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•