Finding Factorial of a number.
/* Finding factorial of a number input by user using while loop */
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number to find factorial: ");
int num=sc.nextInt();
int fact=1;
while(num>0)
{
fact=fact*num;
num=num-1;
}
System.out.println("Factorial is: " + fact);
}
}
while(num>0)
{
fact=fact*num;
num=num-1;
}
can be replaced by
for(i=1;i<=num;i++)
{
fact=fact*num;
}
Filename: Factorial.java
Compile: javac Factorial.java
Run: java Factorial
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number to find factorial: ");
int num=sc.nextInt();
int fact=1;
while(num>0)
{
fact=fact*num;
num=num-1;
}
System.out.println("Factorial is: " + fact);
}
}
while(num>0)
{
fact=fact*num;
num=num-1;
}
can be replaced by
for(i=1;i<=num;i++)
{
fact=fact*num;
}
Filename: Factorial.java
Compile: javac Factorial.java
Run: java Factorial