Java Programming Questions and it's Solution

1.Write a program for Fibonacci Series: Program: import java.util.Scanner; public class Practice { //Write a program for Fibonacci Series //This is a program where each numbers are summation of previous two numbers like public static void main(String args[]) { Scanner sc = new Scanner(System.in);//Here Scanner class is used to take inputs from user long x = 0; long y = 1; long z; System.out.print("The maximum value entered by you is: "); int num = sc.nextInt(); System.out.println("The maximum value entered by you is: " + num); System.out.println("Expected Fibonacci series is: "); System.out.print("\t" + x); System.out.print("\t" + y); for (int k = 2; k <= num; k++) {// Since the value at position 0 and 1 is already printed hence in for loop we are starting from 3rd position directly z = x + y;//Since each value is the summation of it's previous two positions System.out.print("\t" + z); x = y;//As after each iteration position of x will be replaced/changed by y y = z;//As after each iteration position of y will be replaced/changed by z } } }

No comments:

Post a Comment