Printing Fibonacci Series

 Printing Fibonacci Series


C Program
1.For Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x,y,n,z;
    printf("Enter Any Number:");
    scanf("%d",&n);
    x=0;
    y=1;
    for(n=n;n!=0;n--)
    {
        printf(" %d",x);
        z=y+x;
        x=y;
        y=z;
    }
}
2.While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x,y,n,z;
    printf("Enter Any Number:");
    scanf("%d",&n);
    x=0;
    y=1;
    while(n!=0)
    {
        printf(" %d",x);
        z=y+x;
        x=y;
        y=z;
        n--;
    }
}
3.Do While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x,y,n,z;
    printf("Enter Any Number:");
    scanf("%d",&n);
    x=0;
    y=1;
  if(n!=0)
  {
     do
      {
        printf(" %d",x);
        z=y+x;
        x=y;
        y=z;
        n--;
     }while(n!=0);

  }
}
Java Program
1.For Loop

import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {
		int x,y,z;
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		x=0;
	    y=1;
	    for(n=n; n!=0;n--)
	    {
	        System.out.print(x + " ");
	        z=y+x;
	        x=y;
	        y=z;
	    }
	}
}
2.While Loop
import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {
		int x,y,z;
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		x=0;
	    y=1;
	    while(n!=0)
	    {
	    	System.out.print(x + " ");
	        z=y+x;
	        x=y;
	        y=z;
	        n--;
	    }
	}
}
3.Do while Loop
import java.util.Scanner;

public class EvenoroddSwitch {

	public static void main(String[] args) {
		int x,y,z;
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		x=0;
	    y=1;
	    if(n!=0)
	    {
	       do
	        {
	    	   System.out.print(x + " ");
	          z=y+x;
	          x=y;
	          y=z;
	          n--;
	       }while(n!=0);
	   
	    }
	}
}

0 Comments:

Post a Comment