Object-Oriented Programming with Java, part I – Exercise 34

This program works out the factorial of an input number. For instance the factorial of 3 would me 1*2*3=6.

My Code

import java.util.Scanner;

 

public class Factorial {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Type a number:  ");

        int n = Integer.parseInt(reader.nextLine());

        int factorial = 1;

        

        int number = 1;

        while (number <= n) {

            factorial *= number;

            number++;

        }

        

        System.out.println("The result is" + factorial);

    }

}

Model Code

import java.util.Scanner;

 

public class Factorial {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Type a number:  ");

        int n = Integer.parseInt(reader.nextLine());

        int factorial = 1;

        

        int number = 1;

        while (number <= n) {

            factorial *= number;

            number++;

        }

        

        System.out.println("The result is" + factorial);

    }

}
Leave a Reply

Your email address will not be published. Required fields are marked *