Home > Java > javaTutorial > How to use while loop to find the factorial of n in java

How to use while loop to find the factorial of n in java

王林
Release: 2020-06-16 11:03:21
Original
12947 people have browsed it

How to use while loop to find the factorial of n in java

Implementation ideas:

1. Define two variables to store the number representing the factorial and the factorial result respectively;

2. Use while Calculate the factorial in a loop;

3. Just print the factorial result.

(Recommended video tutorial: java video tutorial)

The specific code is as follows:

package hello;

import java.util.Scanner;

public class Hello {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  int n;
  n=in.nextInt();
  int i=1,sum=1;
  while(i<=n)
  {
   sum=sum*i;
   i++;
  }
  System.out.print(sum);
 }

}
Copy after login

Recommended tutorial: java entry program

The above is the detailed content of How to use while loop to find the factorial of n in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template