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

#include<stdio.h> #include<Windows.h> int main() { int arr[500]; int i = 0; int

ID: 3543772 • Letter: #

Question

#include<stdio.h>

#include<Windows.h>

int main()

{

int arr[500];

int i = 0;

int temp, j;

int value;

int count = 0;

        char c;

        FILE*inFile;

FILE*outFile;

        inFile = fopen("input.txt", "r");

outFile = fopen("output.txt", "w");



//count the number of elements in the text file

while((c = getc(inFile)) != EOF ) {

        if(c == ' ')

{

            count++;

}

}


printf("The number of intergers in the file is:%d ", count);


//FILL array from text file

for (i = 0; i < count; i++)

{

fscanf(inFile, "%d", &arr[i]);

}

//Bubble sort array

for (i = 0 ; i < ( count - 1 ); i++)

{

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

{

if (arr[j] > arr[j+1]) /* For decreasing order use < */

{

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1]= temp;

}

}

}

//print the sorted array

printf("Sorted list in ascending order: ");

for ( i= 0 ; i < count ; i++ )

  {

     printf("%d ", &arr[i]);

fprintf(outFile, "%d", arr[i]);

  }


for some reason this program is printing the memory address instead of the elements, any help would be great.

Explanation / Answer

This is happening because after reading the number of integers in the file you are reaching end of file and are not going back to the beginning of the file. Instead you are trying to read integers after end of file due to which garbage values are getting printed. Just modify the program as follows :


#include<stdio.h>

#include<Windows.h>

int main()

{

int arr[500];

int i = 0;

int temp, j;

int value;

int count = 0;

char c;

FILE*inFile;

FILE*outFile;

inFile = fopen("input.txt", "r");

outFile = fopen("output.txt", "w");



//count the number of elements in the text file

while((c = getc(inFile)) != EOF ) {

if(c == ' ')

{

count++;

}

}


//END OF FILE HAS BEEN REACHED NOW. WE NEED TO GET BACK TO THE BEGINNING OF FILE

//The following line sets the FILE pointer infile to point back to the beginning of the file.

fseek(infile,0,SEEK_SET);


printf("The number of intergers in the file is:%d ", count);


//FILL array from text file

for (i = 0; i < count; i++)

{

fscanf(inFile, "%d", &arr[i]);

}

//Bubble sort array

for (i = 0 ; i < ( count - 1 ); i++)

{

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

{

if (arr[j] > arr[j+1]) /* For decreasing order use < */

{

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1]= temp;

}

}

}

//print the sorted array

printf("Sorted list in ascending order: ");

for ( i= 0 ; i < count ; i++ )

{

printf("%d ", &arr[i]);

fprintf(outFile, "%d", arr[i]);

}

}

//I'm sure this will solve your problem :)