Ejercicio
Estructuras Anidadas
Objectivo
Cree una estructura para almacenar dos datos para una persona:
nombre y fecha de nacimiento.
La fecha de nacimiento debe ser otra estructura que consista en día, mes y año.
Finalmente, cree una matriz de personas, pida al usuario el dato de dos personas y muéstrelas.
Ejemplo Ejercicio C#
Mostrar Código C#
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
}
}
}
Salida
Enter the name of person 1: John
Enter the birth day of person 1: 15
Enter the birth month of person 1: 01
Enter the birth year of person 1: 1999
Enter the name of person 2: Marta
Enter the birth day of person 2: 20
Enter the birth month of person 2: 02
Enter the birth year of person 2: 1999
Person 1:
Name: John
Birth Date: 15/1/1999
Person 2:
Name: Marta
Birth Date: 20/2/1999
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp