C Program to Find Average of Numbers
average = sum / count;.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n, i; float num, sum = 0.0, average; printf("Enter the number of elements: "); scanf("%d", &n); if (n == 0) { printf("Cannot divide by zero. No numbers entered.\n"); return 1; } for(i = 0; i < n; i++) { printf("Enter number %d: ", i + 1); scanf("%f", &num); sum += num; } average = sum / n; printf("Average = %.2f\n", average); return 0; }
Dry Run
Let's trace the example with 3 numbers: 5, 10, 15 through the code.
Input count
User enters n = 3
Initialize sum
sum = 0.0
First iteration
Read num = 5; sum = 0.0 + 5 = 5.0
Second iteration
Read num = 10; sum = 5.0 + 10 = 15.0
Third iteration
Read num = 15; sum = 15.0 + 15 = 30.0
Calculate average
average = 30.0 / 3 = 10.0
Print result
Output: Average = 10.00
| Iteration | Input Number | Sum After Addition |
|---|---|---|
| 1 | 5 | 5.0 |
| 2 | 10 | 15.0 |
| 3 | 15 | 30.0 |
Why This Works
Step 1: Reading numbers
We read each number one by one using a loop and add it to the total sum stored in sum.
Step 2: Calculating average
After summing all numbers, we divide the sum by the count n to get the average.
Step 3: Displaying result
We print the average with two decimal places using printf formatting.
Alternative Approaches
#include <stdio.h> int main() { int n, i; float numbers[100], sum = 0.0, average; printf("Enter the number of elements: "); scanf("%d", &n); if (n == 0) { printf("Cannot divide by zero. No numbers entered.\n"); return 1; } for(i = 0; i < n; i++) { printf("Enter number %d: ", i + 1); scanf("%f", &numbers[i]); sum += numbers[i]; } average = sum / n; printf("Average = %.2f\n", average); return 0; }
#include <stdio.h> int main() { int n, i = 0; float num, sum = 0.0, average; printf("Enter the number of elements: "); scanf("%d", &n); if (n == 0) { printf("Cannot divide by zero. No numbers entered.\n"); return 1; } while(i < n) { printf("Enter number %d: ", i + 1); scanf("%f", &num); sum += num; i++; } average = sum / n; printf("Average = %.2f\n", average); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program reads each number once in a loop of size n, so time complexity is O(n).
Space Complexity
Only a few variables are used to store sum and counters, so space complexity is O(1).
Which Approach is Fastest?
Both for and while loop approaches have the same time and space complexity; using an array uses more memory but allows reuse of numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop with sum | O(n) | O(1) | Quick average calculation without storing numbers |
| Array storage | O(n) | O(n) | When numbers need to be reused later |
| While loop | O(n) | O(1) | Beginners preferring while loops |