I'm working on the following homework question:
Build a program that uses a single-dimension array to store 10 numbers input by a user. After inputting the numbers, the user should see a menu with two options to sort and print the 10 numbers in ascending or descending order.
I'm running into some puzzling issues.
My code is posted below. I've managed to accept user input for the array's elements, and I found code for sorting an integer array here: http://www.java-samples.com/showtutorial.php?tutorialid=1577
The code in that tutorial works just fine, but as soon as I add in my code for user specified elements in the array instead of just initializing the array myself, I get a segmentation fault: core dumped error upon running the program. It'll work until it hits the sorting programming, then crashes. No errors upon compiling in gcc.
#include<stdio.h>
#include<stdbool.h>
main()
{
int temporaryStorage;
int counter;
int numArray[] = {0};
int i = 0;
bool sortExists = true;
for (i = 0; i < 10; ++i)
{
fprintf(stdout, "Enter element[%d]->", i);
fscanf(stdin, "%d", &numArray[i]);
}
printf("Array Before Sorting\n");
for(counter = 0; counter < 10; ++counter){
printf("%d ", numArray[counter]);
}
while (sortExists == true)
{
sortExists = false;
for (counter = 0; counter < 9; ++counter)
{
if (numArray[counter] > numArray[counter + 1])
{
temporaryStorage = numArray[counter];
numArray[counter] = numArray[counter + 1];
numArray[counter + 1] = temporaryStorage;
sortExists = true;
}
}
}
printf("\n\nArray After Sorting – Ascending Order\n");
for(counter = 0; counter < 10; ++counter){
printf("%d ", numArray[counter]);
}
}