Fibonacci sequence – Example in language C
FIBONACCI SEQUENCE – EXAMPLE IN LANGUAGE C
Another example of how to write a program that generates numbers in the Fibonacci sequence. Again using the C language.
The code is simple and goes straight to the point with explanatory comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Include file <"stdio.h"> // stdio.h is responsible for inputs and outputs. #include "stdio.h" #include "stdio.h" void main() { unsigned long long int a, b, aux; unsigned int i, n; // Assign initial values to the variables a = 0; b = 1; // The function printf() shows on the screen printf("Enter a number: "); // Gets the value entered scanf("%d", &n); printf("Fibonacci:\n"); printf("1: 1\n"); // This block generates a sequence of numbers for(i = 0; i < n-1; i++) { aux = a + b; a = b; b = aux; printf("%u: %llu\n", i+2, aux); } } |
Usually, this type of problem is proposed in computer courses and the purpose of this post is to present a way to solve it. There are other ways to solve this problem or to improve the code presented, so I hope you will not only copy and paste but try to do something better.
I hope I have been clear in the explanations.
Questions or suggestions, please contact us.
This code is available on Github: https://github.com/marceloweb/tutorials/blob/master/fibonacci.c
With the contribution of Benjamin Zaremba.