trying to generate a fibonacci sequence 0,1,1,2,3,5,8,13,21,34 with for loop and without the final comma

1

This is my code, if I do not put conditions I get everything but I add a final comma and trying to filter the last position of i with an if () omits the last two numbers.

public class EjercicioFibonacci {
    public static void main(String[] args) {
        int a=0,b=1;
        for (int i = 0; i < 4; i++) {
            if (i==0) {
                System.out.print(a+","+b+",");
            }else if(i==3) {
                a=a+b;
                b=a+b;
                System.out.print(a+","+b);
            }else {
                a=a+b;
                b=a+b;
                System.out.print(a+","+b+",");
            }



        }
    }

}
    
asked by David Palanco 27.05.2018 в 16:25
source

2 answers

3

The way you are doing the tour, you should set the conditionals in this way .. with two consecutive ifs , so that in the first loop of the for loop , read the first if the condition is met, and continue and also enter the else , with i=0 . So you will not miss another round in the for, as I was missing. I do not know if I explained myself well.

for (int i = 0; i < 4; i++) {
            if (i==0) {
                System.out.print(a+","+b+",");
            }
            if(i==3) {
                a=a+b;
                b=a+b;
                System.out.print(a+","+b);
            }else {
                a=a+b;
                b=a+b;
                System.out.print(a+","+b+",");
            }
        }
    
answered by 27.05.2018 / 17:26
source
5

You can do it easily in the following way without needing if-else and solving the problem of the last comma:

public static void main(String[] args) {

        int n1 = 0, n2 = 1, n3, cantidad = 10;

        // Imprimir 0 y 1
        System.out.print(n1 + ", " + n2);

        // Comienza desde 2 porque 0 y 1 ya fueron imprimidos anteriormente
        for (int i = 2; i < cantidad; ++i) {
            n3 = n1 + n2;
            System.out.print(", " + n3);
            n1 = n2;
            n2 = n3;
        }
    }

Result: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

    
answered by 27.05.2018 в 17:04