Recall the M&M exercise that we did in the first week of class where everyone gu
ID: 674339 • Letter: R
Question
Recall the M&M exercise that we did in the first week of class where everyone guessed the
number of M&Ms in the jar. In addition to finding the maximum, minimum, and average values
guessed, it is also interesting to see the distribution of the guessed values, In this assignment,
you are asked to write a program that will print a histogram of the values submitted. Please
name your program "histogram.c". Your input file will be named "input.txt". Your output file
should be named "output.txt".
As with the previous homework, a list of everyone's guesses has been stored in a file called
"input.txt". The data in this file is organized as follows:
(1) The first line contains an integer indicating the number of guesses in the file.
(2) Each additional line contains a single guess.
A histogram is a bar chart in which each bar represents a "bin" and the length of the bar indicates
how many elements are in each "bin". For this program, each bin will store the count for ten
numbers; that is, bin #0 will store the number of guesses in the range of 0 to 9 (inclusive), bin #1
will store the number of guesses in the range of 10 to 19, bin #2 will store the number of guesses
in the range of 20-29, etc. You may assume that all guesses will be less than 100 which means
that your histogram will have 10 bins.
Explanation / Answer
This will serve your need.
#include <stdio.h>
int main()
{
FILE *inputFP, *outputFP;
int i, j, numOfGuesses, guessValue, guessesCount[10];
inputFP = fopen("input.txt", "r");
outputFP = fopen("output.txt", "w");
fscanf(inputFP, "%i", &numOfGuesses);
for(i = 0; i < 10; i++)
guessesCount[i] = 0;
for(i = 0; i < numOfGuesses; i++)
{
fscanf(inputFP, "%i", &guessValue);
guessesCount[guessValue / 10]++;
}
for(i = 0; i < 10; i++)
{
fprintf(outputFP, "BIN #%i: ",i);
for(j = 1; j <= guessesCount[i]; j++)
fprintf(outputFP, "*");
fprintf(outputFP, " ");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.