8.DS - Lab - C Program to read the names of cities and arrange them alphabetically

 8.C Program to read the names of cities and arrange them alphabetically

ALGORITHM :
Step 1: Start
Step 2: Input the number of cities (num_cities).
Step 3: Create an empty list (cities_list) to store the city names.
Step 4: For each city, input its name and append it to the cities_list.
Step 5: Sort the cities_list in alphabetical order.
Step 6: Display the sorted cities_list.
Step 7: End

SOURCE CODE :

#include <stdio.h>
#include <string.h>

#define MAX_CITY_LENGTH 50
#define MAX_CITIES 10

void sortCities(char cities[MAX_CITIES][MAX_CITY_LENGTH], int n) {
    char temp[MAX_CITY_LENGTH];
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (strcmp(cities[i], cities[j]) > 0) {
                strcpy(temp, cities[i]);
                strcpy(cities[i], cities[j]);
                strcpy(cities[j], temp);
            }
        }
    }
}

int main() {
    int n;
    printf("Enter the number of cities: ");
    scanf("%d", &n);

    char cities[MAX_CITIES][MAX_CITY_LENGTH];

    for (int i = 0; i < n; i++) {
        printf("Enter city %d: ", i + 1);
        scanf("%s", cities[i]);
    }

    sortCities(cities, n);

    printf("\nCities in alphabetical order:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", cities[i]);
    }

    return 0;
}

OUTPUT : 

Enter the number of cities: 5
Enter city 1: London
Enter city 2: Paris
Enter city 3: New York
Enter city 4: Tokyo
Enter city 5: Sydney

Cities in alphabetical order:
London
New York
Paris
Sydney
Tokyo



No comments:

Post a Comment