Static Local Persistence
C
Hard
2 views
Problem Description
Create a function that generates the Fibonacci sequence. Store the previous two values in static variables. Return the next Fibonacci number on every call.
Official Solution
#include <stdio.h>
/* Function to generate next Fibonacci number on each call */
int nextFibonacci() {
static int first = 0; // previous Fibonacci number F(n-2)
static int second = 1; // previous Fibonacci number F(n-1)
static int count = 0; // count of numbers returned
int next;
if (count == 0) {
count++;
return 0; // First Fibonacci number
} else if (count == 1) {
count++;
return 1; // Second Fibonacci number
} else {
next = first + second;
first = second;
second = next;
count++;
return next;
}
}
int main() {
int n, i;
printf("How many Fibonacci numbers do you want? ");
scanf("%d", &n);
printf("Fibonacci sequence:n");
for (i = 0; i < n; i++) {
printf("%d ", nextFibonacci());
}
printf("n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!