I have written code to sort elements of an array. It works fine but i don't understand why it works. I expected an IndexOutOfBounds error. But nothing of the sort happens. I thought I "had to" use
SIZE - 1 // in the for loops but even SIZE works fine. THAT IS MY PROBLEM
the question in Array index out of bound in C doesn't clearly explain why i get correct results after sorting the array. below is the code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 12 // definition
int main(int argc, char *argv[])
{
int a[ SIZE ] = {12, 9, 10, 7, 6, 8, 5, 1, 3, 2, 4, 11};
int i;
int j;
for( i = 0; i < SIZE; i++ )
{
for ( j = 0; j < SIZE; j++ ) // why not SIZE - 1 ????
{
if( a[j] > a[j + 1])
{
int hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1] = hold;
}
}
}
for( i=0; i < SIZE; i++ )
{
printf( "%4d", a[ i ] );
}
return 0;
}