Skip to content

Week 2 - Control Structures

Learning Goals

  • Use if, else if and else to make decisions in code.
  • Use a while or for loop to repeat actions.
  • Combine conditions using logical operators.

Key Concepts

Selection

int quantity = 5;

if (quantity == 0)
{
    Console.WriteLine("OUT OF STOCK");
}
else if (quantity < 10)
{
    Console.WriteLine("Low stock - consider reordering");
}
else
{
    Console.WriteLine("Stock level is fine");
}

Logical Operators

  • && means both conditions must be true.
  • || means at least one condition must be true.
  • ! reverses a Boolean value.

Examples:

  • price > 0 && quantity > 0
  • quantity == 0 || expired == true
  • !inStock

Iteration

Use a for loop when you know how many times to repeat:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Item number {i}");
}

Use a while loop when you want to continue until a condition changes:

int count = 0;
while (count < 3)
{
    Console.WriteLine("Checking stock...");
    count++;
}

Your Task

Create a new Console App called Week2_Control.

Write a program that:

  1. Declares three shop items, each with a name, price and quantity.
  2. Uses a for loop to display each item.
  3. Uses if/else logic inside the loop to print a stock status message:
  4. quantity == 0 -> "OUT OF STOCK"
  5. quantity < 5 -> "LOW STOCK"
  6. otherwise -> "IN STOCK"

Suggested Starting Point

string[] names = { "Milk", "Bread", "Eggs" };
int[] quantities = { 0, 3, 20 };

for (int i = 0; i < 3; i++)
{
    // your code here
}

Expected Output

Milk       - OUT OF STOCK
Bread      - LOW STOCK
Eggs       - IN STOCK

Extension

  • Add a double[] prices array and also print the price for each item.
  • After the loop, use another loop to count how many items are out of stock and display the total.

Common Mistakes to Avoid

  • using = instead of == when comparing values
  • off-by-one errors in loops
  • forgetting braces when an if block has more than one line