Programming Examples
Cpp program to input 5 cities name and sort in alphabetical order
Write a cpp program to input 5 cities and sort in alphabetical order
Solution
#include <iostream>
#include <cstring> // Include the <cstring> header for strlen
using namespace std;
int main()
{
char city[5][10], ch;
int length, max = 0;
int a, b;
char temp[10];
cout << "Enter the cities" << endl;
for (a = 0; a < 5; a++)
{
cin.getline(city[a], 10);
}
for (a = 0; a < 5; a++)
{
for (b = 0; b < 4 - a; b++)
{
int result = strcmp(city[b], city[b + 1]);
if (result > 0)
{
// temp = city[b]; // str1 is lexicographically greater than str2
strcpy(temp, city[b]);
// strcpy(city[b + 1],city[b]);// strcpy(destination, source)
strcpy(city[b], city[b+1]); // strcpy(destination, source)
strcpy(city[b + 1], temp);
// city[b + 1]=temp;
// swap(city[b+1],temp);
}
/* else if (result < 0)
{
//cout << city[a + 1];
}
else if(result<0)
{
//cout << "Strings are equal";
}*/
}
}
cout << "Sorted cities in alphabetical order:" << endl;
for (int a = 0; a < 5; a++)
{
cout << city[a] << endl;
}
return 0;
}
Output
Enter the cities
kanpur
allahabad
agra
delhi
mumbai
Sorted cities in alphabetical order:
agra
allahabad
delhi
kanpur
mumbai