Sort an array of user input names alphabetically ascending and descending in c -
i new c , have assignment class. need //build program uses single-dimension array store 10 names input user. //after inputting names, user should see menu 2 options sort , print 10 names in ascending or descending order.
so far here
`
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char names[10][10]; char temp[10],i,j; int count; int sort; count=1; ((i=0);i<10;i++) { while (count<11) { printf("please enter name %i\n",count); scanf("%s",names); count=count+1; } } printf("would print in ascending (press 1) or descending (press 2) order?\n\n"); scanf("%d",&sort); switch (sort) { case 1: printf("\n ascending order:\n "); printf("%s\n",names); qsort(temp, 10, 10, names); break; default: case 2: printf("\n descending order:\n "); printf("%s\n",names); break; } return 0;
i need figuring out how make sort.
firstm there bugs:
1、you can't store 10 person names in 1 single-dimension array, need 2d array, char names[10][10]
.
2、when use function qsort
, fourth parameter function pointer int (*cmp)(const void*, const void*)
.
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp1(const void* l, const void* r) { return strcmp((char*)l , (char*) r); } int cmp2(const void* l, const void* r) { return -strcmp((char*)l , (char*) r); } int main() { char names[10][10] = {0}; char temp[10]; int count; int sort; count=1; (int i=0;i<10;i++) { printf("please enter name %i\n",i+1); scanf("%s",names[i]); } printf("would print in ascending (press 1) or descending (press 2) order?\n\n"); scanf("%d",&sort); switch (sort) { case 1: printf("\n ascending order:\n "); qsort(names, 10, 10, cmp1); break; case 2: printf("\n descending order:\n "); qsort(names, 10, 10, cmp2); break; } (int = 0; < 10; ++) { printf("%s\n", names[i]); } return 0; }
Comments
Post a Comment