C++ File handling: Calculate average of numbers in a file
15. Calculate the Average of Numbers Stored in a File
Write a C++ program to calculate the average of numbers stored in a file.
Sample Solution:
C Code:
Sample Output:
File content: 100 200 300 500 600 Average: 340
Explanation:
In the above exercise,
- The calculateAverage() function takes a filename and reads the numbers from the file using std::ifstream. It maintains a running sum of the numbers and a count of how many numbers are read.
- The program checks if the file has been successfully opened. If so, it reads each number from the file and updates the sum and count variables accordingly.
- After reading all the numbers, the file is closed.
- If the count is greater than 0, the average is calculated by dividing the sum by the count.
- If no numbers are found in the file, an appropriate message is displayed, and the average is set to 0.
Note: Content of a file is displayed using displayFileContent("filename.txt").
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to read numbers from a text file, calculate their sum and count, and then output the average.
- Write a C++ program that processes a file of integers, computes the average value, and displays the result with precision.
- Write a C++ program to open a file containing numeric values, sum them, and then calculate the average using file stream operations.
- Write a C++ program that reads a text file with numbers separated by spaces, computes the average, and handles invalid entries gracefully.
CPP Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Reading and displaying CSV file in tabular form.
What is the difficulty level of this exercise?