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