Write a program which, given a positive integer n, returns 1 if n is even and 0 if n is odd

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int is_even(int n);

int main(int argc, char **argv) {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    if(is_even(number))
        printf("EVEN\n");
    else
        printf("ODD\n");
    return 0;
}

int is_even(int n) {

    if(n%2 == 0)
        return 1;
    else
        return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Enter a positive integer: 4
EVEN

Brief Explanation

  • The function is_even checks if the number inputted by the user is even or not.
  • It returns 1 if the number is even and 0 otherwise (odd).
  • If the remainder when a number, n is divided by 2 is zero, then that number is even.

Add comment


Security code
Refresh