Cities database C# Exercise - C# Programming Course

 Exercise

Cities database

 Objetive

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

 Example Code

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.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
        }
    }
}

More C# Exercises of Arrays, Structures and Strings

 Reverse array
Write a C# program to ask the user for 5 numbers, store them in an array and show them in reverse order....
 Search in array
Write a C# program that says if a data belongs in a list that was previously created. The steps to take are: - Ask the user how many data will he ...
 Array of even numbers
Write a C# program to ask the user for 10 integer numbers and display the even ones....
 Array of positive and negative numbers
Write a C# program to ask the user for 10 real numbers and display the average of the positive ones and the average of the negative ones....
 Many numbers and sum
Write a C# program which asks the user for several numbers (until he enters "end" and displays their sum). When the execution is going to end, it must...
 Two dimensional array
Write a C# program to ask the user for marks for 20 pupils (2 groups of 10, using a two-dimensional array), and display the average for each group....
 Statistics V2
Write a C# statistical program which will allow the user to: - Add new data - See all data entered - Find an item, to see whether it has been en...
 Struct
Write a C# Struct to store data of 2D points. The fields for each point will be: x coordinate (short) y coordinate (short) r (red colour, byte) ...
 Array of struct
Write a C# program that expand the previous exercise (struct point), so that up to 1.000 points can be stored, using an "array of struct". Ask the use...
 Array of struct and menu
Write a C# program that expand the previous exercise (array of points), so that it displays a menu, in which the user can choose to: - Add data for...
 Books database
Create a small database, which will be used to store data about books. For a certain book, we want to keep the following information: Title Author...
 Triangle V2
Write a C# program to ask the user for his/her name and display a triangle with it, starting with 1 letter and growing until it has the full length: ...
 Rectangle V3
Write a C# program to ask the user for his/her name and a size, and display a hollow rectangle with it: Enter your name: Yo Enter size: 4 YoYoYoY...
 Centered triangle
Write a C# program that Display a centered triangle from a string entered by the user: __a__ _uan_ Juan...
 Banner
Write a C# program to imitate the basic Unix SysV "banner" utility, able to display big texts....
 Triangle right side
Write a C# program that asks the user for a string and displays a right-aligned triangle: ____n ___an __uan Juan...
 Strings manipulation
Write a C# program that asks the user for a string and: - Replace all lowercase A by uppercase A, except if they are preceded with a space - Displ...
 Nested structs
Write a C# Struct to store two data for a person: name and date of birth. The date of birth must be another struct consisting on day, month an...
 Sort data
Write a C# program to ask the user for 10 integer numbers (from -1000 to 1000), sort them and display them sorted....
 Two dimensional array as buffer for screen
Write a C# program that declares a 70x20 two-dimensional array of characters, "draws" 80 letters (X, for example) in random positions and displays the...
 Two dimensional array 2: circunference on screen
Write a C# program that declares creates a 70x20 two-dimensional array of characters, "draws" a circumference or radius 8 inside it, and displays it o...
 Computer programs
Write a C# program that can store up to 1000 records of computer programs. For each program, you must keep the following data: * Name * Category ...
 Exercise tasks
Write a C# program that can store up to 2000 "to-do tasks". For each task, it must keep the following data: • Date (a set of 3 data: day, month and...
 Household accounts
Write a C# program in C# that can store up to 10000 costs and revenues, to create a small domestic accounting system. For each expense (or income), sh...

Juan A. Ripoll - Programming Tutorials and Courses © 2025 All rights reserved.  Legal Conditions.