In: Computer Science
Q1:Write a Java program to find Fibonacci Series using 1) using for loop 2) using while loop To Understand what the Fibonacci series is: The Fibonacci sequence is a series of numbers where a number is the sum of the previous two numbers. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Q2: Write a Java program to find the Factorial of a number using a while loop. To Understand what the Factorial of a Number is: Factorial of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n
Solution:
Q1)
Code:
Copyable Code:
//Import package
import java.util.Scanner;
//Main class
class Main {
//Main method
public static void main(String[] args) {
//Declaration of variables
int number,temp1=0,temp2=1;
//Prompt and get from user
System.out.println("Enter the number:");
Scanner s=new Scanner(System.in);
number=s.nextInt();
//1
System.out.print("1.Fibonacci Series using For loop is:");
//Using For loop
for (int i = 1; i <= number; ++i)
{
//output
System.out.print(temp1 + " , ");
//Calculation part
int tot = temp1 + temp2;
temp1 = temp2;
temp2 = tot;
}
//2
System.out.print("\n2.Fibonacci Series using While loop is:");
//Inititalization of variables
int i=1;
temp1=0;
temp2=1;
//Using while loop
while (i <= number)
{
//Output
System.out.print(temp1 + " , ");
//Calculation part
int tot = temp1 + temp2;
temp1 = temp2;
temp2 = tot;
i++;
}
}
}
Q2)
Code:
Output:
Copyable code:
//Import package
import java.util.Scanner;
//Main class
class Main {
//Main method
public static void main(String[] args) {
//Declaration of variables
int number,i=1;
long res=1;
//Prompt and get from user
System.out.println("Enter the number:");
Scanner s=new Scanner(System.in);
number=s.nextInt();
//Factorial of the number is
while(i<=number)
{
//Calculation
res = res * i;
i++;
}
//Print the result
System.out.println("Factorial of given number "+number+" is: "+res);
}
}