Week 2 - Control Structures
Learning Goals
- Use
if,else ifandelseto make decisions in code. - Use a
whileorforloop 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 > 0quantity == 0 || expired == true!inStock
Iteration
Use a for loop when you know how many times to repeat:
Use a while loop when you want to continue until a condition changes:
Your Task
Create a new Console App called Week2_Control.
Write a program that:
- Declares three shop items, each with a
name,priceandquantity. - Uses a
forloop to display each item. - Uses
if/elselogic inside the loop to print a stock status message: quantity == 0->"OUT OF STOCK"quantity < 5->"LOW STOCK"- 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
Extension
- Add a
double[] pricesarray 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
ifblock has more than one line