Cities Database - C# Programming Exercise

In this exercise, you are asked to create a database to store information about cities.

In the first approach, you will store only the name of each city and the number of inhabitants, with space allocated for up to 500 cities.

The menu should include the following options:

1 .- Add a new city (at the end of the existing data)
2 .- View all cities (name and inhabitants)
3 .- Modify a record (rename and/or change the number of inhabitants)
4 .- Insert a new record (at a specified position, moving the following ones to the right)
5 .- Delete a record (moving the following ones to the left so no empty spaces remain)
6 .- Search in the records (display those that contain certain text in their name, regardless of case, using partial search)
7 .- Correct the capitalization of the names (turn the first letter and those after spaces to uppercase, and the rest to lowercase)
0 .- Exit

This exercise will allow you to practice creating and manipulating records in a simple database, as well as implementing an interactive menu to perform operations on the data.

 Category

Arrays, Structures and Strings

 Exercise

Cities Database

 Objective

Create a database to store information about cities.

In a first approach, we will store only the name of each city and the number of inhabitants, and allocate space for up to 500 cities.

The menu should include the following options:
1 .- Add a new city (at the end of the existing data)
2 .- View all cities (name and inhabitants)
3 .- Modify a record (rename and / or change number of inhabitants)
4 .- Insert a new record (in a specified position, moving the following ones to the right)
5 .- Delete a record (moving the following ones to the left so that no empty spaces are left)
6 .- Search in the records (display the ones which contain a certain text in their name, whether in upper or lower case, using partial search)
7 .- Correct the capitalization of the names (turn into uppercase the first letter and the ones after a space, and make the rest lowercase).
0 .- Exit

 Write Your C# Exercise

using System;  // Import the System namespace for basic functionality
using System.Linq;  // Import LINQ to use string manipulation and search functionality

class Program  // Define the main class
{
    // Define the structure for a city
    struct City
    {
        public string Name;  // Name of the city
        public int Inhabitants;  // Number of inhabitants
    }

