Sorting an array of Strings in C++
By: Ignatius
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: ";
cin>>n;
// outer loop for counter...
for(i=0; i<n; i++)
{
cout<<"\nEnter the name(one word) "<<(i+1)<<": ";
cin>>name[i];
}
// 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++)
cout<<"\n"<<name[i];
cout<<endl;
return 0;
}
Archived Comments
1. Thanks so much useful to me.
View Tutorial By: Bhuvan at 2012-05-31 14:57:57
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++