In: Computer Science
C Language
NO ARRAY UTILIZATION OR SORTING
Create a .txt file with 20 integers in the range of 0 to
100. There may be repeats. The numbers must
not be ordered/sorted. The task is to find and print the two
smallest numbers. You must accomplish
this task without sorting the file and without using arrays for any
purpose.
It is possible that the smallest numbers are repeated – you
should print the number of occurrences of
the two smallest numbers.
The reading of the numbers, the comparisons, the printing
of the smallest numbers should all be in
separate functions. You MUST employ PASS BY REFRENCE for this
problem. The counting of the two
smallest numbers occurrences functionality must be implemented with
static counter.
Program Code Screenshot
Program Sample Console Input/Output Screenshot
Program Code to Copy
#include <stdlib.h>
#include <stdio.h>
void updateMinimum(int value, int *min1, int *min2, int *min1_count, int *min2_count)
{
//update count if this is a repeated element
if (*min1 == value)
{
(*min1_count)++;
return;
}
else if (*min2 == value)
{
(*min2_count)++;
}
//initialize element if its the first element being read
else if (*min1_count == 0)
{
*min1 = value;
*min1_count = 1;
}
else if (*min2_count == 0)
{
//make sure the min1 is less than min2 always
if (*min1 < value)
{
*min2 = value;
*min2_count = 1;
}
else
{
*min2 = *min1;
*min2_count = *min1_count;
*min1 = value;
*min1_count = 1;
}
}
else
{
//update values on min1 and min2
if (value < *min1)
{
*min2_count = *min1_count;
*min2 = *min1;
*min1_count = 1;
*min1 = value;
}
else if (value < *min2)
{
*min2_count = 1;
*min2 = value;
}
}
}
int read_num(FILE *file)
{
int val;
fscanf(file, "%d", &val);
return val;
}
void print_result(int min1, int min2, int min1_count, int min2_count)
{
//print theṇ results
printf("Minimum element 1: %d occured %d times\n", min1, min1_count);
printf("Minimum element 2: %d occured %d times\n", min2, min2_count);
}
int main(int argc, char *argv[])
{
//declare variable to read from file
FILE *file = fopen("input.txt", "r");
//declare variable to read integers
int val;
//declare static counter variables to store two minimum numbers
//and there count
static int min1 = 101, min2 = 101;
int min1_count = 0, min2_count = 0;
//read 20 integers from the file
for (int i = 0; i < 20; i++)
{
int val = read_num(file); //separate function to read file
//passing variables by reference
updateMinimum(val, &min1, &min2, &min1_count, &min2_count); //separate function for comparisions
}
//separate function to print result
print_result(min1, min2, min1_count, min2_count);
}