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

Write down a program in C that should do the following: Accept a user input for

ID: 3820481 • Letter: W

Question

Write down a program in C that should do the following: Accept a user input for the size of data 'n' from the user. Randomly generate 'n' integers in the range 0 to 9. Save the randomly generated integers in a file called 'data.txt'. Read the input file 'data.txt' and generate the frequency count of the integers in this file. Frequency count means the number of occurrences of each integer in the data. Create a new file 'output.txt'. In this file write down the result of frequency count from step 4. Make use of the frequency count in step 4 to sort the data in the file 'data.txt' in ascending order. Write down the sorted data in the output file output.txt after the frequency count. if you generated the following data: 2, 8, 9, 2, 7, 6, 5, 2, 9, 3, 3, 2, 5, then the data.txt file should have frequency count like: Sorted data: 2, 2, 2, 2, 3, 3, 5, 5, 6, 7, 8, 9, 9

Explanation / Answer

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

int main()
{
int i, n,num;
time_t t;

/* Intializes random number generator */
srand((unsigned) time(&t));   

printf("Enter size of data:");
scanf("%d",&n);


// initilize the freq array with zero
int freq[9]={0};

FILE *fileptr;
fileptr = fopen("data.txt","w");

if(fileptr == NULL)
{
printf("Open Error!");   
exit(1);   
}

/* Print random numbers from 0 to 9 to data.txt */
for( i = 0 ; i < n ; i++ )
{
fprintf(fileptr,"%d ", rand() % 10);
}
fclose(fileptr);


if ((fileptr = fopen("data.txt","r")) == NULL){
printf("Open Error! opening file");
exit(1);
}

/* Read numbers from data.txt and store in frequency array */
for(i=0;i<n;i++){

fscanf(fileptr,"%d", &num);
  
freq[num] += 1;

}
fclose(fileptr);

fileptr = fopen("data.txt","w");
if(fileptr == NULL)
{
printf("Open Error!");   
exit(1);   
}

/* Write frequency to data.txt file */
fprintf(fileptr,"Integer Count ");
for(i=0;i<10;i++){
fprintf(fileptr,"%d %d ",i,freq[i]);
}
fclose(fileptr);

fileptr = fopen("output.txt","w");
if(fileptr == NULL)
{
printf("Open Error!");   
exit(1);   
}

/* write sorted order to output.txt file */
fprintf(fileptr,"Sorted Data: ");
for(i=0;i<10;i++){
while(freq[i]>0){
fprintf(fileptr,"%d,",i);
freq[i] -= 1;
}
}
fclose(fileptr);
return(0);
}

/*

Sample output

data.txt

Integer   Count
0       0
1       1
2       3
3       0
4       1
5       2
6       1
7       1
8       0
9       1

Output.txt

Sorted Data: 1,2,2,2,4,5,5,6,7,9,

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote