Question
need help with Q4 Question 3: File Handling Write a C program that reads data from a text file named input.txt containing integers separated by
need help with Q4
Question 3: File Handling
Write a C program that reads data from a text file named "input.txt" containing integers separated by spaces. The program should calculate and display the average of these integers.
i have done this question but i need help to put this in Q4. here what I have for this Q.
#include
int main() {
FILE *file;
int num, sum = 0, count = 0;
// Open the file for reading
file = fopen("input.txt", "r");
// Check if the file is opened successfully
if (file == NULL) {
printf("Error opening the file. ");
return 1; // Exit the program with an error code
}
// Read integers from the file and calculate the sum and count
while (fscanf(file, "%d", &num) == 1) {
sum += num;
count++;
}
// Close the file
fclose(file);
// Check if any numbers were read from the file
if (count == 0) {
printf("No numbers found in the file. ");
return 1; // Exit the program with an error code
}
// Calculate and display the average
double average = (double)sum / count;
printf("Average: %.2lf ", average);
return 0; // Exit the program successfully
}
#include
int main() {
FILE *file = fopen("input.txt", "r");
int num, sum = 0, count = 0;
while (fscanf(file, "%d", &num) == 1) { sum += num; count++; }
fclose(file);
printf("Average: %.2lf ", count > 0 ? (double)sum / count : 0.0);
return 0;
Question 4: Comprehensive C Problem
Write a C program that performs the actions of Question 3, but outputs the result to another file.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started