Home > Software engineering >  What is the difference between the and operator and or operator in a for loop?
What is the difference between the and operator and or operator in a for loop?

Time:09-17

This loop is breaking with the (||) 'OR' operator but not with the (&&) 'AND' operator. Why is that? What's the difference between the two?

    int a;
    char ch;
    for(a=1;a<=20;a  )
    {
        printf("%d\n",a);
        printf("do you want to break the loop(y/n)");
        scanf(" %c",&ch);
        if(ch=='y' && ch=='Y')
        {
            break;
        }

    }
    return 0;
}

CodePudding user response:

The statement

if (ch=='y' && ch=='Y')
{
    break;
}

says "if the character is simultaneously the character y and the character Y, then exit the loop." But that can't happen, since a character can't simultaneously be both y and Y.

On the other hand, the code

if (ch=='y' || ch=='Y')
{
    break;
}

says "if the character is either y or Y, then exit the loop." And it is indeed possible for a character to be one of y or Y, even if it can't be both.

CodePudding user response:

First you have to know the difference between && and ||

What is logical AND(&&) ?

When you use logical and i.e && in between statements it will go through all those statements and check every statement in condition.

if ( ch == 'Y' && ch1 == 'y')
{
    // Here it check both the conditions
    // When both the conditions comes true then if block will execute.
 }

What is logical OR (||) ?

Logical OR ( || ) is something which try to find one possible condition which is true. When you put multiple conditions using || then compiler doesn't go through all condition it will stop check the condition when it encounters a valid condition.

if ( ch == 'Y' || ch1 == 'y')
{
    // If you input any value
    // When any one condition from both comes true then 
    // Your if block will be executed
 }

As per your assumption you have to give two valid inputs to break the if statement

int a;
char ch;
char ch1;
for(a=1;a<=20;a  )
{
    printf("%d\n",a);
    printf("do you want to break the loop y/n : ");
    scanf(" %c",&ch);
    printf("\n Are you sure Y/N : ");
    scanf(" %c",&ch1);
    if(ch=='y' && ch1=='Y')
    {
        break;
    }

}
return 0;
  • Related