static void Main(string[] args)
{
string name = null, surname = null;
while (name != "A" && surname != "A")
{
Console.WriteLine("Enter Name:");
name = Console.ReadLine(); // Point A
Console.WriteLine("Enter Surname:");
surname = Console.ReadLine(); // Point B
}
Console.WriteLine("Oops");
Console.ReadLine();
}
The loop works fine:
Output1:
Enter Name:
John
Enter Surname:
Peter
Enter Name:
Jack
Enter Surname:
Andrew
Output2: (Trying the break the loop at Point A)
Enter Name:
A //loop didn't exit but went to the next statement
Enter Surname:
Peter
Oops
When I try to break the loop at Point A, the loop doesn't exit, but goes to the next statement and then exits after point B
Question: Why doesn't it exit the loop at point and how can I make it exit at point A?
The loop condition will be checked exactly before entering the whole block of code not after every statement execution in code. You can add a condition to execute the second part or break out of the loop or force checking of loop condition.
Breaking out of loop:
while (name != "A" && surname != "A")
{
Console.WriteLine("Enter Name:");
name = Console.ReadLine(); // Point A
if (name == "A")
break;
Console.WriteLine("Enter Surname:");
surname = Console.ReadLine(); // Point B
}
Set a condition to execute rest of the code:
while (name != "A" && surname != "A")
{
Console.WriteLine("Enter Name:");
name = Console.ReadLine(); // Point A
if (name != "A")
{
Console.WriteLine("Enter Surname:");
surname = Console.ReadLine(); // Point B
}
}
Force to check the loop condition (code after continue will not execute):
while (name != "A" && surname != "A")
{
Console.WriteLine("Enter Name:");
name = Console.ReadLine(); // Point A
if (name == "A")
continue;
Console.WriteLine("Enter Surname:");
surname = Console.ReadLine(); // Point B
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With