Sorting of Names in Alphabetic Order in C++

//Sorting of Names in alphabetic Order with UDF
#include<iostream.h>
#include<conio.h>
#include<string.h>

void sortNames(char [][20], int);
void main()
{
char names[100][20];
int n, i;
clrscr();
cout<<"Enter the No. of Names you want to enter : ";
cin>>n;
cin.get();
for(i=0;i<n;i++)
{
cout<<"Enter the name:"<<i+1<<": ";
cin.getline(names[i],20);
}
cout<<"\nThe Names stored in an array are:\n";
for(i=0;i<n;i++)
cout<<names[i]<<endl;

sortNames(names,n);
getch();
}
void sortNames(char str[][20],int r)
{
int i,j;
char tmp[20];
for(i=0;i<r;i++)
{
for(j=i;j<r-1;j++)
{
if(strcmp(str[i],str[j+1])>0)
{
strcpy(tmp,str[i]);
strcpy(str[i],str[j+1]);
strcpy(str[j+1],tmp);
}
}
}
cout<<"\nThe Names stored in an array are:\n";
for(i=0;i<r;i++)
cout<<str[i]<<endl;
}


/*
Output of the Program:

Enter the No. of Names you want to enter : 5
Enter the name:1: Pankaj
Enter the name:2: Mahi
Enter the name:3: Johny
Enter the name:4: Elizabeth
Enter the name:5: Kevin

The Names stored in an array are:
Pankaj
Mahi
Johny
Elizabeth
Kevin

The Names stored in an array are:
Elizabeth
Johny
Kevin
Mahi
Pankaj

*/


No comments

Post your comments

Powered by Blogger.