studentprogrammer - 1 year ago 85
Java Question

# find the fractorial and show the working of it e.g 5*4*3*2*1=120

i have been asked to create a program which will receive a number and take 1 away each loop until it reaches 0 and then output each number and multiply them

e.g if the user enters 5 the output should be

5*4*3*2*1=120

i tried the following with no luck

``````int factor = sc.nextInt();
int count = 0;
int total = factor;
while(factor>0)
{

for(int i = factor; i >= 0; i--)
{
count++;
total = total*count;
total = total -1;
if(i==factor)
{
}
else
}

}
}
``````

First with each iteration append the number `i` looped. Then decide to append `*` or finally `=` based on if the following iteration is the final one. After printing `=`, there remains only to print the result number. You cannot onvert the String to int, easily if it contains not-digit characters.

Try the following code:

``````Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
long factorial = 1L;

for (int i=num; i>0; i--) {
if (i-1>0) {
} else {
Input: `8`. Output: `8*7*6*5*4*3*2*1=40320`.
Input: `5`. Output: `5*4*3*2*1=120`.