-1

I want to change this recursive method into an iterative method using a while and or for loop but am having trouble. Here is the Recursive method I want to translate:

public static int recursiveNum (int n)
   {
      if(n<=2)
      {  
          return 1;     
      }
      else
      {       
         return recursiveNum(n-1)+recursiveNum(n-2);
      }
   }

What i've attempted so far:

public static int iterativeNum (int n) { 
      while (i<n) {
         i++;
         if (n<=2) {
            return 1; 
            }
        
         else {
            return n = (n-1) + (n-2);
            }
         }
         return n;
      }
GabeNas
  • 1
  • 1
  • public static int iterativeNum (int n) { while (i – GabeNas May 20 '21 at 00:26
  • `(n-1) + (n-2)` sums the indexes, not the sums. You need a couple of variables to track the previous sums. – shmosel May 20 '21 at 00:31
  • 1
    And there shouldn't be a `return` in middle of the loop. You can't just dump recursive code into a loop and hope it'll work the same. – shmosel May 20 '21 at 00:32
  • If I create another variable, wouldn't I still continue to need more when n is larger than 3? Should I be using arrays? – GabeNas May 20 '21 at 00:33
  • Why use while loop? Fibonnaci sequence is best described by the recursiveness of the function. – Onyambu May 20 '21 at 00:49
  • Does this help? https://stackoverflow.com/questions/18296360/fibonacci-sequence-in-java-using-for-statements Or this? https://stackoverflow.com/questions/13021102/in-java-how-would-i-find-the-nth-fibonacci-number – Abra May 20 '21 at 01:41
  • Yes this was helpful thank you. – GabeNas May 21 '21 at 01:48

1 Answers1

0

This is Fibonnaci number you can do it by a loop and using 3 variables

public static int f(int n) {
    if (n<=2) {
      return 1;
    } else {
      int n1=0;
      int n2=1;
      int n3=0;
      for (int i=2;i<=n;i++){
          
          n3=n1+n2;
          n1=n2;
          n2=n3;
        }
      return n3;
    }
  }



public class Main
{
    public static void main(String[] args) {
            int result = f(10);
            System.out.println(result);
    }
}

output

55
ab.fe
  • 111
  • 7