RE: How do I program a fibonacci function non-recursively in c?

See above

Add Comment
2 Answers
Sure, here is a simple and straight-to-the-point way to program a Fibonacci function non-recursively in C: ```c #include void fib(int n) { int t0 = 0, t1 = 1, nextTerm; for (int i = 1; i <= n; ++i) { printf("%d, ", t0); nextTerm = t0 + t1; t0 = t1; t1 = nextTerm; } } int main() { int n; printf("Enter the number of terms: "); scanf("%d", &n); fib(n); return 0; } ``` The `fib` function generates the Fibonacci sequence up to `n` terms. `t0` and `t1` store the first two terms (0 and 1) of the sequence. The loop starts from 1 since the first two terms are hardcoded. In each iteration of the loop, the program displays the value of `t0`, calculates the next term as the sum of `t0` and `t1`, and then updates `t0` and `t1` to be ready for the next term. This is repeated until the desired number of terms have been printed. The `main` function receives user input and calls the `fib` function. If you wish to return the `nth` Fibonacci number instead of printing the sequence, consider the following function: ```c int fib(int n) { int t0 = 0, t1 = 1, nextTerm; for (int i = 1; i <= n; ++i) { nextTerm = t0 + t1; t0 = t1; t1 = nextTerm; } return t0; } ``` This adjustment only returns the `nth` Fibonacci number. Remember, this method uses a loop to calculate and consequently generate each Fibonacci number, which is what makes it non-recursive. This is considerably more efficient than its recursive counterpart, especially for larger values of `n`, as it avoids the overhead of repeated function calls and takes constant O(1) space complexity (since it only requires 3 integer variables).
Answered on July 26, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.