Factorial in Java - iteratively

 <<algorithm

Factorial iteratively

import java.util.Scanner;
public class Fact_iter {
  public static void main(String[] args) {
    int n;
    Scanner klaw=new Scanner(System.in);
    System.out.print("n = ");
    n=klaw.nextInt();
    int i=1, s=1;
    while(i<=n){
      s=s*i;
      i++;
    }
    System.out.print(n);
    System.out.print("! = ");
    System.out.println(s);
  }
}

 

   In the first line of the program, we inform you that we will use the Scanner class from the util java library. The Scanner class will be used to load input data in our program. In java, program execution starts with calling the public mai () function contained in the class whose name matches the program name (the program must be saved in the Fact_iter.java file and then compiled to the Fact_iter.class file). The definition of the Fact_iter class starts in the 3 program lines. Line 4 contains the beginning of the main function definition, this is the beginning of our algorithm execution (START block (1)). In the next line, we declare a variable of integer type n, which we will use in a moment to load the argniaengt function from the keyboard. In java, variables can be declared anywhere before they are used, so we do not declare variables i and s here right away. In 6 lines, we declare and initialize the key variable as a Scanner object. We indicate that the source of text data will be the System.in stream, or keyboard.

 The lines from 7 and 8 perform the input / output operation (2) in which the input data is taken - n, the number for which we want to calculate the value of the function factorial.

  In line 9, we declare the variables i and s, giving them also the initial values ​​(in both cases equal to 1) (3).

  The while statement is equivalent to the selection block (4) from our algorithm. Instructions contained in lines 11 - 12 (block 5) will be executed as long as the condition in the while statement is satisfied, i.e. until i is less than or equal to n. When constantly increasing and becomes greater than n we pass to the statement after the while loop, starting on line 14. In lines 14 to 16, the result is printed (6).

 The curly brace } from line 17 completes the main function and also the operation of the entire program (end block of the algorithm (7)).

 The curly brace } on line 18 ends the definition of the Fact_iter class.