Objective
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 and year.
Finally, create an array of persons, ask the user for the data of two persons and display them.
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to access basic classes like Console
class Program
{
// Define a struct for Date of Birth with three fields: Day, Month, and Year
struct DateOfBirth
{
public int Day; // Day of birth
public int Month; // Month of birth
public int Year; // Year of birth
}
// Define a struct for Person that includes a Name and a DateOfBirth
struct Person
{
public string Name; // Name of the person
public DateOfBirth BirthDate; // Date of birth of the person
}
static void Main()
{
// Create an array of Persons to store the data for two people
Person[] persons = new Person[2];
// Ask the user to input data for two persons
for (int i = 0; i < persons.Length; i++)
{
// Ask the user to enter the name of the person
Console.Write($"Enter the name of person {i + 1}: ");
persons[i].Name = Console.ReadLine(); // Store the name in the Name field of the struct
// Ask the user to enter the birth day of the person
Console.Write($"Enter the birth day of person {i + 1}: ");
persons[i].BirthDate.Day = int.Parse(Console.ReadLine()); // Store the birth day in the Day field of the nested struct
// Ask the user to enter the birth month of the person
Console.Write($"Enter the birth month of person {i + 1}: ");
persons[i].BirthDate.Month = int.Parse(Console.ReadLine()); // Store the birth month in the Month field of the nested struct
// Ask the user to enter the birth year of the person
Console.Write($"Enter the birth year of person {i + 1}: ");
persons[i].BirthDate.Year = int.Parse(Console.ReadLine()); // Store the birth year in the Year field of the nested struct
}
// Display the data of both persons
for (int i = 0; i < persons.Length; i++)
{
Console.WriteLine($"Person {i + 1}:"); // Print the person index (1 or 2)
Console.WriteLine($"Name: {persons[i].Name}"); // Display the name of the person
Console.WriteLine($"Birth Date: {persons[i].BirthDate.Day}/{persons[i].BirthDate.Month}/{persons[i].BirthDate.Year}"); // Display the birth date of the person
}
}
}