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

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz