If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, you can use a for loop to generate the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.
Here's an example of C code that generates the first n numbers in the Fibonacci sequence:
Copy code
#include <stdio.h>
int main() {
int n, i, a=0, b=1, c;
printf("Enter the number of Fibonacci numbers to generate: ");
scanf("%d", &n);
printf("The first %d Fibonacci numbers are: \n", n);
for(i = 1; i <= n; ++i) {
if (i == 1) {
printf("%d, ", a);
continue;
}
if (i == 2) {
printf("%d, ", b);
continue;
}
c = a + b;
a = b;
b = c;
printf("%d, ", c);
}
return 0;
}
This code prompts the user to enter a positive integer n and then uses a for loop to generate the first n numbers in the Fibonacci sequence. It uses three variables, a, b, c, to store the current, next and previous Fibonacci numbers. It starts by initializing the values of a and b to 0 and 1 respectively, and then uses a for loop to iterate from 1 to n. Within the loop, it uses an if statement to handle the case for the first and second numbers of the sequence, then calculates the next Fibonacci number by adding a and b, and assigns the value of b to a, and c to b. Then it prints the current Fibonacci number. It also possible to use recursion to calculate the fibonacci sequence, where in each step the function calls itself twice with the argument decremented by 1 and 2.
Comments: 0