C program Write a program binning c that asks the user for a
C program.
Write a program binning. c that asks the user for a range of integers of interest, a number of bins, and a set of integer data. The program then partitions the range into equal-sized bins and prints the bin ranges and the numbers of data elements that fall in each. For example, if the range is 10 to 21, there are 3 bins, and the data are 8, 12, 17, 10, and 24, then the bin ranges are 10-13, 14-17, and 18-21, and two element (10, 12) fall in the first bin, one (17) in the second, and none in the third. All user inputs will be integers, separated by spaces. The range provided by the user is valid only if it is entered in increasing order (e.g. 11 14) and can be divided equally between the number of bins (e.g.. there are 4 integers between 11 and 14. inclusive, they can be divided into 1, 2, or 4 bins, but not 3). If the user inputs numbers outside this range, these numbers are not included in any bin count. (-) $ a.out Range: 1 9 Number of bins: 3 Data: 3 6 3 2 9 5 4 The bin are: 1-3: 3 4-6: 3 7-9: 1 (-) $ a.out Range: 2 5 Number of bins: 2 Data: 12345678 The bins are: 2-3: 2 4-5: 2 (-) $ a.out Range: 3 3 Number of bins: 1 Data: -23034 The bins are: 3-3: 2 (-) $ a.out Range: 2 9 Number of bins: 3 Not a valid ranges (-)$ a.out Range: 50 10 Number of bins: 1 Not a valid range ! (-)$Solution
Here is the code for you:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int start, end, numOfBins;
char line[50];
printf(\"Range: \");
scanf(\"%d%d\", &start, &end);
printf(\"Number of bins: \");
scanf(\"%d\", &numOfBins);
if((end - start + 1) % numOfBins != 0 || (end - start + 1) < 0)
{
printf(\"Not a valid range!\ \");
return 0;
}
printf(\"Data: \");
scanf(\"%s\", line);
char *token;
const char ch[1] = \" \";
token = strtok(line, ch);
int array[20], numOfElements = 1;
array[0] = atoi(token);
while(token != NULL)
{
token = strtok(NULL, ch);
array[numOfElements++] = atoi(token);
}
printf(\"The bins are:\ \");
for(int i = 0; i < numOfBins; i++)
{
int first = start + numOfBins * i;
int next = first + numOfBins - 1;
int count = 0;
for(int j = 0; j < numOfElements; j++)
if(array[j] >= first && array[j] <= next)
count++;
printf(\"%d-%d: %d\ \", first, next, count);
}
}
