Home > Enterprise >  Java code shows wrong Fibonacci number in Fibonacci sequence
Java code shows wrong Fibonacci number in Fibonacci sequence

Time:12-17

Im trying to make a Java code that displays the nth number in the Fibonacci sequence. For example if i put in 7, the code should show the number 8 since the 7th number in the Fibonacci sequence is 8.

But when I tried to make one, it shows the wrong number. For some reason, when i enter 7 it shows 13, and when I enter 1, it shows 0 although I already stated that the first number is 0 in the code.

Scanner input = new Scanner(System.in);
System.out.print(“In: ”);
int n = input.nextInt();

int x = 0;
int y = 1;
int a;

for (int i = 1; i <= n; i  ) {
  a = x   y;
  x = y;
  y = a;
}
System.out.print(x   " ");

I think the code for some reason ignores the first 0 which I dint understand. I would love some help, thank you.

CodePudding user response:

you will have to change the for condition to i <= n-1 and make a separate condition for when it is the first term. Fibonacci series is 1 1 2 3 5 8 13 but according to your code it is taking it as 1 2 3 5 8 13

CodePudding user response:

Spandan is correct, if you modify your code to the below you will get the correct response all the way from 1 and up...

Note:

  1. The loop now iterates only as long as i<n which removes the unwanted result.

  2. The loop though will never produce the first number in the sequence (zero) as the first iteration can not be lower than one. For that reason I have added the print of X before the loop runs the first time.

I hope this helps :)

import java.util.Scanner;

public class Fibonacci {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of terms: ");
    int n = input.nextInt();

    int x = 0;
    int y = 1;
    int a;

    System.out.print("Fibonacci sequence: ");
    System.out.print(x   " ");
     
    for (int i = 1; i < n; i  ) {
      a = x   y;
      x = y;
      y = a;
      System.out.print(x   " ");
    }
  }
}

CodePudding user response:

Try this

Scanner input = new Scanner(System.in);
System.out.print("In: ");
int n = input.nextInt();

int x = 0;
int y = 1;
int a;

for (int i = 1; i <= n; i  ) {
  a = x   y;
  x = y;
  y = a;
}
System.out.print(x   " ");
  • Related