CS TECHIIE

Java Program 4: Factorial

Java learning illustration

CS TECHIIE | Java Notes and Solutions

Solved Java programming exercise. Computes factorial iteratively using long.

Logic

Computes factorial iteratively using long. Read the input, apply the operation and display the result. Test boundary values as well as typical values.

Explanation

Compile or run the program using the appropriate compiler or interpreter. Trace the variables to understand each step.

Program / SQL Solution

import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); long f=1; if(n<0){System.out.println("Invalid");return;} for(int i=2;i<=n;i++)f*=i; System.out.println(f); s.close(); } }

Practice and revision

  • Run the example and verify the output.
  • Change the input and test normal, boundary and invalid cases.
  • Write the solution again without looking at the notes.

Learn • Practise • Build • Secure — CS TECHIIE