- How to calculate the average of array elements
- How to use type casting for accurate results
- How to handle integer and float calculations
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to calculate the average of array elements.
Finding the average of elements in an array is a common programming task. It is used in many real-world applications, such as:
- Calculating the average score of students in a class
- Finding the average temperature in weather data
- Calculating the average sales figures
- Finding the average of sensor readings
💡 Key Point: The average is calculated by first finding the sum of all elements and then dividing by the total number of elements. Using type casting ensures you get a decimal result instead of integer division.
C Program to Calculate Average of Array Elements
#include <stdio.h>
int main() {
int n, i;
int sum = 0;
float average;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array of size n
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Calculate sum of array elements
for(i = 0; i < n; i++) {
sum = sum + arr[i];
}
// Calculate average using type casting
average = (float)sum / n;
// Display the average
printf("\nSum of all elements: %d\n", sum);
printf("Average of all elements: %.2f\n", average);
return 0;
}
Sample Output
Enter the number of elements: 5 Enter 5 elements: 10 20 30 40 50 Sum of all elements: 150 Average of all elements: 30.00
Another Example (With Decimal Result):
Enter the number of elements: 4 Enter 4 elements: 10 15 25 30 Sum of all elements: 80 Average of all elements: 20.00
Example with Non-Integer Average:
Enter the number of elements: 6 Enter 6 elements: 10 20 30 40 50 60 Sum of all elements: 210 Average of all elements: 35.00
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;— stores the number of elementsint i;— loop counterint sum = 0;— stores the sum of elementsfloat average;— stores the calculated average
- Get User Input: Prompts the user to enter the number of elements and then reads them into the array.
- Calculate Sum: The
forloopfor(i = 0; i < n; i++)iterates through each element and adds it tosumusingsum = sum + arr[i];. - Calculate Average:
average = (float)sum / n;divides the sum by the number of elements. The(float)type casting is important because:- If both operands are integers, C performs integer division and truncates the decimal part
- Type casting converts the sum to float, resulting in a decimal value
- Display Results:
printf("\nSum of all elements: %d\n", sum);andprintf("Average of all elements: %.2f\n", average);display the results with two decimal places. - Return:
return 0;indicates successful program execution.
📝 Important: Without type casting (float)sum / n, if sum is an integer and n is an integer, the result will be truncated. For example, 7 / 2 = 3 instead of 3.5. Always use type casting for accurate average calculations.
Algorithm to Calculate Average
- Start
- Read the number of elements (n)
- Read n elements into the array
- Set
sum = 0 - For
i = 0ton-1:sum = sum + arr[i]
- Set
average = (float)sum / n - Print sum and average
- End
Optimized Version: Single Loop
You can combine the sum calculation into the same loop where you read the input, making the program more efficient:
#include <stdio.h>
int main() {
int n, i;
int sum = 0;
float average;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum = sum + arr[i]; // Calculate sum on the fly
}
average = (float)sum / n;
printf("\nSum of all elements: %d\n", sum);
printf("Average of all elements: %.2f\n", average);
return 0;
}
💻 Practice Exercise
Challenge 1: Modify the program to calculate the average of only the even numbers in the array.
Challenge 2: Calculate the average of positive and negative numbers separately.
🔍 Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int n, i;
int sum = 0;
int count = 0;
float average;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
if(arr[i] % 2 == 0) { // Check if even
sum = sum + arr[i];
count++;
}
}
if(count > 0) {
average = (float)sum / count;
printf("\nSum of even elements: %d\n", sum);
printf("Average of even elements: %.2f\n", average);
} else {
printf("\nNo even numbers found.\n");
}
return 0;
}
Frequently Asked Questions
1. How do you calculate the average of array elements in C?
First, calculate the sum of all elements using a loop. Then, divide the sum by the total number of elements. Use type casting (float) to get a decimal result.
2. Why do I need type casting when calculating average?
Without type casting, C performs integer division when both operands are integers. For example, 7 / 2 = 3 instead of 3.5. Type casting ensures you get the correct decimal result.
3. What happens if the array is empty?
If the array has no elements (n = 0), division by zero occurs, which causes an error. Always check that n > 0 before calculating the average.
4. Can I calculate the average using a float array?
Yes, you can use a float array. The average calculation remains the same. If the array is of type float, you don't need type casting.
5. How can I display the average with more decimal places?
Use %f instead of %.2f in the printf statement. You can also specify the number of decimal places, like %.3f for three decimal places.
💡 Tip: Always use type casting (float) when dividing integers to get accurate decimal results. This is a common mistake beginners make.