NO

Author Topic: ascending and decending arrays  (Read 2420 times)

sannemander

  • Guest
ascending and decending arrays
« on: November 21, 2011, 11:34:17 AM »
hello!

I am trying to make a code where a user can input numbers and later choose to print them in ascending or descending order, the code compiles fine but I can´t figure out how to print it in order!
I have been looking for hours but found nothing!
thx already, ok, here´s the code:

#include <stdio.h>
#include <stdlib.h>


int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int y;

int main(){

int iArray[9] = {0};   
int iOption = 0;
int iResponse = 0;
int x = 0;

      
      do {


      printf("\nEnter a number: ");
      scanf("%d", &iArray[iResponse]);
        x++;
      


   } while ( x < 10 );

    system("cls");
   printf("\tCHOOSE OPTIONS\n");
   printf("\n1\tDisplay the numbers from low to high\n");
   printf("\n2\tDisplay the numbers from high to low\n");
   printf("\nChoose your option: ");
   scanf("%d", &iOption);


switch (iOption){


         case 1:   
         
         
         
       
         system("cls");
            qsort(iArray, 10, sizeof(int), compare);
      
         for(y = 0; y < 10; y++)   {
         
            printf("\n%d\n", iArray[y]);
           }
            
            break;
       
         

         

   case 2:
       
          
           
           system("cls");
            qsort(iArray, 10, sizeof(int), compare);
            
         for (y = 10; y  > 0; y--){
            
            printf("\n%d\n", iArray[y]);
          }
            
            break;
         
           
      

   }//end switch   
 
   return 0;      
      


}//end main function

CommonTater

  • Guest
Re: ascending and decending arrays
« Reply #1 on: November 21, 2011, 12:22:01 PM »
First... your array should be... iArray[10]... each of your loops will go 1 element out of bounds with 9.

Your printing code seens to work... the "gold standard" for listing arrays is a simple for loop...
Code: [Select]
for (int x = 0; x < SIZE; x++)
  printf("%d\t", iArray[x];
Which is what you have...

Your entry loop, however is flawed...
Code: [Select]
do
   {
      printf("\nEnter a number: ");
      scanf("%d", &iArray[iResponse]);  <--- should be &iArray[x];
        x++;
   }
while ( x < 10 );
You never increment iResponse so everything will go into array slot 0.  If you work on the loop iterator instead, you will fill slots successively and you can dispose of the iResponse variable entirely.




sannemander

  • Guest
Re: ascending and decending arrays
« Reply #2 on: November 21, 2011, 01:14:28 PM »
THX gonna work on it!!!!