# Very Simple C Program

• 11-01-2002
jennydarma
Very Simple C Program
Hi

I know this is really simple but i've been stuck trying to work this out for a couple of days now.

I need to write a simple c program in which you can enter three numbers, in any order, and the resulting output will put them in ascending order.

I think IF statements or arrays might be needed???

If any one can give me a hand i'd really appreciate it.
• 11-01-2002
damonbrinkley
Post the code you have so far and then someone can probably nudge you in the right direction.
• 11-01-2002
Morgan
Here you go...
Code:

```#include <stdio.h> #define RANGE 3 int main(         int argc,         int *argv[]         ) {   int numbers[RANGE], ctr, a, b; /* ** Read in the numbers ( limit set using RANGE definition above ) */   for( ctr=0 ; ctr < RANGE ; ctr++ )   {     printf( "\nEnter next number: " );     /** You would normally check for non integers **/     /** before this next statement **/     scanf( "%d", &numbers[ctr] );   } /* ** Sort the array */   for( ctr=0 ; ctr < RANGE ; ctr++ )   {     if( numbers[ctr] < numbers[ctr+1] )     {       /** If the current number is less than the next number, **/       /** swap them round and start again **/       /** I think this is known as a bubble sort **/       a = numbers[ctr];       b = numbers[ctr+1];       numbers[ctr] = b;       numbers[ctr+1] = a;       ctr = -1; /** Effectively restarts loop **/                 /** ( -1 because loop executes ctr++ ) **/     }   } /* ** Print array */   printf( "\nNumbers in sorted order:\n\n" );   for( ctr=0 ; ctr < RANGE ; ctr++ )   {     printf( "%d\n", numbers[ctr] );   }   printf( "\n" );   return( 0 ); }```

&#91;code]&#91;/code]tagged by Salem
• 11-01-2002
Hammer
>>I think this is known as a bubble sort
It is, but you've implemented it incorrectly, and caused a nasty little bug ;)

The problem is here:
>>for( ctr=0 ; ctr < RANGE ; ctr++ )
>>if( numbers[ctr] < numbers[ctr+1] )
Assuming RANGE is 3:
when ctr is 2, the if statement will check numbers[2] against numbers[3]. See the problem? I'll leave that one for you to ponder over.... :)
• 11-01-2002
datainjector
Yeah as hammer said its bubble sort try this
Code:

```void sort( char s [] ) {         int cnt_main, cnt_sub;         int hold;           hold =0;                   for ( cnt_main =0; cnt_main <= SIZEofarray-1; cnt_main++)                         for( cnt_sub = 0; cnt_sub <= SIZEofarray-2;cnt_sub++ )                                   if ( s[i] > s[i+1] ){                                           hold = s[i];                                           s[i] = s[i+1];                                           s[i+1] = hold;                                   } }```
Ahh well if u guys do find a mistake or anything well i am alil tipsy at the movement ...ahh well just rty it ... or u can try quit sort which is faster than bubble..