2

This C code is supposed to create some random numbers and print them and then sort them and print them again, but it just prints the sorted numbers. Could any body help me?

    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    int main(){
        int i, j, k;
        float temper;
        time_t t;
        float grades[1000];
        fflush(stdout);
        printf("Here are the number\n");
        srand(time(&t));
        for(i=0;i<1000;i++){
            grades[i]=rand();
            printf("%f\n", grades[i]);
        }
        for(i=0;i<1000;i++){
            int swap=0;
            for(j=i;j<1000;j++){
                if(grades[i]>grades[j]){
                    temper=grades[i];
                    grades[i]=grades[j];
                    grades[j]=temper;
                    swap=1;
                }
            }
        }
        printf("sorting is done");
        for(i=0;i<1000;i++){
            printf("%f\n", grades[i]);
        } }
3
  • Works as expected for me. It prints the numbers as they're randomly generated, then prints the sorted list. Can you post a sample run, preferably with a smaller amount of numbers, say 10 or so?
    – dbush
    Commented Oct 22, 2015 at 2:44
  • It is working here as well!!!!
    – user4580220
    Commented Oct 22, 2015 at 2:50
  • 1
    The title of this question is misleading. Perhaps it should be edited to "Unexpected missing output from printf"? Commented Oct 22, 2015 at 3:29

3 Answers 3

5

Your program is working correctly. Try changing everything from 1000 to 10 just to test and see for yourself.

What is happening is that it is printing everything out so quickly that the first 1000 is off the page.

0
1

The code is correct.

  1. Try a small size to array,
  2. write all the logs to a file.
1

Code worked fine for me too. Maybe your terminal is not storing enough lines for you to see the beginning of the output. You can change that in the settings for your terminal. Or you can cat them to a file instead. There is an easy option to do so if you google it. Also, add in another printf in between as a marker that is obvious like:

printf("+++++++++++++++++++++++++++ here is the break point ++++++++++++++++");

It will make it that much harder to miss it. Good luck!

PS: to cat your output to a file simply type '> filename' when running the program. I called mine math.c so when I ran I typed: '$./math > file' And the whole output in in a file named 'file'

1
  • I called my program math.c and compiled as $gcc math.c -o math and then to run and cat to a file I did $./math > file
    – JParks
    Commented Oct 22, 2015 at 3:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.