Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program in c Given an integer array that uses a sentinel value to indicate the e

ID: 3831846 • Letter: P

Question

Program in c

Given an integer array that uses a sentinel value to indicate the end of values, and can contain anywhere from 10 to 10,000,000 values, such as

short quartile[ ] = { 1, 3, 2, 4, 1, 3, 1, 4, 1, 4, 4, 1, 1, 1, 4, 2, 4, 1, 1, 4, 1, 3, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 4, 1, 1, 4, 1, 2, 5, 1, 1, 0 };

Write a complete function to read in numbers from a file named "datain.txt" and compare each number in quartile against the corresponding number read in. That is, is the first number in quartile equal the first number in "datain.txt"? Continue to the second number, and so on. Count the number of times the numbers are the same and return that value:

printf( "The number of matches is %d. ", compareWithFile( quartile, "datain.txt" ) );

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>

int compareWithFile(short quartile[], char filename[100])
{
FILE *fp = fopen(filename, "r");
int count = 0;
int i = 0;
int num;
while(fscanf(fp, "%d", &num) != 0)
{
if(quartile[i] == 0)
{
break;
}
if(quartile[i] == num)
{
count++;
}
i++;
}
return count;
}

int main()
{
short quartile[ ] = { 1, 3, 2, 4, 1, 3, 1, 4, 1, 4, 4, 1, 1, 1, 4, 2, 4, 1, 1, 4, 1, 3, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 4, 1, 1, 4, 1, 2, 5, 1, 1, 0 };

printf( "The number of matches is %d. ", compareWithFile( quartile, "datain.txt" ) );
  
return 0;
}