Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 25

C Exercise 25

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Find the sum of 1 + 2! + 3! + ... + 20!.

**Analysis:** This program simply changes accumulation into multiplication.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

// Function to calculate factorial

unsigned

long

long

factorial

(

int

n

)

{

unsigned

long

long

result

=

1

;

for

(

int

i

=

1

;

i

<=

n

;

i

++

)

{

result

*=

i

;

}

return

result

;

}

int

main

(

)

{

unsigned

long

long

sum

=

0

;

// Calculate 1 + 2! + 3! + ... + 20!

for

(

int

i

=

1

;

i

<=

20

;

i

++

)

{

sum

+=

factorial

(

i

)

;

}

// Output result

printf

(

"

The sum of 1 + 2! + 3! + ... + 20! is: %llu

\

n

"

,

sum

)

;

return

0

;

}

The output of the above example is:



1 + 2! + 3! + ... + 20!的和是: 2561327494111820313

Code Analysis

- Initialize `result` to 1. - Use a `for` loop to multiply from 1 up to `n`. - Define a `sum` variable to accumulate the sum of all factorials, of type `unsigned long long` to handle larger values. - Use a `for` loop to compute the factorials from 1 to 20 and accumulate the results into `sum`. - Use the `printf` function to output the final result.

100 Classic C Language Examples 100 Classic C Language Examples