|
|
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_iter.java file and then compiled into the Fact_iter.class file). The definition of the Fact_iter 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 variables i and s 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 variables i and s, simultaneously assigning them initial values (equal to 1 in both cases) (3).
The while statement is the equivalent of the selection block (4) from our algorithm. The instructions contained in lines 11-12 (block 5) will be executed as long as the condition in the while statement is met, meaning as long as i is less than or equal to n. When the constantly incremented i becomes greater than n, we proceed to the statements after the while loop, starting in line 14. In lines 14 through 16, the result is printed (6).
The curly brace } on line 17 ends the main function and simultaneously terminates the operation of the entire program (the algorithm's STOP block (7)).
The curly brace } on line 18 ends the definition of the Fact_iter class.
