
- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
Program to calculate average of array in C
This program should give an insight of how to parse (read) array. We shall use a loop and sum up all values of the array. Then we shall divide the sum with the number of elements in the array, this shall produce average of all values of the array.
Algorithm
Let's first see what should be the step-by-step procedure of this program −
START Step 1 → Take an array A and define its values Step 2 → Loop for each value of A Step 3 → Add each element to 'sum' variable Step 4 → After loop finishes, divide sum with number of array elements Step 5 → Store that result to avg variable and display. STOP
Pseudocode
Let's now see the pseudocode of this algorithm −
procedure avg_array(A) Declare sum as integer FOR EACH value in A DO sum ← sum + A[n] END FOR avg ← sum / size_of_array Display avg end procedure
Implementation
This pseudocode can now be implemented in the C program as follows −
#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("Average of array values is %.2f", avg); return 0; }
The output should look like this −
Average of array values is 4.50
array_examples_in_c.htm
Advertisements