after converting switch to if statements it dont work properly

Viewed 39

This is what i have after converting

int   num = 1;
int   num1 = 1;
int   num2 = 0;
int   sum = 0;
int n = 20;

 for(int i = 1; i <= n; i++) {
            switch (i) {
                case 1: num2 = num; break;
                case 2: num2 = num1; break;    
                default:
                num2 = num + num1;
                num = num1;
                num1 = num2;
            }
            sum += num2;
            System.out.print(num + " ");
        }

to

public class Fibonacci {
    public static void main(String[] args) {
        int num = 1;
        int num1 = 1;
        int num2 = 0;
        int sum = 0;
        int n = 20;

        System.out.println("The first 20 Fibonacci numbers are:");        
        for(int i = 1; i <= n; i++) {
            if(i == 1)
            {
                num2 = num;   
            }
            else if(i == 2)
            {
                num2 = num1;
            }
            else
            {
                num2 = num + num1;
                num = num1;
                num1 = num2;
            }
 
            sum += num2;
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println((double)sum / n);
    }

}

the output were

The first 20 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 885.5000

Now it is

The first 20 Fibonacci numbers are: 1 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 885.5

how to fix this, it has an extra 1 and no 6765

2 Answers

You dont need either switch or if-else to get the output you're saying you want.

But you do need to print the first number before you re-assign it.

static void main(String... args) {
    int f1 = 1;
    int f2 = 1;
    int fibN;

    double sum = 0;

    int range = 20;
    for (int i = 1; i <= range; i++) {
      fibN = f1 + f2;
      System.out.print(f1 + " ");
      f1 = f2;
      f2 = fibN;

      sum += fibN;
    }
    System.out.println();
    System.out.println("Average: " + sum / range);
  }
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
Average: 2318.25

The problem probably lies in the loops that call "i" in the first case vs. the second case. The two are most likely different.

When bounds of 0 to < n are used (vs 1 to <= n), going through the first time with i = 0 gives an extra 1 at the beginning (the default code produces 1), and the last case is omitted. This gives the results that you showed.

Related