In: Computer Science
4. Write a program that reads all numbers from a file and determines the highest and lowest numbers. You must NOT use arrays to solve this problem! Write functions where appropriate.
Programming language should be C
Please find below the code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you need any change in code. Else please upvote
CODE:
#include <stdio.h>
//function prototype
void findMinMax(FILE *fp, int *min, int *max);
int main()
{
int min, max; //Variables for smallest and largest numbers
char filename[200]; //Variable for filename
printf("Enter the filename: ");
scanf("%s", filename); //Reading the filename from user
FILE *fp = fopen(filename, "r"); //Open the file in read mode
if (fp == 0)
{
printf("Failed to open file %s\n", filename); //display error if file open fails
return 1; //and return
}
findMinMax(fp, &min, &max); //calling findMinMax() with fp, min and max as call by reference
fclose(fp); //closing the file
printf("Smallest Number: %d\n", min); //displaying the Smallest number
printf("Largest Number: %d\n", max); //displaying the Largest Number
return(0);
}
//Function to find smallest and largest number in file
void findMinMax(FILE *fp, int* min, int* max){
int num;
fscanf(fp, "%d", &num); //Reading the first number from file
*min = num; //set the number as min and max
*max = num;
while (fscanf(fp, "%d", &num) == 1) //Reading the remaining numnbers line by line
{
if (num < *min) //If num read is less than current min, set num as min
*min = num;
if (num > *max) //If num read is greater than current max, set num as max
*max = num;
}
}
INPUT FILE (numbers.txt):
OUTPUT: