1

I'm having a novice problem with my program here....

I want it to print a list of cities in both ascending and descending order, so far i'm only getting the descending part implemented.

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

int main(void) {
  int i, j, ch, sort=0;
  printf("HOW WOULD YOU LIKE TO SORT?\n\nASCENDING\n\nDESCENDING\n\n");
  ch=getc(stdin);
  if(toupper(ch)=='A'&&tolower(ch)=='a') sort=1;
  if(sort==1) printf("\nSORT ASCENDING...\n");
  else printf("\nSORT DESCENDING...\n");
  printf("\nHOW MANY CITIES WOULD YOU LIKE? : - \n");
  scanf("%d",&i);
  char NAMES[i][20];
  j=0;
  while(j<i) {
    printf("ENTER NAME ");
    scanf("%s",NAMES[j]);
    j++;
  }
  char swapNAME[20];
  int r,k;
  printf("THE ORIGINAL LIST WAS :\n");
  for(r=0;r<i;r++) printf("%s\n",NAMES[r]);
  for(r=0;r<i-1;r++) {
    for(k=r+1;k<i;k++) {
      if(strcmp(NAMES[k],NAMES[r])>0) {
         strcpy(swapNAME,NAMES[r]);
         strcpy(NAMES[r],NAMES[k]);
         strcpy(NAMES[k],swapNAME);
      }
    }
  }
  printf("\n THE SORTED LIST IS NOW : \n");
  for(r=0;r<i;r++) printf("%s\n",NAMES[r]);
  getc(stdin);

  system("pause");
  return 0;
}

please any efforts made will greatly be appreciated aganin thankz

2
  • 7
    What is the exact problem? Are you getting an error? On which line of code? Commented Mar 27, 2011 at 14:22
  • 2
    An aesthetic and moot point, but do you really need to print in all caps? Commented Mar 27, 2011 at 14:33

2 Answers 2

2

If the descending sort is working, then all you need is an extra condition in the if statement to handle the other direction:

 for(r=0;r<i-1;r++) {
    for(k=r+1;k<i;k++) {
      if((sort==0 && strcmp(NAMES[k],NAMES[r])>0)||
         (sort==1 && strcmp(NAMES[k],NAMES[r])<0)) {
         strcpy(swapNAME,NAMES[r]);
         strcpy(NAMES[r],NAMES[k]);
         strcpy(NAMES[k],swapNAME);
      }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

First, your sorting is off. To fix that problem, just replace your bubble sort with a call to qsort, and that immediately leads to a good way to do your reverse sorting. In particular, try:

int
rstrcmp( const char *s1, const char *s2 )
{
    return -strcmp( s1, s2 );
}


int main( int argc, char **argv ) {
    ...
    int (*compare)(const char *s1, const char *s2 );
    /* Based on user input, set 
    compare = rstrcmp;
    -- or --
    compare = strcmp;
    */
    ...
    qsort( NAMES, i, 20, compare );
    ...

As a recommendation, do not prompt for the sort direction but let the user pass it as a flag in argv.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.