Difficulty: Easy
Correct Answer: #include
Explanation:
Introduction / Context:
The Fibonacci series is a common example used to practice loops and variable updates. In its standard form, the sequence starts with 0 and 1, and each subsequent term is the sum of the previous two. Generating the first n terms iteratively in C reinforces correct use of for loops, variable initialisation and update order. This question asks you to choose the code that correctly implements this logic while reading n from the user.
Given Data / Assumptions:
Concept / Approach:
An iterative Fibonacci generator maintains two variables for the previous two terms and computes each new term as their sum. Initially, a equals 0 and b equals 1. After printing them, the loop repeats: compute c = a + b, print c, then update a to b and b to c. This rolling update ensures that at the next iteration, a and b again hold the two most recent terms. The loop control variable counts how many terms have been produced so that the program prints exactly n values.
Step-by-Step Solution:
Step 1: Read n from the user using scanf and declare integers a, b and c.
Step 2: Initialise a = 0 and b = 1 and print these initial two terms.
Step 3: Start a for loop from i = 3 up to i <= n, since the first two terms have already been printed.
Step 4: Inside the loop, compute c = a + b, print c, then set a = b and b = c to advance the pair.
Step 5: After the loop ends, you have printed n Fibonacci numbers starting from 0 and 1.
Verification / Alternative check:
For a small value, for example n equals 5, you can walk through the code: it prints 0 and 1, then in the loop computes 1, 2 and 3 in turn, resulting in "0 1 1 2 3", which is the expected first five Fibonacci numbers. This confirms that the update order and loop bounds are correct. The other code fragments either compute different sequences or do not print all required terms.
Why Other Options Are Wrong:
Option B never prints the initial 0 and 1 explicitly and updates a incorrectly, generating a different sequence that does not match Fibonacci. Option C prints squares of the index, not Fibonacci numbers. Option D prints only two terms regardless of the value of n and does not implement the loop that generates the series.
Common Pitfalls:
Common mistakes include forgetting to print the first two terms separately, starting the loop at the wrong index, or updating a and b in the wrong order, which can misalign the sequence. Some programmers also use recursion for Fibonacci, which is simple to write but inefficient for large n. Iterative solutions like the one shown here are preferred for both interviews and practical programs.
Final Answer:
The correct Fibonacci program initialises a = 0 and b = 1, prints them, then loops computing c = a + b and updating a and b so that it prints the first n terms starting 0 and 1.
Discussion & Comments