Break, Continue and goto
Break
In C#, the break statement is used to exit or “break” out of a loop or a switch statement. It’s commonly used when a certain condition is met, and you want to immediately exit the loop or switch statement, regardless of whether the loop’s condition is still true or not.
Basic Structure
while (condition)
{
// Some code…
if (condition_to_exit_loop)
{
break; // Exit the loop
}
// More code…
}
Scenario: Write a C# program to search for a specific laptop in a list of laptops. If the brand “Apple” laptop is found, print a message saying “Yes, we want an Apple company laptop” and then exit the loop using a break statement.
Break Statement
using System;
class program
{
static void Main()
{
string[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
foreach (string laptop in laptops)
{
if (laptop == “Apple”)
{
Console.WriteLine(“Yes, we want an ” + laptop + ” company laptop”);
break;
}
}
}
}
Output: Yes, we want an Apple company laptop
Code Explanation
string[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
This line creates an array named laptops with the data type string that contains five string values: “Window”, “Samsung”, “Apple”, “Dell”, and “Asus”.
foreach (string laptop in laptops)
This line starts a foreach loop that goes through each item in the laptops array. For each iteration, the current item is stored in the variable laptop.
1. The laptop is “Window”. The condition laptop == “Apple” is false, so the loop continues to the next item.
2. The laptop is “Samsung”. The condition laptop == “Apple” is false, so the loop continues to the next item.
3. The laptop is “Apple”. The condition laptop == “Apple” is true, so the code inside the if statement runs: It prints “Yes, we want an Apple company laptop”. The break statement stops the loop.
Loop Ends:
The loop stops because of the break statement, and no further items are checked.
if (laptop == “Apple”)
Inside the loop, this line checks if the current laptop is equal to “Apple”. If yes then it will execute code under curly braces {}
Console.WriteLine(“Yes, we want an ” + laptop + ” company laptop”);
break;
If the current laptop is “Apple” it prints the message “Yes, we want an Apple company laptop” to the console and the break statement stops the loop immediately.
Output: Yes, we want an Apple company laptop
You will see the above output on your console.
Continue
Scenario: Write a C# program to search for a specific laptop in a list of laptops. If the brand “Apple” laptop is found, print a message saying, “We don’t want an Apple company laptop” and then continue to the next brand using a continue statement.
Basic Structure
for (/* initialization */; /* condition */; /* update */)
{
// code block
if (/* condition to skip current iteration */)
{
// Skip the remaining code in the loop for the current iteration
continue;
}
// code block continues if the continue statement is not executed
}
using System;
class program
{
static void Main()
{
string[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
foreach (string laptop in laptops)
{
if (laptop == “Apple”)
{
Console.WriteLine(“We don’t want an ” +laptop + ” company laptop”);
continue;
}
else
{
Console.WriteLine(“Give me the price of “+laptop + ” company laptop”);
}
}
}
}
Code Explanation
string[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
This line creates an array named laptops with the data type string that contains five string values: “Window”, “Samsung”, “Apple”, “Dell”, and “Asus”.
foreach (string laptop in laptops)
This line starts a foreach loop that goes through each laptop array item. For each iteration, the current item is stored in the variable laptop.
1. The laptop is “Window”. The condition laptop == “Apple” is false, so the loop print else statement , it print : “Give me the price of Window company laptop” and continues to the next item.
2. The laptop is “Samsung”. The condition laptop == “Apple” is false, so the loop print else statement , it print : “Give me the price of Samsung company laptop” and continues to the next item.
3. The laptop is “Apple”. The condition laptop == “Apple” is true, so the code inside the if statement runs: It prints “We don’t want an Apple company laptop”. The continue statement skips the rest of the code in the current iteration and moves to the next item.
4. The laptop is “Dell”. The condition laptop == “Apple” is false, so the loop print else statement , it print : “Give me the price of Dell company laptop” and continues to the next item.
The laptop is “Asus”. The condition laptop == “Apple” is false, so the loop print else statement , it print : “Give me the price of Asus company laptop” and loop ends.
foreach (string laptop in laptops)
Inside the loop, this line checks if the current laptop is equal to “Apple”. If yes, then it will execute the code under the curly braces {} of if condition if no , then it will execute the code under the curly braces {} of else condition.
Console.WriteLine(“We don’t want an ” + laptop + ” company laptop”);
continue;
If the current laptop is “Apple”, it prints the message “We don’t want an Apple company laptop” to the console. The continue statement then skips the rest of the code in the current iteration and moves to the next item in the loop.
Console.WriteLine(“Give me the price of “+laptop + ” company laptop”);
Inside the loop, this line prints the message “Give me the price of window company laptop” like this it updates the name of laptop in loop when ever the if condition is false
The difference between break and continue
Break | Continue |
---|---|
In the Break statement if the condition is true the code will break and exit | In the continue statement, it will run even after the condition is true for all values in the array |
For Example : Imagine you’re playing a board game and you decide to quit the game in the middle. You stop playing and leave. | For Example: Now imagine you’re playing the same game, but this time, if you don’t like one of your turns, you skip it and move to the next round. |
Goto
In C#, goto is a keyword that allows you to transfer the program’s control to a specified label within the same method, or to a label outside of the current method, such as in another method or block of code. The use of goto is generally discouraged because it can make code harder to understand and maintain. However, there are some situations where it can be used effectively.
Basic Structure
label:
// code block
// Goto statement
goto label;
Scenario: Write a C# program to count from 1 to 3 using an if statement. Use a goto statement to jump back to the beginning of the code if the counter is less than 3. When the counter is equal to 3 the code will end.
Goto Statement
using System;
class program
{
static void Main()
{
int counter = 0;
start:
Console.WriteLine($”Current count: {counter}”);
if (counter < 3)
{
counter++;
goto start; // Jumps to the ‘start’ label
}
}
}
Output: Current count: 0
Current count: 1
Current count: 2
Current count: 3
Code Explanation
int counter = 0;
This line declares an integer variable named counter and initializes it to 0.
start:
Console.WriteLine($”Current count: {counter}”);
This defines a label named start. The following line prints the current value of the counter to the console. The $ before the string indicates an interpolated string, allowing the value of the counter to be included in the output.
if (counter < 3)
{
counter++;
goto start; // Jumps to the ‘start’ label
}
This if statement checks if the counter is less than 3. If the condition is true, the code inside the curly braces executes. It increments the value of the counter by 1 and then uses the goto statement to jump back to the start label. This causes the loop to repeat until the counter is no longer less than 3.
Once the counter reaches 3, the if condition evaluates to false, and the program exits the loop, reaching the end of the Main method and finishing execution.
Output: Current count: 0
Current count: 1
Current count: 2
Current count: 3
You will see the above output on your console.
Course Video
Task:
1. Imagine you’re searching for a specific fruit in market like you want apple from this list “mango , orange ,watermelon ,apple , grapes” if you get any apple fruit you can break fruit list.
For example : First you must create string array for fruits and then use that array in loop then check in if condition which fruit you want from list once find then break the loop same as below
2.Certainly! Let’s create a scenario where you visit a clothing boutique and use the concept of break to stop searching once you find the black t-shirt you’re looking for.
For example: First you must create string array for clothes and then use that array in loop then check in if condition which cloth you want from list once find then break the loop same as below
3. Imagine a school or college organizing a racing event where participants are required to have a height greater than 60 inches to qualify for the race. Imagine the heights of six participants is : 60 inches, 62 inches, 58 inches, 65 inches, 55 inches, and 68 inches if height is less then 60 then player don’t participate in racing.
For example : First you must create integer array for height and then use that array in loop then check in if condition which height is less than 60 and use continue to skip that participant and show like below
4. Who are the people in your life who inspire you the most ? from which you not inspired skip that person by using continue
For example : First create string array with values “brother, father ,mother ,sister , teacher” then use loop and check in loop using if condition the names from you didn’t inspire skip them and output like below
5. Find First Even Number:
Use a for loop to iterate from 1 to 20.
Inside the loop, use an if-else statement to check if the number is even.
Use a break statement to stop the loop once the first even number is found.
6. Sum Until Negative:
Use a while loop to continuously ask the user for a number.
Use an if-else statement to check if the entered number is negative.
Use a break statement to exit the loop if a negative number is entered.
7. Skip Multiples of 3:
Use a for loop to iterate from 1 to 30.
Inside the loop, use an if-else statement to check if the number is a multiple of 3.
Use a continue statement to skip printing multiples of 3.
8. Prime Numbers Until Limit:
Use a while loop to print prime numbers starting from 1.
Inside the loop, use an if-else statement to check if the number is prime.
Use a break statement to stop the loop when the prime number exceeds 50.
9. Guessing Game with Attempts:
Use a do-while loop to implement a number guessing game with a maximum of 5 attempts.
Use an if-else statement to check if the guessed number is higher, lower, or equal to the target number.
Use a break statement to exit the loop if the correct number is guessed within 5 attempts.
10. Menu with Exit Option:
Use a while loop to display a menu with options.
Use a switch statement to handle different menu selections.
Use a break statement inside the switch case to exit the loop when the user chooses the exit option.
11. Print Fibonacci Sequence:
Use a for loop to print the Fibonacci sequence up to 100.
Use an if-else statement to check if the next number exceeds 100.
Use a break statement to stop the loop when the sequence exceeds 100.
12. Filter Negative Numbers:
Use a while loop to iterate through an array of integers.
Use an if-else statement to check if the current number is negative.
Use a continue statement to skip processing negative numbers.
13. Days of the Week:
Use a for loop to iterate through an array of days of the week.
Inside the loop, use a switch statement to print “Weekday” for Monday to Friday and “Weekend” for Saturday and Sunday.
Use a break statement to exit the loop if the day is “Sunday”.
14. Temperature Conversion Until Zero:
Use a while loop to continuously ask the user for a temperature in Celsius.
Use an if-else statement to convert the temperature to Fahrenheit.
Use a break statement to stop the loop if the entered temperature is 0.