1

I want to exit from a loop when both i and j have the value 6, but it exits when one of them has the value 6.

int i,j,k;
i=k=0;
j=1;
Random num = new Random();
Console.WriteLine("Please Press any Key to Roll");
while((i!=6)&&(j!=6))
{
    Console.ReadKey();
    i= num.Next(0,7);
    j= num.Next(0,7);
    Console.WriteLine("1st Rolled Number is: "+ i);
    Console.WriteLine("2st Rolled Number is: "+ j);
    k++;
}
Console.WriteLine("Your have achieved it in "+ k + " Atempts");

3 Answers 3

5

To exit the loop when both i and j have the value 6, you can change the condition in the while loop to

Change too

while ((i != 6) || (j != 6))

This will exit the loop when either i or j. To exit the loop when both i and j have the value 6,

while (!(i == 6 && j == 6))

This will exit the loop when both i and j have the value 6.

Sign up to request clarification or add additional context in comments.

Comments

1

In other words, the loop should continue if either i isn't 6 or j isn't 6 - this is a logical or (||) condition, not a logical and (&&) condition:

while ((i != 6) || (j != 6))

Comments

0

an alternative approach can be

while(true)
{
    Console.ReadKey();
    i = num.Next(0, 7);
    j = num.Next(0, 7);
    Console.WriteLine("1st Rolled Number is: " + i);
    Console.WriteLine("2st Rolled Number is: " + j);
    k++;
    if (i == 6 && j == 6) break;
}
Console.WriteLine("You have achieved it in " + k + " attempts");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.