I am a newbie trying to learn C and I need to sort an array using selection sort. I also need to show each iteration as the algorithm progresses. But I cannot seem to make the following code work. It throws up random garbage numbers when executing the showing of the sorting iteration part (please see the picture). I have searched a lot and still can't seem to nail the cause of this error. Please help. Program execution
#include<stdio.h>
int main()
{
int s,i,j,t,temp,a[20];
printf("Enter the number of elements in the array\n");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("Enter element %d\n",i+1);
scanf("%d",&a[i]);
}
printf ("Selection sort.\narray before sorting:\n");
for (i=0;i<s;i++)
printf ("%d ",a[i]);
printf ("\n");
for(i=0;i<s;i++)
{
printf ("After iteration %d\n", i+1);
for(j=i+1;j<s;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for (t=0;t<s;t++);
printf ("%d ",a[t]);
printf ("\n");
}
printf("Array after sorting:\n");
for(i=0;i<s;i++)
printf ("%d ",a[i]);
return 0;
}
Your problem is this line:
for (t=0;t<s;t++);
Having that line end with ;
means that t will count up to s without any work being done and after that loop a single line will be printed with the uninitialized value of a[s]
.