Java test - using "FOR" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java test - using "FOR"

/* ============ Factorial The factorial of a number N is equal to 1 * 2 * 3 * ... * N For example, the factorial of 5 is 1* 2 * 3 * 4 * 5 = 120. Request: Create a program that takes a number from input and output the factorial of that number. Tip: Use a for loop to make the calculation, and start the loop from the number 1. */ import java.util.Scanner; class Demo{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int fat = 1; for(int i=1;i<=x;i++){ fat = fat * i; System.out.println(fat); } } } // In all "test cases" the value is ok; // In "test case 1" (type 14) the result match as the expected (1278945280) //But I need to use something that the exercise request, someone have any idea?

19th Sep 2023, 2:54 PM
Sidnei Souza
Sidnei Souza - avatar
5 Answers
+ 5
Sidnei Souza , in my opinion printing have to be out of the loop -> only one value is needed. Your current code will print many values, because it is inside of the loop.
19th Sep 2023, 3:25 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 3
Sidnei Souza Learn => Practice => Solve. This is the way of solving any problem. You will not get readymade codes everywhere. Sometimes you have to do it by yourself. If you have any doubts you can ask in the community.
19th Sep 2023, 2:58 PM
JAY
JAY - avatar
+ 2
ok, thank you... and, have a nice day
19th Sep 2023, 3:08 PM
Sidnei Souza
Sidnei Souza - avatar
+ 2
//This is the right code bro import java.util.Scanner; class Demo{ public static void main(String[] args) { long fact = 1; //you have to use "long" insted of int to get big result . Scanner sc = new Scanner(System.in); int x = sc.nextInt(); for(int i=1;i<=x;i++){ fact = fact * i; } System.out.println(fact); } }
5th Nov 2023, 10:54 AM
ANIRUDDHA ADAK
ANIRUDDHA ADAK - avatar
0
WhiteCat, thank you, it solve the problem ✌️😁
19th Sep 2023, 3:50 PM
Sidnei Souza
Sidnei Souza - avatar