c language ifelse statement question

Asked 1 years ago, Updated 1 years ago, 103 views

This is a question that enters three integers and indicates whether each integer is even or odd.

 int a, b,c;

    scanf_s("%d%d%d", &a,&b,&c);

    if (a % 2 == 0)
    {
        printf("%s\n", "even");
    }

    else if (a % 2 == 1)
    {
        printf("%s\n", "odd");
    }
    else if (b % 2 == 0)
    {
        printf("%s\n", "even");
    }
    else if (b % 2 == 1)
    {
        printf("%s\n", "odd");
    }
    else if (c % 2 == 0)
    {
        printf("%s\n", "even");
    }
    else
    {
        printf("%s\n", "odd");
    }//

I did solve this problem. if...else if...It's not "else", but "ifelse", "ifelse", "ifelse", "a", "b", and "c", and it'll work out. Maybe I don't understand the if statement yet.Why is there a difference? The way they use it is different, but isn't it the same?

c if문 if-else

2022-09-21 10:09

1 Answers

Yes, it's different.

For a rough architecture

if (){
    // Execute
}
else if () {
    // Execute
}
// Else if blocks can exist multiple times
else{
    // Execute
}

Verify that the given condition is true in the first if statement. If true, do the codes in the corresponding if block and end the if statement.

The else if statement checks whether the given condition is true if the condition of the if (or else if) statement right above is false, and if true, it performs the codes in the block and ends the if statement.

For the last else, execute the code if and all the conditions identified in else if above are false.

So if you create conditions with if and else if like the code you posted, only one of those blocks will be executed.

Writing multiple if~else~ means that you consider the conditions of each if statement separately.

Run the first if~else~ and then check the new conditions regardless of whether you performed if or else.

I explained it for a long time, but if you apply it to the question you posted,

In the code you uploaded, a will be an even number or an odd number, and in that case, only one of the first two print statements is executed and the conditions below are finished without checking at all.

Because elseif performs the task of checking conditions if all of the above conditions are false.

Therefore, it only executes a print statement that checks whether a is even or odd.


2022-09-21 10:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.