Monday, April 28, 2025

C Program - Check if Number is Even or Odd

 This C program takes an integer as input and checks whether it is an even or odd number.

#include<stdio.h>

int main()
{

    int number;

    printf("Enter an Integer: ");
    scanf("%d",&number);

    if ( number % 2 == 0 )
    {
        printf("%d is an even number", number);
    }
    else
    {
        printf("%d is an odd number", number);
    }

    return 0;
}

Result:

Enter an Integer: 2
2 is an even number
Process returned 0 (0x0)   execution time : 2.739 s
Press any key to continue.

One more time: 

Enter an Integer: 5
5 is an odd number
Process returned 0 (0x0)   execution time : 1.359 s
Press any key to continue.

Let's go through it line by line:

 
#include<stdio.h>

 

This line includes the standard input/output header file.

 
int main()
{

 

This line defines the main function of the program.

 
    int number;

 

This line declares an integer variable number which will store the user input.

 
    printf("Enter an Integer: ");
    scanf("%d",&number);

 

These lines print a message asking the user to enter an integer and read the integer input from the user using the scanf() function. %d is the format specifier used to read an integer input from the user.

 
    if ( number % 2 == 0 )
    {
        printf("%d is an even number", number);
    }
    else
    {
        printf("%d is an odd number", number);
    }

 

This if-else statement checks whether the entered number is even or odd. The % operator calculates the remainder of dividing the entered number by 2. If the remainder is 0, the number is even, and the program prints the message "number is an even number" using the printf() function. If the remainder is not 0, the number is odd, and the program prints the message "number is an odd number" using the printf() function.

 
    return 0;
}

 

This line indicates the end of the main() function and returns 0, indicating that the program has executed successfully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...