Ive been asked to write a program that asks the user to input a series of numbers, then reads the numbers back to the user in numerical order. Ive come up with the following code but i get a large negative integer as the sorted output. Can anyone see why?
Code:
#include <stdio.h>
#define k 10 /* used for setting the array size */
int main()
{
int a[k], n, p, j, small_j, smallest;
char proceed='Y';
printf("Program to sort up to %d integer numbers\n\n", k);
while(proceed == 'Y' || proceed == 'y')
{
printf("\nHow many numbers would you like to sort? ");
if(scanf("%d", &n) == 1 && n>0 && n<=k)
{
/* An acceptable value for n was read */
printf("\n\nThe program will sort %d integers\n", n);
/* Read the n values into the array */
printf("\nType in the numbers - integers\n\n");
for(j=0; j<n; j++) scanf("%d", &a[j]);
/* Display the values back to the user */
printf("\n\nThe numbers you have input are\n\n");
for(j=0; j<n; j++) printf("%d ", a[j]);
/* Start the sorting process by swapping each element with the smallest
remaining elements */
/* Use p to count the sorted elements as build them */
/* Note p=k-1 */
for(p=0; p<n-1; p++) /* main loop for sort */
{
/* Find smallest of the remaining n-p unsorted numbers */
/* Start the scan by designating the first of the unsorted elements
as smallest found so far */
smallest = a[p];
small_j = p; /* Note its position */
/* By varying j, scan through the remaining n-p-1 unsorted
elements to see if any is smaller */
for(j=p+1; j<n; j++)
if(a[j] < smallest)
{
smallest = a[j]; /* Update record of smallest element so far */
small_j = j; /* Note its position */
}
/* Scan finished */
/* Enlarge the sorted list and reduce the unsorted list by
swapping the element at position p with the smallest element */
a[small_j] = a[p];
a[p] = smallest;
} /* End of main loop */
/* Sorting process is now complete so now display the sorted values to the user */
printf("\n\nThe sorted numbers are\n\n");
for(j=0; j<n; j++);printf("%d ", a[j]);
}
else printf("\n\nInvalid input\n\n"); /* Unacceptable value was typed when
user was inputting n */
/* Find out if the user wants another sort to be performed */
printf("\n\nWould you like to try to sort another set of numbers?(Y or N) ");
proceed=getchar();
while (proceed !='Y'&&proceed !='y'&&proceed !='n'&&proceed !='N')
proceed=getchar();
}
/*The user no longer wishes to sort numbers so the program can stop*/
printf("\nThis program is now ending\n\n");
return 0;
}