Search code examples
javamathjgrasp

Factorial Issue


I am new at coding Java, but I need to write a program that is from integer 1 to n. The program would ask the user to enter a positive number and if it is not positive then it will ask for another number.

Once the positive integer is entered for n in the program, it shows how the n factorial is computed followed by the result.

So my program will show everything correct except the result, it is not multiplying all the numbers together. If someone can point me in the right direction on how to get this solved that would be great!

CODE:

import java.util.Scanner;
public class Problem5 {
   public static void main(String[] args){

   int n, i =1;
   Scanner kbd = new Scanner(System.in);

   System.out.print("Enter n: ");
   n = kbd.nextInt();

   while (n <= 0) {
      System.out.print("Enter n: ");
       n = kbd.nextInt();
   }
   for (i = 1; i <= n; i++){
      System.out.print( i+ "*");
   }

   System.out.print(" is " + n * i);

   }
}

Output:

Enter n: 5 1*2*3*4*5* is 30


As you can see for the result it should be 120 and not 30.


Solution

  • import java.util.Scanner;
    public class Problem5 {
       public static void main(String[] args){
    
       int n, i =1;
       Scanner kbd = new Scanner(System.in);
    
       System.out.print("Enter n: ");
       n = kbd.nextInt();
    
       while (n <= 0) {
          System.out.print("Enter n: ");
           n = kbd.nextInt();
       }
       int result = 1;
       for (i = 1; i <= n; i++){
          System.out.print( i+ "*");
          result *= i;
       }
    
       System.out.print(" is " + result);
    
       }
    }
    

    Output:
        Enter n: 5
        1*2*3*4*5* is 120