C Online Compiler
Example: Fibonacci Series in a Given Range in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series in a Given Range #include <stdio.h> int main() { // Step 1: Declare variables for the range and Fibonacci numbers int start_range, end_range; int num1 = 0; // First Fibonacci number int num2 = 1; // Second Fibonacci number int next_num; // To store the next Fibonacci number // Step 2: Prompt the user for the range printf("Enter the starting number of the range: "); scanf("%d", &start_range); printf("Enter the ending number of the range: "); scanf("%d", &end_range); // Step 3: Input validation for the range if (start_range > end_range || start_range < 0) { printf("Invalid range. Start range must be non-negative and less than or equal to end range.\n"); return 1; // Indicate an error } printf("Fibonacci series within range [%d, %d]:\n", start_range, end_range); // Step 4: Handle initial Fibonacci numbers (0 and 1) if they fall within the range // Check for 0 if (num1 >= start_range && num1 <= end_range) { printf("%d ", num1); } // Check for 1, ensuring it's not a duplicate if 0 was just printed and 1 is also valid // This condition also handles cases where start_range is 1 and 0 was not printed if (num2 >= start_range && num2 <= end_range && num2 != num1) { printf("%d ", num2); } // Step 5: Generate subsequent Fibonacci numbers and check against the range while (1) { // Infinite loop, will break when condition met next_num = num1 + num2; // If the next number exceeds the end range, break the loop if (next_num > end_range) { break; } // If the next number is within the specified range, print it if (next_num >= start_range && next_num <= end_range) { printf("%d ", next_num); } // Update num1 and num2 for the next iteration num1 = num2; num2 = next_num; } printf("\n"); // New line for cleaner output return 0; }
Output
Clear
ADVERTISEMENTS