Pages

Saturday, 4 November 2017

2D character array sorting

Q : Write a ‘C’ program to read an array of names and to sort them in alphabetical order.

Solution :

/*==============================
     Girfa Student Help
     Program : Sort 2D  Array    
================================*/
#include<stdio.h>
#include<conio.h>
#define MAX 3
void main()
{
     char ar[MAX][20],ch[20];

     int r,i,j,flag=0;
     clrscr();
     for(r=0;r<MAX;r++)
     {
          printf("Enter Name>> ");
          gets(ar[r]);
     }
     /* Sorting Using Bubble Sort */
     for(r=0;r<MAX-1;r++)
     {
          flag=0;
          for(j=0;j<MAX-r-1;j++)
          {
              if(strcmp(ar[j],ar[j+1])>0)
              {
                   strcpy(ch,ar[j]);
                   strcpy(ar[j],ar[j+1]);
                   strcpy(ar[j+1],ch);
                   flag=1;
              }
          }
          if(flag==0)
              break;
     }
     puts("\n");
     for(r=0;r<MAX;r++)
          puts(ar[r]);
     getch();

}

No comments:

Post a Comment