Write a program to print the Fibonacci series up to n terms.
Example:
Input: n = 10 Output: Fibonacci Series is: 0 1 1 2 3 5 8 13 21 34
Approach
C
#include <stdio.h>int main(){int n;printf("Enter a number: ");scanf("%d", &n);int a = 0, b = 1;int cnt = 0;printf("Fibonacci Series is: ");if (n == 1)printf("%d", a);else if (n == 2)printf("%d %d", a, b);else{printf("%d ", a);printf("%d ", b);for (int i = 2; i < n; i++){int fib = a + b;int temp = b;b = a + b;a = temp;printf("%d ", fib);}}return 0;}
Java
import java.util.Scanner;public class Main{public static void main(String[] args) {System.out.println("enter the value of n");Scanner sc = new Scanner(System.in);int n = sc.nextInt();int a = 0;int b = 1;if(n==1){System.out.print(a);}else if(n==2){System.out.print(a+" "+b);}else{System.out.print(a);System.out.print(" "+b);for (int i = 2; i < n; i++){int fib = a + b;int temp = b;b = a + b;a = temp;System.out.print(" "+fib);}}}}
No comments:
Post a Comment