Computer Programs - C# Programming Exercise

Exercise in C# involves creating a program that can store up to 1000 records of computer programs. For each program, the following data should be stored: name, category, description, and version (which consists of three data: version number -text-, release month -byte-, and release year -unsigned short-). The program should allow the user to perform the following operations:

1. Add a new program: It must validate that the name is not empty, that the category does not exceed 30 characters (or else it must be re-entered), and that the description only accepts the first 100 characters entered. The version does not need validation.

2. Show the names of all stored programs: The names of the programs should be displayed on separate lines. If there are more than 20 programs, the program must pause after each block of 20 programs and wait for the user to press Enter before continuing. If there is no data, the user should be notified.

3. View the data for a specific program: The program should allow searching for a program by part of its name, category, or description (case sensitive). If multiple programs are found that match the text entered, they should be displayed separated by a blank line. If no matches are found, the user should be notified.

4. Update a record: The program should ask the user for the number of the record to update. The previous value of each field should be displayed, and the user can press Enter to not modify the data. If the record number entered is incorrect, the program should show a warning without asking again.

5. Delete a record: The program should allow deleting a record by its number. If the number entered is incorrect, the user should be notified.

6. Sort programs alphabetically by name: The program must be able to sort records alphabetically by the name of the programs.

7. Fix redundant spaces: The program should eliminate sequences of two or more consecutive spaces in the name of all programs, reducing them to a single space.

8. Exit the application: The program should allow exiting the application. Since the information is not stored permanently, the data will be lost upon exit.

This Exercise is useful for practicing the manipulation of data collections, such as lists or arrays in C#, and allows working with basic operations like adding, modifying, deleting, and sorting records. Additionally, it reinforces knowledge of flow control structures, user input validation, and string manipulation.

 Category

Arrays, Structures and Strings

 Exercise

Computer Programs

 Objective

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

 Write Your C# Exercise

using System;  // Importing the System namespace for accessing Console, Math, and other functionalities

