Check Whether a Number is Even or Odd in C

Exercise:

Write a C Program to check whether a number is even or odd.

1. Check using If-Else

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);

    //Condition to check if integer is divisible by 2
    if(num % 2 == 0) {
        printf("%d is EVEN.", num);
    }
    else {
        printf("%d is ODD.", num);
    }
    return 0;
}
Click Here to View the Output!
Enter an integer: 6
6 is EVEN.
Click Here to View the Explanation!
  • This program is used to determine whether a number is even or odd.
  • In the main method, the program requests the user to enter a number and stores it in the variable num using the scanf() function.
  • An if…else statement is used which will state that if num is exactly divisible by 2 i.e. the % modulus of num with 2 is equal to 0, then print the message num is even.
  • Else, print the message num is odd.
  • The return 0 statement is used to exit the program execution.

2. Check using Ternary Operator

Click Here to View the Solution!
#include <stdio.h>      
int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    (num % 2 == 0) ? printf("%d is EVEN.", num) : printf("%d is ODD.", num);
    return 0;
}
Click Here to View the Output!
Enter an integer: 6
6 is EVEN.
Click Here to View the Explanation!
  • This program is used to determine whether a number is even or odd using a ternary operator.
  • In the main method, the program requests the user to enter a number and stores it in the variable num using the scanf() function.
  • Instead of using the if…else statement, the program uses a ternary operator (? :) which acts in a similar way.
  • It first checks the condition (num % 2 == 0), if true, the program executes the first statement after the ? that is num is even.
  • If the condition is false, the second statement, after : is executed which is num is odd.
  • The return 0 statement is used to exit the program execution.

%d bloggers like this: