Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.608221'
Loops: While: Fibonacci
Loops: While: Fibonacci
Task: Compute the Fibonacci sequence:
Write a C program that prompts the user to enter the number of terms they want in the Fibonacci sequence and computes the sequence using a while loop. Display the sequence using printf().
The Fibonacci sequence starts with 0 and 1, and each subsequent term is the sum of the previous two terms. For example, if the user enters 8, the program should compute and display the first 8 terms of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13.
Hint: You need to follow the 2 previous number ans so 2 variables need to be defined for that.
Solution
#include
int main() {
int numTerms;
printf("Enter the number of terms for the Fibonacci sequence: ");
scanf("%d", &numTerms);
if (numTerms <= 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 0;
}
printf("The Fibonacci sequence of %d terms is: ", numTerms);
int term1 = 0;
int term2 = 1;
int count = 2;
printf("%d, %d", term1, term2);
while (count < numTerms) {
int nextTerm = term1 + term2;
printf(", %d", nextTerm);
term1 = term2;
term2 = nextTerm;
count++;
}
printf("...\n");
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter the number of terms they want in the Fibonacci sequence. The scanf() function is used to scan the input from the user and store it in the numTerms variable. The program checks if the number of terms is less than or equal to 0. If it is, it prints an error message and terminates the program. Otherwise, it uses printf() to display the initial terms of the Fibonacci sequence. The variables term1 and term2 are initialized to 0 and 1 respectively, and the count variable is set to 2 since the initial terms have already been displayed. The while loop continues as long as count is less than the number of terms. In each iteration, it computes the next term by adding term1 and term2, displays the next term using printf(), updates term1 and term2 to shift them for the next iteration, increments count, and repeats the process until the desired number of terms is reached. Finally, it uses printf() to display the ellipsis to indicate that the sequence continues.