|
|
In the first line of the program, we state that we will use the Scanner class from Java's util library. The Scanner class will be used for reading input data in our program. In Java, program execution starts with the call to the public static main() function, which is contained within a class whose name matches the program's name (the program must be saved in the Fact_rec.java file and then compiled into the Fact_rec.class file). The definition of the Fact_rec class begins in line 3 of the program. Line 4 contains the start of the main function definition; this is the beginning of our algorithm's implementation (START block (1)). In the following line, we declare the integer variable n, which we will shortly use to read the factorial function argument from the keyboard. In Java, variables can be declared anywhere before they are used, which is why we don't immediately declare the f (result) variable here. In line 6, we declare and initialize the variable klaw as an object of type Scanner. We specify that the source of the text data will be the System.in stream, which is the keyboard.
Lines 7 and 8 implement the input/output operation (2), where the input data is retrieved—n, the number for which we want to calculate the factorial function.
In line 9, we declare the f variable and assign to it the result of the factorial function called with the argument n.
In lines 10 through 11, we print the obtained result (input-output block (6)).
The curly brace } on line 12 ends the main function and simultaneously terminates the operation of the main part of the program (STOP block (7) of the algorithm).
In line 15, we declare the factorial function that we used in the main function. A function that is a method of the same class does not have to be declared before its use. The factorial function accepts one integer argument (n) and returns an integer result. The function body—the set of instructions executed by the program after the function is called—is contained between the curly braces { at the end of line 15 and } on line 20.
In line 16, we check if n is greater than 1—block (3) of the algorithm. If so, then in line 17, we set the function's result as n multiplied by the value of the factorial function (the same factorial function we are currently defining) for n minus 1 (4). At this point, the factorial function calls itself. Such a function is called a recursive function. If n is not greater than 1, then in line 19, we set the function's result equal to 1 (the condition for ending the recursion)—block (5).
The curly brace } on line 20 ends the factorial function, while the curly brace on line 21 ends the definition of the Fact_rec class.