class Program
{
    // Define the Program struct to store the program details
    struct ProgramRecord
    {
        public string Name;
        public string Category;
        public string Description;
        public (string VersionNumber, byte LaunchMonth, ushort LaunchYear) Version;
    }

    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)
        {
            Console.Clear();
            Console.WriteLine("Program Management System");
            Console.WriteLine("1 - Add a new program");
            Console.WriteLine("2 - Show all program names");
            Console.WriteLine("3 - View details of a program");
            Console.WriteLine("4 - Update a record");
            Console.WriteLine("5 - Delete a record");
            Console.WriteLine("6 - Sort by program name");
            Console.WriteLine("7 - Fix redundant spaces in names");
            Console.WriteLine("X - Exit");
            Console.Write("Enter an option: ");
            string choice = Console.ReadLine();

            switch (choice.ToUpper())
            {
                case "1":
                    AddProgram(ref programs, ref programCount);
                    break;
                case "2":
                    ShowProgramNames(programs, programCount);
                    break;
                case "3":
                    ViewProgramDetails(programs, programCount);
                    break;
                case "4":
                    UpdateRecord(programs, programCount);
                    break;
                case "5":
                    DeleteRecord(ref programs, ref programCount);
                    break;
                case "6":
                    SortProgramsByName(ref programs, programCount);
                    break;
                case "7":
                    FixRedundantSpaces(ref programs, programCount);
                    break;
                case "X":
                    return;
                default:
                    Console.WriteLine("Invalid option. Try again.");
                    break;
            }
        }
    }

    static void AddProgram(ref ProgramRecord[] programs, ref int programCount)
    {
        if (programCount >= 1000)
        {
            Console.WriteLine("Error: Program limit reached.");
            return;
        }

        // Get program details from the user
        string name;
        do
        {
            Console.Write("Enter program name: ");
            name = Console.ReadLine();
        } while (string.IsNullOrWhiteSpace(name));

        string category;
        do
        {
            Console.Write("Enter category (max 30 characters): ");
            category = Console.ReadLine();
        } while (category.Length > 30);

        Console.Write("Enter description (max 100 characters): ");
        string description = Console.ReadLine();
        if (description.Length > 100) description = description.Substring(0, 100);

        Console.Write("Enter version number: ");
        string versionNumber = Console.ReadLine();

        Console.Write("Enter launch month (1-12): ");
        byte launchMonth = byte.Parse(Console.ReadLine());

        Console.Write("Enter launch year: ");
        ushort launchYear = ushort.Parse(Console.ReadLine());

        // Store the program
        programs[programCount] = new ProgramRecord
        {
            Name = name,
            Category = category,
            Description = description,
            Version = (versionNumber, launchMonth, launchYear)
        };
        programCount++;
        Console.WriteLine("Program added successfully!");
    }

    static void ShowProgramNames(ProgramRecord[] programs, int programCount)
    {
        if (programCount == 0)
        {
            Console.WriteLine("No programs stored.");
            return;
        }

        int index = 0;
        while (index < programCount)
        {
            for (int i = index; i < Math.Min(index + 20, programCount); i++)
            {
                Console.WriteLine(programs[i].Name);
            }

            if (index + 20 < programCount)
            {
                Console.WriteLine("Press Enter to see the next 20 programs...");
                Console.ReadLine();
            }

            index += 20;
        }
    }

    static void ViewProgramDetails(ProgramRecord[] programs, int programCount)
    {
        Console.Write("Enter part of the name, category, or description to search: ");
        string searchQuery = Console.ReadLine().ToLower();

        bool found = false;
        for (int i = 0; i < programCount; i++)
        {
            if (programs[i].Name.ToLower().Contains(searchQuery) ||
                programs[i].Category.ToLower().Contains(searchQuery) ||
                programs[i].Description.ToLower().Contains(searchQuery))
            {
                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;
            }
        }

        if (!found)
        {
            Console.WriteLine("No programs found matching the search query.");
        }
    }

    static void UpdateRecord(ProgramRecord[] programs, int programCount)
    {
        Console.Write("Enter the program number to update: ");
        int programNumber = int.Parse(Console.ReadLine()) - 1;

        if (programNumber < 0 || programNumber >= programCount)
        {
            Console.WriteLine("Invalid program number.");
            return;
        }

        Console.WriteLine("Current data:");
        Console.WriteLine($"Name: {programs[programNumber].Name}");
        Console.WriteLine($"Category: {programs[programNumber].Category}");
        Console.WriteLine($"Description: {programs[programNumber].Description}");
        Console.WriteLine($"Version: {programs[programNumber].Version.VersionNumber}, {programs[programNumber].Version.LaunchMonth}/{programs[programNumber].Version.LaunchYear}");
        
        Console.Write("Enter new name (or press Enter to keep current): ");
        string newName = Console.ReadLine();
        if (!string.IsNullOrWhiteSpace(newName)) programs[programNumber].Name = newName;

        Console.Write("Enter new category (or press Enter to keep current): ");
        string newCategory = Console.ReadLine();
        if (!string.IsNullOrWhiteSpace(newCategory)) programs[programNumber].Category = newCategory;

        Console.Write("Enter new description (or press Enter to keep current): ");
        string newDescription = Console.ReadLine();
        if (!string.IsNullOrWhiteSpace(newDescription)) programs[programNumber].Description = newDescription;

        Console.Write("Enter new version number (or press Enter to keep current): ");
        string newVersionNumber = Console.ReadLine();
        if (!string.IsNullOrWhiteSpace(newVersionNumber)) programs[programNumber].Version.VersionNumber = newVersionNumber;

        Console.Write("Enter new launch month (or press Enter to keep current): ");
        byte newLaunchMonth;
        if (byte.TryParse(Console.ReadLine(), out newLaunchMonth)) programs[programNumber].Version.LaunchMonth = newLaunchMonth;

        Console.Write("Enter new launch year (or press Enter to keep current): ");
        ushort newLaunchYear;
        if (ushort.TryParse(Console.ReadLine(), out newLaunchYear)) programs[programNumber].Version.LaunchYear = newLaunchYear;

        Console.WriteLine("Program updated successfully!");
    }

    static void DeleteRecord(ref ProgramRecord[] programs, ref int programCount)
    {
        Console.Write("Enter the program number to delete: ");
        int programNumber = int.Parse(Console.ReadLine()) - 1;

        if (programNumber < 0 || programNumber >= programCount)
        {
            Console.WriteLine("Invalid program number.");
            return;
        }

        for (int i = programNumber; i < programCount - 1; i++)
        {
            programs[i] = programs[i + 1];
        }
        programCount--;
        Console.WriteLine("Program deleted successfully!");
    }

    static void SortProgramsByName(ref ProgramRecord[] programs, int programCount)
    {
        Array.Sort(programs, 0, programCount, Comparer.Create((a, b) => a.Name.CompareTo(b.Name)));
        Console.WriteLine("Programs sorted alphabetically by name.");
    }

    static void FixRedundantSpaces(ref ProgramRecord[] programs, int programCount)
    {
        for (int i = 0; i < programCount; i++)
        {
            programs[i].Name = System.Text.RegularExpressions.Regex.Replace(programs[i].Name, @"\s+", " ");
        }
        Console.WriteLine("Redundant spaces in program names fixed.");
    }
}

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

  •  Exercise tasks

    This exercise in C# consists of creating a program that can store up to 2000 "to-do tasks". Each task must store the following data: • Date (a set of 3 data: ...

  •  Household accounts

    This exercise in C# consists of creating a program that can store up to 10,000 costs and revenues, to create a small domestic accounting system. For eac...

  •  Reverse array

    In this C# exercise, you are asked to write a program that prompts the user for 5 numbers, stores them in an array, and displays them in reverse order. ...

  •  Search in array

    In this C# exercise, you are asked to write a program that checks if a given data belongs to a previously created list. The steps to follow are:

  •  Array of even numbers

    In this C# exercise, you are asked to write a program that asks the user for 10 integer numbers and displays the even ones. This exercise w...

  •  Array of positive and negative numbers

    In this C# exercise, you are asked to write a program that asks the user for 10 real numbers and displays the average of the positive ones and the average of t...