Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop doesn't exit on false condition

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?

like image 814
Mishael Ogochukwu Avatar asked Sep 16 '26 03:09

Mishael Ogochukwu


1 Answers

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
}
like image 184
Hamid Pourjam Avatar answered Sep 17 '26 15:09

Hamid Pourjam