Week 3 - Data Structures: Arrays and Lists
Learning Goals
- Store multiple values using a one-dimensional array.
- Use a
List<T>to store data that can grow and shrink. - Access items by index.
- Understand the difference between an array and a list.
Key Concepts
One-Dimensional Arrays
An array holds a fixed number of items, all the same type.
string[] items = { "Milk", "Bread", "Eggs" };
Console.WriteLine(items[0]);
Console.WriteLine(items[2]);
items[1] = "Butter";
Console.WriteLine(items.Length);
Lists
A List<T> can grow and shrink at runtime.
List<string> shoppingList = new List<string>();
shoppingList.Add("Apple");
shoppingList.Add("Orange");
shoppingList.Add("Banana");
shoppingList.Remove("Orange");
Console.WriteLine(shoppingList[0]);
Console.WriteLine(shoppingList.Count);
foreach (string item in shoppingList)
{
Console.WriteLine(item);
}
Records Through Parallel Arrays
When each item needs multiple pieces of data, you can use parallel arrays.
string[] productNames = { "Milk", "Bread", "Eggs" };
double[] productPrices = { 2.10, 3.50, 4.00 };
int[] productStock = { 12, 0, 7 };
Console.WriteLine($"{productNames[1]} costs ${productPrices[1]}");
Your Task
Create a new Console App called Week3_DataStructures.
Write a program that:
- Uses parallel arrays to store 4 shop products: name, price and stock quantity.
- Uses a
forloop to display all products in a table format. - Calculates and displays the total value of all stock.
Expected Output
--- Inventory ---
Milk $2.10 x12 = $25.20
Bread $3.50 x0 = $0.00
Eggs $4.00 x7 = $28.00
Cola $3.00 x5 = $15.00
Total stock value: $68.20
Extension
- Create a
List<string>calledoutOfStockand add the names of any items with quantity0during the loop. - After the loop, display the out-of-stock list.
Common Mistakes to Avoid
- accessing an index that does not exist
- using
.Lengthon aList<T>instead of.Count - forgetting that parallel arrays must stay in sync