C Online Compiler
Example: Fibonacci Series up to N Terms in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series up to N Terms #include <stdio.h> int main() { int n; int first_term = 0, second_term = 1; int next_term; // Step 1: Prompt user for the number of terms printf("Enter the number of terms (n): "); scanf("%d", &n); // Step 2: Handle edge cases for n if (n <= 0) { printf("Please enter a positive integer.\n"); } else if (n == 1) { printf("Fibonacci Series: %d\n", first_term); } else { // Step 3: Print the first two terms printf("Fibonacci Series: %d, %d", first_term, second_term); // Step 4: Calculate and print subsequent terms for (int i = 3; i <= n; ++i) { next_term = first_term + second_term; printf(", %d", next_term); first_term = second_term; // Update first_term second_term = next_term; // Update second_term } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS