Fibonacci sequence in C

0

I'm doing a college exercise where the user must enter a number and the program should return the Fibonacci sequence. However, according to the teacher, it should start at 0 (ZERO), but my program starts at 1.

Note: The teacher has already corrected and will not accept any further modifications, I really want to understand why my program did not print zero, since I declared a = 0 .

Program:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <locale.h>

main() {

    setlocale(LC_ALL, "Portuguese");

    int a, b, auxiliar, i, n;

    a = 0;
    b = 1;

    printf("Digite um número: ");
    scanf("%d", &n);
    printf("\nSérie de Fibonacci:\n\n");
    printf("%d\n", b);

    for(i = 0; i < n; i++) {

        auxiliar = a + b;
        a = b;
        b = auxiliar;

        printf("%d\n", auxiliar);
    }
}

Thanks in advance.

    
asked by anonymous 24.05.2018 / 00:38

1 answer

0

In fact, some things were missing:

  • The printf("%d\n", b); should be if (n >= 1) printf("%d\n", b);
  • Before the above line, you would have to if (n >= 0) printf("%d\n", a);
  • The for would have to be for (i = 2; i <= n; i++) { ... }

The { ... } above means:

{
    auxiliar = a + b;
    a = b;
    b = auxiliar;

    printf("%d\n", auxiliar);
}
    
24.05.2018 / 18:30