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

C Language Examples - Calculating the Average of Array Elements

C Language Examples - Calculating the Average of Array Elements

C Language Examples C Language Examples

Use a for loop to iterate over and output the elements, add up all elements to get the sum, then divide by the number of elements:

Example 1

#include

<

stdio.h

int

main

(

)

{

int

array

[

10

]

=

{

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

0

}

;

int

sum

,

loop

;

float

avg

;

sum

=

avg

=

0

;

for

(

loop

=

0

;

loop

<

10

;

loop

++

)

{

sum

=

sum

array

[

loop

]

;

}

avg

=

(

float

)

sum

/

loop

;

printf

(

"

The average is %.2f

"

,

avg

)

;

return

0

;

}

The output is:



平均值为 4.50

User-defined input:

Example 2

#include

<

stdio.h

int

main

(

)

{

int

n

,

i

;

float

num

[

100

]

,

sum

=

0

.0

,

average

;

printf

(

"

Enter the number of elements:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

while

(

n

100

||

n

<=

0

)

{

printf

(

"

Error! The number must be between 1 and 100.

\

n

"

)

;

printf

(

"

Enter again:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

}

for

(

i

=

0

;

i

<

n

; ++

i

)

{

printf

(

"

%d. Enter number:

"

,

i

1

)

;

scanf

(

"

%f

"

, &

num

[

i

]

)

;

sum

+=

num

[

i

]

;

}

average

=

sum

/

n

;

printf

(

"

Average = %.2f

"

,

average

)

;

return

0

;

}

The output is:



输入元素个数: 4

1. 输入数字: 1

2. 输入数字: 2

3. 输入数字: 4

4. 输入数字: 8

平均值 = 3.75

C Language Examples C Language Examples