- Course
- Arrays
- Array of struct
Array of struct
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C # program that uses an array of struct to store a car record. You will first need to create a data structure called Car
with two public properties:
- Model: string
- AnyoFabricacion: int
Now request for example 3 cars from the user and save them in the structs array. Lastly, order the cars by their year of manufacture, the oldest first.
Input
BMW
2005
Porsche
1970
Toyota
1993
Output
Model: Porsche, Year of production: 1970
Model: Toyota, Year of production: 1993
Model: BMW, Year of production: 2005
Solution
using System;
class ArrayOfStruct
{
struct Car
{
public string Model;
public int YearOfProduction;
}
static void Main(string[] args)
{
int total = 3;
Car[] cars = new Car[total];
for (int i = 0; i < total; i++)
{
cars[i] = new Car()
{
Model = Console.ReadLine(),
YearOfProduction = int.Parse(Console.ReadLine())
};
}
// Sort
for (int i = 0; i < total - 1; i++)
{
for (int j = i + 1; j < total; j++)
{
if (cars[i].YearOfProduction > cars[j].YearOfProduction)
{
var aux = cars[i];
cars[i] = cars[j];
cars[j] = aux;
}
}
}
// Show
for (int i = 0; i < total; i++)
{
var car = cars[i];
Console.WriteLine("Model: " + car.Model + ", " +
"Year of production: " + car.YearOfProduction);
}
}
}