    static void Main()  // The entry point of the program
    {
        City[] cities = new City[500];  // Array to store up to 500 cities
        int currentCityCount = 0;  // Counter to keep track of the current number of cities

        while (true)  // Infinite loop to display the menu repeatedly
        {
            // Display the menu options
            Console.Clear();
            Console.WriteLine("1. Add a new city");
            Console.WriteLine("2. View all cities");
            Console.WriteLine("3. Modify a record");
            Console.WriteLine("4. Insert a new record");
            Console.WriteLine("5. Delete a record");
            Console.WriteLine("6. Search in the records");
            Console.WriteLine("7. Correct the capitalization of the names");
            Console.WriteLine("0. Exit");
            Console.Write("Select an option: ");
            string choice = Console.ReadLine();  // Read the user's choice

            // Perform actions based on the user's choice
            switch (choice)
            {
                case "1":  // Add a new city
                    if (currentCityCount < 500)  // Check if there is space for more cities
                    {
                        Console.Write("Enter the city name: ");
                        string name = Console.ReadLine();
                        Console.Write("Enter the number of inhabitants: ");
                        int inhabitants = int.Parse(Console.ReadLine());
                        cities[currentCityCount] = new City { Name = name, Inhabitants = inhabitants };  // Add the city to the array
                        currentCityCount++;
                        Console.WriteLine("City added successfully!");
                    }
                    else
                    {
                        Console.WriteLine("Database is full!");
                    }
                    break;

                case "2":  // View all cities
                    Console.WriteLine("Cities:");
                    for (int i = 0; i < currentCityCount; i++)
                    {
                        Console.WriteLine($"{cities[i].Name} - {cities[i].Inhabitants} inhabitants");
                    }
                    break;

                case "3":  // Modify a record
                    Console.Write("Enter the name of the city to modify: ");
                    string cityToModify = Console.ReadLine();
                    bool found = false;

                    for (int i = 0; i < currentCityCount; i++)
                    {
                        if (cities[i].Name.Equals(cityToModify, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            Console.Write("Enter the new name: ");
                            cities[i].Name = Console.ReadLine();
                            Console.Write("Enter the new number of inhabitants: ");
                            cities[i].Inhabitants = int.Parse(Console.ReadLine());
                            Console.WriteLine("City updated successfully!");
                            break;
                        }
                    }

                    if (!found) Console.WriteLine("City not found!");
                    break;

                case "4":  // Insert a new record
                    Console.Write("Enter the position to insert at (1 to {0}): ", currentCityCount + 1);
                    int position = int.Parse(Console.ReadLine()) - 1;
                    if (position >= 0 && position <= currentCityCount)
                    {
                        Console.Write("Enter the city name: ");
                        string cityName = Console.ReadLine();
                        Console.Write("Enter the number of inhabitants: ");
                        int cityInhabitants = int.Parse(Console.ReadLine());

                        for (int i = currentCityCount; i > position; i--)
                        {
                            cities[i] = cities[i - 1];  // Move cities to the right
                        }

                        cities[position] = new City { Name = cityName, Inhabitants = cityInhabitants };
                        currentCityCount++;
                        Console.WriteLine("City inserted successfully!");
                    }
                    else
                    {
                        Console.WriteLine("Invalid position!");
                    }
                    break;

                case "5":  // Delete a record
                    Console.Write("Enter the name of the city to delete: ");
                    string cityToDelete = Console.ReadLine();
                    found = false;

                    for (int i = 0; i < currentCityCount; i++)
                    {
                        if (cities[i].Name.Equals(cityToDelete, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            for (int j = i; j < currentCityCount - 1; j++)
                            {
                                cities[j] = cities[j + 1];  // Shift cities to the left
                            }
                            currentCityCount--;
                            Console.WriteLine("City deleted successfully!");
                            break;
                        }
                    }

                    if (!found) Console.WriteLine("City not found!");
                    break;

                case "6":  // Search in the records
                    Console.Write("Enter the text to search for: ");
                    string searchText = Console.ReadLine().ToLower();  // Make the search case-insensitive

                    Console.WriteLine("Search results:");
                    bool foundSearch = false;
                    for (int i = 0; i < currentCityCount; i++)
                    {
                        if (cities[i].Name.ToLower().Contains(searchText))  // Partial search
                        {
                            Console.WriteLine($"{cities[i].Name} - {cities[i].Inhabitants} inhabitants");
                            foundSearch = true;
                        }
                    }

                    if (!foundSearch) Console.WriteLine("No cities found matching the search criteria.");
                    break;

                case "7":  // Correct the capitalization of the names
                    for (int i = 0; i < currentCityCount; i++)
                    {
                        cities[i].Name = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(cities[i].Name.ToLower());
                    }
                    Console.WriteLine("Capitalization corrected for all city names.");
                    break;

                case "0":  // Exit the program
                    Console.WriteLine("Exiting program...");
                    return;

                default:
                    Console.WriteLine("Invalid option! Please try again.");
                    break;
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();  // Wait for user input before continuing
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of Arrays, Structures and Strings

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Banner

    This Exercise in C# involves creating a program that imitates the basic Unix SysV "banner" utility, allowing you to display large texts in a similar manner. The purpo...

  •  Triangle right side

    This Exercise in C# involves creating a program that asks the user for a text string and displays a right-aligned triangle using that string. The triang...

  •  Strings manipulation

    This Exercise in C# involves creating a program that asks the user for a text string and performs three specific transformations on it. The program must...

  •  Nested structs

    This Exercise in C# involves creating a struct to store two pieces of data for a person: their name and their date of birth. The date of birth...

  •  Sort data

    This Exercise in C# involves creating a program that asks the user for 10 integer numbers (from -1000 to 1000), sorts them, and then displays them in ascending...

  •  Two dimensional array as buffer for screen

    This Exercise in C# involves creating a program that declares a 70x20 two-dimensional array of characters and "draws" 80 letters (e.g., 'X') in random positions withi...