Fibonacci Generator (Loop)
C
Medium
2 views
Problem Description
Print Fibonacci series of n terms using loop (not recursion). Do variables maintaining same as for previous two numbers. Space-efficient approach.
Official Solution
#include <stdio.h>
int main() {
int n, i;
int a = 0, b = 1, c;
printf("Enter number of terms: ");
scanf("%d", &n);
if (n <= 0) {
return 0;
}
printf("Fibonacci series:n");
if (n >= 1)
printf("%d ", a);
if (n >= 2)
printf("%d ", b);
for (i = 3; i <= n; i++) {
c = a + b;
printf("%d ", c);
a = b; // shift previous values
b = c;
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!