Computer programs C# Exercise - C# Programming Course

 Exercise

Computer programs

 Objetive

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
* Description
* Version (is a set of 3 data: version number -text-, launch month -byte- and launch year -unsigned short-)

The program should allow the user the following operations:
1 - Add data of a new program (the name must not be empty, category must not be more than 30 letters (or should be re-entered), and for the description, it will accept only the first 100 letters entered and skip the rest; the version needs no validation).
2 - Show the names of all the stored programs. Each name must appear on one line. If there are more than 20 programs, you must pause after displaying each block of 20 programs, and wait for the user to press Enter before proceeding. The user should be notified if there is no data.
3 - View all data for a certain program (from part of its name, category or description, case sensitive). If there are several programs that contain that text, the program will display all of them, separated by a blank line. The user should be notified if there are no matches found.
4 - Update a record (asking the user for the number, the program will display the previous value of each field, and the user can press Enter not to modify any of the data). He should be warned (but not asked again) if he enters an incorrect record number. It is not necessary to validate any of the fields.
5 - Delete a record, whose number will be indicated by the user. He should be warned (but not asked again) if he enters an incorrect number.
6 - Sort the data alphabetically by name.
7 - Fix redundant spaces (turn all the sequences of two or more spaces into a single space, only in the name, for all existing records).
X - Exit the application (as we do not store the information, data will be lost).

 Example Code

using System;  // Importing the System namespace for accessing Console, Math, and other functionalities
using System.Collections.Generic;  // Importing the Collections.Generic namespace to use Comparer

class Program
{
    // Define the Program struct to store the program details
    struct ProgramRecord
    {
        public string Name;  // The name of the program
        public string Category;  // The category of the program
        public string Description;  // A brief description of the program
        public (string VersionNumber, byte LaunchMonth, ushort LaunchYear) Version;  // The version of the program, including version number, launch month, and launch year
    }

