0

I have to create a program that finds the k largest elements of a file and stores them in a array size k. It is supposed to read each next element in a file and insert it in the sorted array only if it belongs. I cannot figure out what i am doing wrong. I am reading from a file which contains about 100 numbers. The array is supposed to print out 996 980 956 932 929 in the end but it is printing 386 915 886 793 996. Here is my code:

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

int main(int argc, char *argv[]){
FILE *file;
int i,j, n, temp; 
printf("Enter number of max elements to find:\n");
n = atoi(argv[2]);
int maxnumbers[n];
file = fopen(argv[1], "r");
for(i = 0; i < n; i++)
  fscanf(file, "%d", &maxnumbers[i]); 

for (i=0; i<n-1; i++)
{
  for (j = 0; j< n-1-i; j++)

    if (maxnumbers[j] < maxnumbers[j+1])
    {
    temp = maxnumbers[j];
    maxnumbers[j] = maxnumbers[j+1];
    maxnumbers[j+1] = temp;
    }
}
for (i = 0; i<n; i++)
 printf("%d\n", maxnumbers[i]);

while (!feof(file))
{
temp = maxnumbers[n-1];
j = n-1;
fscanf(file,"%d",&i);
 if (i > temp)
 {
  while(i >=  maxnumbers[j-1])
  {
    maxnumbers[j] = maxnumbers[j-1];
    j = j-1;
  }
 maxnumbers[j] = i;
 }

}
fclose(file);
for (i = 0; i<n; i++)
 printf("%d\n", maxnumbers[i]);
return 0;
}
cstudent
  • 1
  • 1
  • it would be helpful to post what is wrong with your code (i.e., what you were expecting, and what you are getting) – Tommy Mar 07 '17 at 02:45
  • 1
    @cstudent what is the current behaviour of the code – Sarath Sadasivan Pillai Mar 07 '17 at 02:45
  • `while(i >= maxnumbers[j-1])` is wrong. if `i >= maxnumbers[0]`, occurs out of bounds at next loop. – BLUEPIXY Mar 07 '17 at 03:05
  • @BLUEPIXY Thank you!! I changed that statement to while((i >= maxnumbers[j-1]) && (j-1 >= 0) ) and it seems to be working now! – cstudent Mar 07 '17 at 03:27
  • `(i >= maxnumbers[j-1]) && (j-1 >= 0)` --> `(j-1 >= 0 && i >= maxnumbers[j-1])` Since `i >= maxnumbers[j-1]` may cause an access violation, it is necessary to first check the index. – BLUEPIXY Mar 07 '17 at 03:35
  • 1
    Read [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – BLUEPIXY Mar 07 '17 at 03:44
  • @BLUEPIXY wow thanks for the help. I did not know that that order would matter.what would be the correct way to read the file in this situation? – cstudent Mar 07 '17 at 03:52
  • `EOF` occurs at `fscanf(file,"%d",&i);`. So Check return value of `fscanf` like `if(EOF == fscanf(file,"%d",&i)) break;/* occurs EOF*/` or `if(1 != fscanf(file,"%d", &i)) break;/* could not read it.*/` – BLUEPIXY Mar 07 '17 at 04:59

0 Answers0