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

Help with C please, file name is klargest.txt and please use argc and argv many

ID: 3827063 • Letter: H

Question

Help with C please,

file name is klargest.txt and please use argc and argv many Thanks

(100 pts) Write a program to find the k largest elements of a file. Allocate an array of size k and while you read the numbers from the file, store the k largest numbers in the array. When you read the next element from the file, find if the array needs to be modified or not. Consider the below figure as an example. Assume that next element read is 80. Since 80 is larger than the smallest element, we need to shift elements 80 to the right by 1 position and create space for 80. We then insert 80 into the new position. 97 83 76 65 54 2 76 65 97 83 2 97 83 80 76 65 Figure 1: Insert 80 into 5 largest elements n main. use argc and argu to read the filename and k om the user and compute and print the k largest elements. Name your program assign4.c Sample execution of the program is given below. First parameter is filename and second parameter is k. You need to use atoi() in stdlib.h to convert strings to integer. foxx 013 assign4 a.txt 5 996 980 956 932 929

Explanation / Answer

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

int main(int argc,char** argv)
{
    if(argc<3){
        printf("Invalid input ");
        return 1;
    }
    int k = atoi(argv[2]);
  
    int MaxValues[k];
    int i =0;
  
    FILE *myFile;
    myFile = fopen(argv[1], "r");
    if (myFile == NULL)
    {
        printf("Error Reading File ");
        exit (0);
    }
    i = 0;
    for(i=0;i<k;i++){
        MaxValues[i]=0;
    }
    i = 0;
    do{
        int value;
        if( fscanf(myFile, "%d,", &value ) ==1){
            int min = MaxValues[0];
            int j=0;
            if(value>min){
                MaxValues[j] = value;
                for(j=0;j<k-1;j++){
                    if(value> MaxValues[j+1])
                    {
                         MaxValues[j] = MaxValues[j+1];
                         MaxValues[j+1] = value;
                    }
                }
            }
            continue;
        }
        break;
    }while(!feof(myFile));
  
    printf("RESULT : ");
    for(i=0;i<k;i++){
        printf(" < %d ",MaxValues[i]);
    }
    printf(" ");
    fclose(myFile);

    return 0;
}

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