📖 Scenario: Imagine you are checking a list of daily temperatures to find the first day when the temperature reaches or exceeds a certain limit. Once you find that day, you want to stop checking further to save time.
🎯 Goal: You will write a program that uses a break statement inside a for loop to stop the loop early when a condition is met.
📋 What You'll Learn
Create an array called temperatures with the exact values: 23, 25, 28, 30, 27, 31, 29
Create an integer variable called threshold and set it to 30
Use a for loop with the variable i to iterate over temperatures
Inside the loop, use an if statement to check if temperatures[i] is greater than or equal to threshold
Use the break statement to exit the loop when the condition is true
After the loop, print the index i where the temperature first reached or exceeded the threshold
💡 Why This Matters
🌍 Real World
Checking sensor data or daily measurements to find the first occurrence of a critical value quickly.
💼 Career
Understanding how to stop loops early is important for writing efficient programs in many software development jobs.
Progress0 / 4 steps
1
Create the temperature data array
Create an integer array called temperatures with these exact values: 23, 25, 28, 30, 27, 31, 29.
C Sharp (C#)
Hint
Use int[] temperatures = { ... }; to create the array with the exact numbers.
2
Set the temperature threshold
Create an integer variable called threshold and set it to 30.
C Sharp (C#)
Hint
Use int threshold = 30; to create the threshold variable.
3
Use a for loop with break to find the first day reaching threshold
Write a for loop with the variable i to iterate over temperatures. Inside the loop, use an if statement to check if temperatures[i] is greater than or equal to threshold. Use the break statement to exit the loop when this condition is true.
C Sharp (C#)
Hint
Use for (i = 0; i < temperatures.Length; i++) and inside it check if (temperatures[i] >= threshold) then break;.
4
Print the index where threshold was reached
Write a Console.WriteLine statement to print the value of i, which is the index where the temperature first reached or exceeded the threshold.
C Sharp (C#)
Hint
Use Console.WriteLine(i); to print the index.
Practice
(1/5)
1. What does the break statement do inside a loop in C#?
easy
A. It skips the current iteration and continues the loop.
B. It immediately stops the loop and exits it.
C. It pauses the loop until a condition is true.
D. It restarts the loop from the beginning.
Solution
Step 1: Understand the role of break in loops
The break statement is designed to stop the nearest enclosing loop immediately when executed.
Step 2: Compare with other loop control statements
Unlike continue which skips to the next iteration, break exits the loop entirely.
Final Answer:
It immediately stops the loop and exits it. -> Option B