Search code examples
javaloopsfor-loopfactorial

factorial in java using for loop


 /* this program 
  * finds the factorial for any number
  */

public class forLoop1{

    public static void main(int x){    
        int init; 
        for( init = x; init < 2; init--){
            int finalint = init * --init; 
            System.out.println(finalint); 
        }
    }
}

^^ This program doesn't have an output, can anyone think of what's going wrong here? Any help would be appreciated, thank you!


Solution

  • If you want to use command line argument then parse String to int.

    public static void main(String args[]) {
        int n=Integer.parseInt(args[0]);
        int fac = 1;
        for(int i = n; i >= 2; i--) {
            fac = fac * i;
        }
        System.out.println(fac);
    }
    

    You should run this program as java forLoop1 5 for an input 5 for example.