You are on page 1of 2

package forLoops;

import java.util.Scanner;

public class AnotherFactorialCalculator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

for (int i = 0; i < 5; i++) { //loop of 5 repeats, as said in


instruction

System.out.print("Enter a potive integer: ");


int input = sc.nextInt(); //user input (u.i)

if(input > 0) { //if u.i (user input) is valid (positive


integer), lets continue. else, lets stop the program

int product = 1; //initialize "product" variable since we


cant initialize more than 1 variable inside a for loop (e.g., for (int ii = 1,
product = 1; ii <= input; ii++)). we put "1" (product = 1;) because no matter what
u.i (user input) is, 1 is the starting value, not 0.

for (int ii = 1; ii <= input; ii++) { //loop for the


factorial calculator (=1*2*3*4..). we will only stop counting while multiplying
(our loop) if we reached the value of the u.i (user input).

if(ii > 1) { //instead of using (ii == 1), we used


(ii > 1) since it has a shorter syntax. we used this logic because we want to
seperate the first instance between the rest of the loop, since the first instance
has a different (System.out.print) value. the first instance is "(user input)! =
1", while the rest is " x (ii)".

System.out.print(" x " + ii);

product *= ii; //whenever the (ii) variable has


a new value, we will multiply it to our (product) variable. if we reached the
maximum number (which is the u.i or user input), we will display the (product)
variable at the end of the line " = product".

}else {
System.out.print(input + "! = 1"); //first
instance
}
}
System.out.println(" = " + product);

}else {
System.out.println("Invalid input! Stopping the program.");
}

}
}

package forLoops;
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// ENZO PARANE DANIELA BT102A

for (int i = 0; i < 4; i++) {


System.out.print("Enter a positive integer: ");
int input = sc.nextInt();

if(input > 0) {
int product = 1;

for (int ii = 1; ii <= input; ii++) {


if(ii > 1) {
System.out.print(" x " + ii);
product *= ii;

}else {
System.out.print(input + "! = 1");
}
}
System.out.println(" = " + product);

}else {
System.out.println("Invalid input! Stopping the program.");
}

}
}

You might also like