22.3k views
1 vote
Write a program that reads numbers from a file into an array. The array's size is 50, and the program should keep count of how many numbers it reads from the file into the array. If the file has more than 50 numbers, read the first 50 numbers into the array. If the file has fewer than 50 numbers, read only that many numbers into the array. Write a display function that accepts three arguments: an array, a number 'n', and the count of numbers read. The function should display all the numbers in the array that are greater than 'n'. The prototype of the function will be void displayGreaterThan(int array[], int n, int count).

1 Answer

5 votes

Final answer:

The solution involves creating a C program that reads up to 50 integers from a file into an array and counts them. A function called displayGreaterThan is defined to print array elements greater than a specified value, 'n'.

Step-by-step explanation:

The problem is to write a program that reads numbers from a file into an array and keeps track of the count of numbers read. The program should handle different cases depending on whether the file has more than, fewer than, or exactly 50 numbers, taking into consideration the array's size limit. After reading the numbers into the array, a display function is used to show numbers greater than a given value 'n'.

Assume the file is 'numbers.txt' and contains integer values. The program structure in C could be as follows:

#include <stdio.h>

void displayGreaterThan(int array[], int n, int count) {
int i;
for (i = 0; i < count; i++) {
if (array[i] > n) {
printf("%d\\", array[i]);
}
}
}

int main() {
FILE *file = fopen("numbers.txt", "r");
int array[50], count = 0, number;
if (file == NULL) { return -1; }

while (count < 50 && fscanf(file, "%d", &number) == 1) {
array[count++] = number;
}
fclose(file);

int n = 30; // Example threshold value
displayGreaterThan(array, n, count);
return 0;
}

The displayGreaterThan function takes an array, a threshold value 'n', and the count of elements to process. It goes through the array and prints out the values that are greater than 'n'.

User AuroMetal
by
8.2k points