1

This is the problem:

Develop a recursive function f() to display the sequence:

1 2 3 4 5...i (i-1) (i-2)...2 1 

in a text field when f(1,i) is called.

We are not allowed to use loops, global variables, or arrays. We also have to be able to make it work for any starting point and ending point. ex:

f(2,5)=2 3 4 5 4 3 2.

I am completely stumped. Please at least give me a hint.

4
  • 6
    We are not allowed to use loops, global variables, or arrays.: Are you allowed to code? Start it and bring here the code where you end at, then someone can surely help you finish it Commented Oct 5, 2013 at 2:37
  • 1
    Are you sure that f(2,5) is 2 3 4 5 4 3 2 1 and not f(2,5)=2 3 4 5 4 3 2? Commented Oct 5, 2013 at 2:38
  • What type does this function return? Commented Oct 5, 2013 at 2:39
  • oh yes, the sequence is 2 3 4 5 4 3 2. I do am not sure how to even start the program code..I am completely stumped Commented Oct 5, 2013 at 2:40

4 Answers 4

2

Big hint:

f(2,5) = 2 + f(3,5) + 2;
f(3,5) = 3 + f(4,5) + 3;
f(4,5) = 4 + f(5,5) + 5;
f(5,5) = 5;

so

         { a + f(a+1,b) + a     if a<b 
f(a,b) = {
         { a                    if a==b

Now try to code it.

Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking along that track, but I couldn't make it work, I think I can make that work. Thank you so much.
0

Assuming the function must return a string, here's a hint:

The base case is when the sequence has only one number in it, in which you return a sequence with that number. In other cases, you call the function recursively with the first argument one less, then put the first argument on the beginning and the end of the result.

Comments

0

Use 2 recursive functions. The code below is not tested - it is intended to serve as a hint

 void printSequenceForGivenNumber(int i)
 {
printNextBiggerNumber(i, maximum);
printNextSmallerNumber(maximum - 1)
 }

void printNextBiggerNumber(int input, int maximum)
{
    if(input <= maximum)
    {
     System.out.print(input + " ");
     printNextBiggerNumber(input + 1, maximum);  
    }
}   


void printNextSmallerNumber(int input)
{
 if (current > = 1)
 {
    System.out.print(input + " ");
    printNextSmallerNumber(input - 1);
 }

}

Comments

0

This example also handles if the the first argument is greater than the second

printUpAndDown(1, 5) = 1 2 3 4 5 4 3 2 1

printUpAndDown(5, 1) = 5 4 3 2 1 2 3 4 5

printUpAndDown(5, 5) = 5

public static void printUpAndDown(int i, int j)
{
    System.out.print(i + " ");
    if (i == j) return;
    int intToPass = (i > j) ? i - 1 : i + 1;   
    printUpAndDown(intToPass, j);
    System.out.print(i + " ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.