You will write a program that will scan in and store in an array a specified num
ID: 3673324 • Letter: Y
Question
You will write a program that will scan in and store in an array a specified number of integers ranging between 1 – 10. You can assume that the user will not enter a number less than 1 nor greater than 10. Your program will then count the number of occurrences of each number, store the count in an array and print the number of occurrences of each number.
Lastly, you will create an input.txt file that has first the number of integers that will be entered followed by the appropriate number of integers between 1 and 10.
Compile your program as follows: gcc arrayHW.c –o arrayHW –Wall
Sample output:
csdhcp153:Array yfeaste$ ./array <num.txt
In my list of 50, the number 1 occurred 4 times.
In my list of 50, the number 2 occurred 4 times.
In my list of 50, the number 3 occurred 5 times.
In my list of 50, the number 4 occurred 3 times.
In my list of 50, the number 5 occurred 4 times.
In my list of 50, the number 6 occurred 5 times.
In my list of 50, the number 7 occurred 3 times.
In my list of 50, the number 8 occurred 7 times.
In my list of 50, the number 9 occurred 7 times.
In my list of 50, the number 10 occurred 8 times.
Explanation / Answer
Please find the required code below :
Note : replace the input file location with your input file location, otherwise will get runtime exception.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/example/input.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int size = 0,i;
read = getline(&line, &len, fp);
size = atoi(line);
int n[ 10 ] = {0,0,0,0,0,0,0,0,0,0};
while ((read = getline(&line, &len, fp)) != -1) {
int num = atoi(line);
n[num-1] = n[num-1] + 1;
}
fclose(fp);
for(i=0; i<10; i++) {
printf("In my list of %d, the number %d occurred %d times.",size,i+1,n[i]);
}
if (line)
free(line);
exit(EXIT_SUCCESS);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.