Java Program to Find Sum of Factorials From 1 to N

You are currently viewing Java Program to Find Sum of Factorials From 1 to N

Java program to find sum of factorials from 1 to N

import java.util.Scanner;
 
public class SumOfFactorial
{
	public static void main(String[] args)
	{
		// create scanner class object.
		Scanner sc = new Scanner(System.in);
		
		// enter the number.
		System.out.print("Enter number : ");
		int n = sc.nextInt();
 
		int total=0;
 
		int i=1;
		
		// calculate factorial here.
		while(i <= n) 
		{
			int factorial=1;
			int j=1;
			
			while(j <= i) 
			{
				factorial=factorial*j;
				j = j+1;
			}
			// calculate sum of factorial of the number.
			total = total + factorial;
			i=i+1;
		}
		// print the result here.
		System.out.println("Sum : " + total);
	}
}

Output

First run:
Enter number : 3
Sum : 9

Second run:
Enter number : 5
Sum : 153

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply