Question

Created a program that would input a number and provides its equivalent fibonacci number as an output. But there's something wrong with my code :c

import java.util.Scanner;
public class Fibonacci {
    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        int prev, next, num, sum = 0, n;
        prev=next=1;

        System.out.print("Input number: ");
        num = in.nextInt();

        if ((num == 1) || (num ==2))
            System.out.println(prev);

        else {
            for( n=1; n<=prev; n++ ) {
                sum = prev + next;
                prev = next;
                next = sum;
            }

            System.out.println(sum);
        }

    }
}

Something's wrong I just can't see. Help? :c

Was it helpful?

Solution 2

Change your for loop to this:

for( n=2; n<num; n++ )

That'll solve your problem.

Explanation: Since you've already determined that 1 or 2 will give you a 1, start your loop @ 2. Loop through until n becomes larger than the entered number. This will solve the problem you were having.

OTHER TIPS

You're stopping the loop when n reaches beyond prev, so you aren't getting the correct number. Stop it when you've passed num instead:

for(n = 1; n <= num; n++) {

Example run:

Input number: 6
21

If you want to get the fiboniki number times the user has given input then you need to iterate in for loop.

 for( n=1; n<=num; n++ ) {
                    sum = prev + next;
                    prev = next;
                    next = sum;
                    System.out.println(sum);
                }

Also to print the number you need to put it in the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top