studentprogrammer studentprogrammer - 14 days ago 4
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;
StringBuilder answer = new StringBuilder();
answer.append(factor);
while(factor>0)
{

for(int i = factor; i >= 0; i--)
{
count++;
total = total*count;
total = total -1;
if(i==factor)
{
answer.append(" = ").append(total);
}
else
answer.append(" * ").append(String.valueOf(i));
}

}
int sanswer=Integer.parseInt(answer.toString());
return sanswer;
}

Answer

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;
StringBuilder answer = new StringBuilder();

for (int i=num; i>0; i--) {
    answer.append(i);
    if (i-1>0) {
        answer.append("*");
    } else {
        answer.append("=");
    }
    factorial *= i;
}
answer.append(factorial); 
System.out.println(answer);

Input: 8. Output: 8*7*6*5*4*3*2*1=40320.

Input: 5. Output: 5*4*3*2*1=120.