Programming Tutorials

Sorting an array of Strings in C++

By: Ignatius in C++ Tutorials on 2012-03-16  

This simple C++ program sorts the elements of an integer array and prints them.

#include <iostream>
using namespace std;
#include <cstring>
int main()
       // declare two arrays named tname with 1-Dimension
       // and name with 2-Dimension
       char  tname[20], name[20][20];
       // normal variables...
       int   i, j, n;
       cout<<"Enter the number of names:  ";
       // outer loop for counter...
       for(i=0; i<n; i++)
              cout<<"\nEnter the name(one word) "<<(i+1)<<": ";
       // inner for loop, read row by row set outer for loop...
       for(i=0; i<n-1; i++)
       // innermost for loop, read column by column of the characters...
       for(j = i+1; j<n; j++)
       // set the condition...
       // strcmp - compare the string standard library function
       // do the sorting...
       if(strcmp(name[i], name[j])>0)
              // strcpy - copy the strings...
              // compare and swap...
              strcpy(tname, name[i]);
              strcpy(name[i], name[j]);
              strcpy(name[j], tname);
       cout<<"\nSorted names:\n";
       for (i =0; i<n; i++)
       return 0;

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)