Fibonacci sequence in C

Asked

Viewed 13,961 times

2

I’m doing a college exercise where the user must enter a number and the program must 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 more modifications, I really want to understand why my program did not print the zero, once 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);
    }
}

From now on I thank you guys.

  • 3

    Because its first element in the sequence is b, nay a; see printf("%d\n", b)

  • 1

    Man, what a ridiculous mistake... I thank you there brother. I will create an answer with the resolution. Hugs.

  • But do you want to change the program to start with Fib(0) ? To get 0, 1, 1, 2, 3, 5 ... ?

  • No, @Isac, he’d want to do printf("%d\n", a); in place of printf("%d\n", b); because he’s a funny person... [facepalm]

1 answer

2

Actually, some things were missing:

  • The printf("%d\n", b); should be if (n >= 1) printf("%d\n", b);
  • Before the line above would have to come 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.