    static void Main()
    {
        // Create an array to hold up to 1000 program records
        ProgramRecord[] programs = new ProgramRecord[1000];  
        int programCount = 0;  // Keeps track of how many programs have been added

        while (true)  // Infinite loop to keep the menu running until the user chooses to exit
        {
            Console.WriteLine("Program Management System");  // Display the system title
            Console.WriteLine("1 - Add a new program");  // Option to add a new program
            Console.WriteLine("2 - Show all program names");  // Option to show all program names
            Console.WriteLine("3 - View details of a program");  // Option to view detailed information of a program
            Console.WriteLine("4 - Update a record");  // Option to update an existing program record
            Console.WriteLine("5 - Delete a record");  // Option to delete a program record
            Console.WriteLine("6 - Sort by program name");  // Option to sort programs alphabetically by name
            Console.WriteLine("7 - Fix redundant spaces in names");  // Option to fix redundant spaces in program names
            Console.WriteLine("X - Exit");  // Option to exit the program
            Console.Write("Enter an option: ");  // Prompt the user to select an option
            string choice = Console.ReadLine();  // Read the user's choice

            switch (choice.ToUpper())  // Convert the choice to uppercase and process it
            {
                case "1":
                    // Adding a new program
                    if (programCount >= 1000)  // Check if the program limit has been reached
                    {
                        Console.WriteLine("Error: Program limit reached.");  // Inform the user if the program limit is reached
                        break;  // Exit the case if the limit is reached
                    }

                    // Get program details from the user
                    string name;
                    do
                    {
                        Console.Write("Enter program name: ");  // Prompt the user for the program name
                        name = Console.ReadLine();  // Read the program name from the user input
                    } while (string.IsNullOrWhiteSpace(name));  // Keep asking until the user enters a valid name

                    string category;
                    do
                    {
                        Console.Write("Enter category (max 30 characters): ");  // Prompt the user for the program category
                        category = Console.ReadLine();  // Read the category
                    } while (category.Length > 30);  // Keep asking if the category is longer than 30 characters

                    Console.Write("Enter description (max 100 characters): ");  // Prompt the user for the program description
                    string description = Console.ReadLine();  // Read the description
                    if (description.Length > 100) description = description.Substring(0, 100);  // Trim the description if it's longer than 100 characters

                    Console.Write("Enter version number: ");  // Prompt for the version number
                    string versionNumber = Console.ReadLine();  // Read the version number

                    Console.Write("Enter launch month (1-12): ");  // Prompt for the launch month
                    byte launchMonth = byte.Parse(Console.ReadLine());  // Read and parse the launch month

                    Console.Write("Enter launch year: ");  // Prompt for the launch year
                    ushort launchYear = ushort.Parse(Console.ReadLine());  // Read and parse the launch year

                    // Store the program details in the programs array
                    programs[programCount] = new ProgramRecord
                    {
                        Name = name,
                        Category = category,
                        Description = description,
                        Version = (versionNumber, launchMonth, launchYear)  // Store version details as a tuple
                    };
                    programCount++;  // Increment the count of added programs
                    Console.WriteLine("Program added successfully!");  // Inform the user that the program has been added
                    break;

                case "2":
                    // Displaying all program names
                    if (programCount == 0)  // Check if there are no programs stored
                    {
                        Console.WriteLine("No programs stored.");  // Inform the user that no programs exist
                        break;  // Exit the case if there are no programs
                    }

                    int index = 0;  // Initialize the index for program names display
                    while (index < programCount)  // Loop through all programs
                    {
                        for (int i = index; i < Math.Min(index + 20, programCount); i++)  // Display 20 programs at a time
                        {
                            Console.WriteLine(programs[i].Name);  // Display the program name
                        }

                        if (index + 20 < programCount)  // Check if there are more programs to display
                        {
                            Console.WriteLine("Press Enter to see the next 20 programs...");  // Prompt the user to see more programs
                            Console.ReadLine();  // Wait for the user to press Enter
                        }

                        index += 20;  // Move the index to the next 20 programs
                    }
                    break;

                case "3":
                    // Viewing program details
                    Console.Write("Enter part of the name, category, or description to search: ");  // Prompt the user to search
                    string searchQuery = Console.ReadLine().ToLower();  // Read and convert the search query to lowercase

                    bool found = false;  // Flag to check if any program matches the search query
                    for (int i = 0; i < programCount; i++)  // Loop through the programs
                    {
                        // Check if any part of the program matches the search query
                        if (programs[i].Name.ToLower().Contains(searchQuery) ||
                            programs[i].Category.ToLower().Contains(searchQuery) ||
                            programs[i].Description.ToLower().Contains(searchQuery))
                        {
                            // Display the program details if a match is found
                            Console.WriteLine($"Program {i + 1}:");
                            Console.WriteLine($"  Name: {programs[i].Name}");
                            Console.WriteLine($"  Category: {programs[i].Category}");
                            Console.WriteLine($"  Description: {programs[i].Description}");
                            Console.WriteLine($"  Version: {programs[i].Version.VersionNumber}, {programs[i].Version.LaunchMonth}/{programs[i].Version.LaunchYear}");
                            Console.WriteLine();
                            found = true;  // Set the flag to true if a match is found
                        }
                    }

                    if (!found)  // If no match was found, inform the user
                    {
                        Console.WriteLine("No matching program found.");
                    }
                    break;

                case "4":
                    // Updating a program record
                    Console.Write("Enter the program name to update: ");  // Prompt the user for the program name to update
                    string nameToUpdate = Console.ReadLine();  // Read the name of the program to update
                    bool updated = false;  // Flag to check if the program was updated

                    for (int i = 0; i < programCount; i++)  // Loop through the programs
                    {
                        if (programs[i].Name.Equals(nameToUpdate, StringComparison.OrdinalIgnoreCase))  // Check if the program name matches
                        {
                            // Get new program details from the user
                            Console.Write("Enter new program name: ");
                            programs[i].Name = Console.ReadLine();
                            Console.Write("Enter new category: ");
                            programs[i].Category = Console.ReadLine();
                            Console.Write("Enter new description: ");
                            programs[i].Description = Console.ReadLine();
                            Console.Write("Enter new version number: ");
                            programs[i].Version = (Console.ReadLine(), byte.Parse(Console.ReadLine()), ushort.Parse(Console.ReadLine()));
                            updated = true;  // Set flag to true if the program was updated
                            Console.WriteLine("Program updated successfully!");
                            break;
                        }
                    }

                    if (!updated)  // If the program was not found, inform the user
                    {
                        Console.WriteLine("Program not found.");
                    }
                    break;

                case "5":
                    // Deleting a program record
                    Console.Write("Enter the program name to delete: ");  // Prompt the user for the program name to delete
                    string nameToDelete = Console.ReadLine();  // Read the name of the program to delete
                    bool deleted = false;  // Flag to check if the program was deleted

                    for (int i = 0; i < programCount; i++)  // Loop through the programs
                    {
                        if (programs[i].Name.Equals(nameToDelete, StringComparison.OrdinalIgnoreCase))  // Check if the program name matches
                        {
                            // Shift all subsequent programs one position to the left
                            for (int j = i; j < programCount - 1; j++) 
                            {
                                programs[j] = programs[j + 1];
                            }
                            programCount--;  // Decrease the program count
                            deleted = true;  // Set the flag to true if the program was deleted
                            Console.WriteLine("Program deleted successfully!");
                            break;
                        }
                    }

                    if (!deleted)  // If the program was not found, inform the user
                    {
                        Console.WriteLine("Program not found.");
                    }
                    break;

                case "6":
                    // Sorting programs by name
                    Array.Sort(programs, 0, programCount, Comparer.Create((x, y) => x.Name.CompareTo(y.Name)));  // Sort the programs by name
                    Console.WriteLine("Programs sorted by name.");
                    break;

                case "7":
                    // Fixing redundant spaces in program names
                    for (int i = 0; i < programCount; i++)  // Loop through the programs
                    {
                        programs[i].Name = programs[i].Name.Trim();  // Remove leading and trailing spaces
                        programs[i].Name = string.Join(" ", programs[i].Name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));  // Remove extra spaces between words
                    }
                    Console.WriteLine("Redundant spaces removed.");
                    break;

                case "X":
                    return;  // Exit the program when the user enters 'X'

                default:
                    Console.WriteLine("Invalid option, try again.");  // Inform the user if an invalid option is selected
                    break;
            }
            Console.WriteLine("Press Enter to return to the menu...");  // Prompt the user to press Enter to go back to the menu
            Console.ReadLine();  // Wait for the user to press Enter
        }
    }
}

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...
 Cities database
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, a...
 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...
 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.