Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Program to determines even or odd

Write a program that takes an integer N as input and determines whether it is even or odd.

Program in C

C
#include <stdio.h>

int main() {
    int N;

    printf("Enter an integer: ");
    scanf("%d", &N);

    if (N % 2 == 0) {
        printf("%d is even.\n", N);
    } else {
        printf("%d is odd.\n", N);
    }

    return 0;
}

Explanation:

  • In this program, we prompt the user to enter an integer N using printf and then read the input using scanf.
  • We use the modulo operator % to check if N is divisible by 2.
  • If the remainder is 0, it means N is even, and we display the corresponding message.
  • Otherwise, if the remainder is 1, it means N is odd, and we display the corresponding message.
  • Finally, we return 0 to indicate successful execution of the program.

Output:

Output
Enter an integer: 4
4 is even.

Program in Java

Java
import java.util.Scanner;

public class CheckEvenOdd {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int N = scanner.nextInt();

        if (N % 2 == 0) {
            System.out.printf("%d is even.\n", N);
        } else {
            System.out.printf("%d is odd.\n", N);
        }

        scanner.close();
    }
}

Explanation:

  1. The program starts by importing the Scanner class from the java.util package. The Scanner class allows us to read input from the user.
  2. The program defines a public class named CheckEvenOdd.
  3. Inside the class, the program defines the main method, which serves as the entry point of the program.
  4. Within the main method, an instance of the Scanner class is created by initializing it with System.in, which represents the standard input stream (keyboard input).
  5. The program prompts the user to enter an integer by printing the message “Enter an integer: ” to the console using System.out.print().
  6. The entered integer is read from the user using the nextInt() method of the Scanner class. It reads the next integer from the input stream and stores it in the variable N.
  7. The program then checks if the entered integer N is even or odd by using the modulo operator %. If N is divisible by 2 (i.e., the remainder is 0), it means N is even.
  8. If N is even, the program prints the message “%d is even.\n”, where %d is a placeholder for the integer value N. The printf() method is used to format the output.
  9. If N is not even (i.e., the remainder is not 0), it means N is odd. In this case, the program prints the message “%d is odd.\n” using printf().
  10. Finally, the scanner object is closed using the close() method to release system resources associated with the Scanner object.
Output
Enter an integer: 4
4 is even.