Home > database >  do while loop. C program
do while loop. C program

Time:12-10

I dont know what is wrong with my program. Whenever I try the output it only prints the It is the season of Winter, I don't know how to fix this.

int main() {
    int answer = 1;
    int mon;

    do {
        printf("Input a month : ");
        scanf("%d", &mon);

        if (mon == 1 || 2 || 12)
            printf("It is the season of winter\n\n\n");
        
        if (mon == 3 || 4 || 5) 
            printf("It is the season of spring\n\n\n");
        
        if (mon == 6 || 7 || 8)
            printf("It is the season of summer\n\n\n");
        
        if (mon == 9 || 10 || 11)
            printf("It is the season of fall\n\n\n");
        
        printf("Would you like to try again? (1= YES / 0= NO) : ");
        scanf("%d", &answer);
    
    } while (answer !=0);
    
    printf("\n\n\n");
}

CodePudding user response:

The conditions in the if statements are incorrect.

For example let's consider this if statement

if (mon == 1 || 2 || 12)

It is equivalent to

if ( ( mon == 1 ) || ( 2 ) || ( 12 ) )

So as the second and the third operands of the logical OR operators are not equal to 0 then the condition always evaluates to logical true.

From the C Standard (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

You need to write

if (mon == 1 || mon == 2 || mon == 12)

Also instead of the series of if statements it would be better to write if -else if statements like

    if (mon == 1 || mon == 2 || mon == 12)
        printf("It is the season of winter\n\n\n");
    
    else if (mon == 3 || mon == 4 || mon == 5) 
        printf("It is the season of spring\n\n\n");
    
    else if (mon == 6 || mon == 7 || mon == 8)
        printf("It is the season of summer\n\n\n");
    
    else if (mon == 9 || mon == 10 || mon == 11)
        printf("It is the season of fall\n\n\n");

In this case for example if the expression of the first if statement evaluates to true all other if statements will be skipped. That is in this case you can avoid redundant evaluations of expressions of the if statements.

CodePudding user response:

The code in the question should print all four seasons because all tests evaluate to true:

if (mon == 1 || 2 || 12)

evaluates the first condition mon == 1 which is only true for January, then for other months it evaluates 2 which is non zero, hence true, so the whole condition is true and It is the season of winter is printed. The same happens for all four tests.

You should write this instead:

if (mon == 1 || mon == 2 || mon == 12)
  • Related