C Online Compiler
Example: Fibonacci Sequence Up To N in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Sequence Up To N #include <stdio.h> int main() { // Step 1: Declare variables int limit; int t1 = 0, t2 = 1; // Initialize first two Fibonacci numbers int nextTerm; // Step 2: Get user input for the limit printf("Enter a positive integer limit: "); scanf("%d", &limit); // Step 3: Print introductory message printf("Fibonacci Sequence up to %d:\n", limit); // Step 4: Handle special case for limit 0 if (limit == 0) { printf("0\n"); return 0; // Exit if limit is 0, only 0 is printed } // Step 5: Print the first term (0) if within limit if (t1 <= limit) { printf("%d", t1); } // Step 6: Print the second term (1) if within limit if (t2 <= limit && limit >= 1) { // Also ensure limit is at least 1 to print 1 printf(", %d", t2); } // Step 7: Calculate and print subsequent terms nextTerm = t1 + t2; // Calculate the third term initially while (nextTerm <= limit) { printf(", %d", nextTerm); // Print the calculated next term t1 = t2; // Shift t2 to t1 t2 = nextTerm; // Shift nextTerm to t2 nextTerm = t1 + t2; // Calculate the new next term } printf("\n"); // New line for cleaner output return 0; }
Output
Clear
ADVERTISEMENTS