In: Computer Science
Let’s revisit the Fibonacci sequence, this time without an array. Recall that the sequence is defined by the following recurrence relation: F0 = 0 F1 = 1 Fk = Fk-1 + Fk-2 So, the sequence looks like: 0, 1, 1, 2, 3, 5, 8, 13, 21, … Write a program fib.c consisting only of a main() function that prompts the user for the last Fibonacci number n to print, and then prints them from F0 to Fn. (No file input needed.) For instance, if the user enters 4, the output should be: F0: 0 F1: 1 F2: 1 F3: 2 F4: 3 Again, no arrays or pointers. For full credit use no more than five integer variables (and no other variables). You may assume that n > 1.
Solution:-
C Code:-
#include<stdio.h>
int main()
{
// Declaratio of variables
int i, term, z, x = 0, y = 1;
// Prompt user to Enter number of terms
printf("Enter the number of terms:");
scanf("%d",&term);
// Printing first two term results
printf("F0: %d F1: %d ",x,y);
// Looping from second term till user entered term
for(i = 2 ; i <= term ; i++ )
{
// Computing the next term
z = x + y;
// Printing the next term
printf("F%d: %d ",i,z);
// Swapping the term values
x = y;
y = z;
}
return 0;
}
Code snapshot:-
Output snapshot:-