Factorials
by CodeChum Admin
For those of you who may not now, a factorial is a product of multiplying from 1 until the number. Now, you must make a program that will accept an integer and then print out its factorial using loops.
Are you up for this task?
Instructions:
Input a positive integer.
Using a for() loop, generate the factorial value of the integer and print out the result.
Tip #1: Factorials work like this: Factorial of 5 = 1 * 2 * 3 * 4 * 5
Tip #2: There's a special case in factorials. The factorial of 0 is 1.
Input
A line containing an integer.
5
Output
A line containing an integer.
120
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
package com.company;
import java.util.*;
class Main {
// Main driver method
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//propmt the user to enter an integer value
System.out.print("\nEnter an integer: ");
int my_integer = sc.nextInt();
int factorial = 1;
for(int i = 1; i<= my_integer;i++)
{
factorial = factorial * i;
}
System.out.println("\nThe factorial of "+my_integer+" = "+factorial);
}
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment