Program to Print Fibonacci Series using While loop
- Write a program to Print Fibonacci Series using While loop in C
- Write a program to Print Fibonacci Series using While loop in C++
- Write a program to Print Fibonacci Series using While loop in Python
- Write a program to Print Fibonacci Series using While loop in PHP
- Write a program to Print Fibonacci Series using While loop in Java
- Write a program to Print Fibonacci Series using While loop in Java Script
- Write a program to Print Fibonacci Series using While loop in C#
Explanation:
We begin with two numbers, 0 and 1, and then add the final two numbers in the sequence to produce successive numbers in order to display the Fibonacci series using a for loop.
Logic
- The first two numbers of the Fibonacci series are 0 and 1.
- Use a While loop to calculate the next number in the series by adding the two previous numbers.
- Update the previous numbers (a and b) after calculating each new number.
- Repeat until the desired number of terms is generated.
Program to Print Fibonacci Series using While loop
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h> int main() { int n, a = 0, b = 1, next; printf("Enter the number of terms: "); scanf("%d", &n); printf("Fibonacci Series: "); int i = 1; while (i <= n) { printf("%d ", a); next = a + b; a = b; b = next; i++; } return 0; }
#include <iostream> using namespace std; int main() { int n, a = 0, b = 1, next; cout << "Enter the number of terms: "; cin >> n; cout << "Fibonacci Series: "; int i = 1; while (i <= n) { cout << a << " "; next = a + b; a = b; b = next; i++; } return 0; }
n = int(input("Enter the number of terms: ")) a, b = 0, 1 print("Fibonacci Series: ", end="") i = 1 while i <= n: print(a, end=" ") next_term = a + b a = b b = next_term i += 1
<?php $n = (int)readline("Enter the number of terms: "); $a = 0; $b = 1; echo "Fibonacci Series: "; $i = 1; while ($i <= $n) { echo "$a "; $next = $a + $b; $a = $b; $b = $next; $i++; } ?>
import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of terms: "); int n = sc.nextInt(); int a = 0, b = 1, next; System.out.print("Fibonacci Series: "); int i = 1; while (i <= n) { System.out.print(a + " "); next = a + b; a = b; b = next; i++; } sc.close(); } }
let n = parseInt(prompt("Enter the number of terms: ")); let a = 0, b = 1; console.log("Fibonacci Series: ", end=""); let i = 1; while (i <= n) { console.log(a); let nextTerm = a + b; a = b; b = nextTerm; i++; }
using System; class Program { static void Main() { Console.Write("Enter the number of terms: "); int n = int.Parse(Console.ReadLine()); int a = 0, b = 1, next; Console.Write("Fibonacci Series: "); int i = 1; while (i <= n) { Console.Write(a + " "); next = a + b; a = b; b = next; i++; } } }