Week 4 - Procedures, Functions and Methods
Learning Goals
- Write your own methods in C#.
- Understand the difference between a method that performs an action and one that returns a value.
- Pass data into methods using parameters.
- Call methods from other parts of your code.
Key Concepts
Why Use Methods?
Instead of writing the same code repeatedly, put it in a method and call it when needed. This makes code easier to read, fix and reuse.
Void Methods
static void DisplayItem(string name, double price, int quantity)
{
Console.WriteLine($"{name,-15} ${price:F2} x{quantity}");
}
DisplayItem("Milk", 2.10, 12);
DisplayItem("Bread", 3.50, 0);
Functions That Return a Value
static double CalculateStockValue(double price, int quantity)
{
return price * quantity;
}
double value = CalculateStockValue(2.10, 12);
Console.WriteLine($"Stock value: ${value:F2}");
Parameters vs Arguments
- A parameter is the variable in the method definition.
- An argument is the actual value passed into the method call.
Your Task
Create a new Console App called Week4_Methods.
Use the parallel arrays from Week 3, or create new ones. Write and use these three methods:
DisplayItem(string name, double price, int quantity)- prints one row of the inventory tabledouble CalculateStockValue(double price, int quantity)- returnsprice * quantitydouble CalculateTotalValue(double[] prices, int[] quantities)- loops through both arrays and returns the total stock value
Your Main method should be short and mainly set up the data and call your methods.
Expected Structure
static void Main(string[] args)
{
string[] names = { "Milk", "Bread", "Eggs", "Cola" };
double[] prices = { 2.10, 3.50, 4.00, 3.00 };
int[] stock = { 12, 0, 7, 5 };
Console.WriteLine("--- Inventory ---");
for (int i = 0; i < names.Length; i++)
{
DisplayItem(names[i], prices[i], stock[i]);
}
double total = CalculateTotalValue(prices, stock);
Console.WriteLine($"\nTotal stock value: ${total:F2}");
}
Extension
- Write a
bool IsLowStock(int quantity)method that returnstrueif quantity is less than 5. - Call it inside your display loop to add a
"LOW"tag next to items that need reordering.
Common Mistakes to Avoid
- forgetting the
returnstatement in a function - returning the wrong data type
- letting
Mainbecome too long when logic should be moved to methods