Write a program to generate a sum of 1! + 2! +3! ... +n!
Example:
Input: n = 4 Output: Sum of series is 33
Approach
C
#include <stdio.h>int main(){int n;printf("Enter a number: ");scanf("%d", &n);int sum = 0;for (int i = 1; i <= n; i++){int facti = 1;for (int j = 1; j <= i; j++){facti = facti * j;}sum += facti;}printf("Sum of series is %d", sum);return 0;}
Java
import java.util.Scanner;public class SumOfSeries {public static void main(String[] args) {System.out.println("Enter the number");Scanner sc = new Scanner(System.in);int n = sc.nextInt();int sum = 0;for (int i = 1; i <= n; i++) {int facti = 1;for (int j = 1; j <= i; j++) {facti = facti * j;}sum += facti;}System.out.println("Sum of series is " + sum);sc.close();}}
No comments:
Post a Comment