
Write a program to check whether the given number is even or odd.
Program:
#include <stdio.h>
int main() {
int a;
printf("Enter a: \n");
scanf("%d", &a);
/* logic */
if (a % 2 == 0) {
printf("The given number is EVEN\n");
}
else {
printf("The given number is ODD\n");
}
return 0;
}
Output:
Enter a: 2
The given number is EVEN
Explanation with examples:
Example 1: If entered number is an even number
Let value of 'a' entered is 4
if(a%2==0) then a is an even number, else odd.
i.e. if(4%2==0) then 4 is an even number, else odd.
To check whether 4 is even or odd, we need to calculate (4%2).
/* % (modulus) implies remainder value. */
/* Therefore if the remainder obtained when 4 is divided by 2 is 0, then 4
is even. */
4%2==0 is true
Thus 4 is an even number.
Example 2: If entered number is an odd number.
Let value of 'a' entered is 7
if(a%2==0) then a is an even number, else odd.
i.e. if(7%2==0) then 4 is an even number, else odd.
To check whether 7 is even or odd, we need to calculate (7%2).
7%2==0 is false /* 7%2==1 condition fails and else part is executed */
Thus 7 is an odd number.
|
This page was last modified on 15 Dec 2011 at 19:30:43. |
Gautam Kumar EDP Manager |
» C program to generate the Fibonacci series
» C program to print a semicolon without using a semicolon
» C program to compare two strings without using strcmp
» C program to concatenate two strings without using strcat
» C program to delete a specified line from a text file
» C program to replace a specified line in a text file
» C program to find the number of lines in a text file
» C program which asks the user for a number between 1 to 9
» C program to check whether the given string is a palindrome
» C program to check whether the given number is a palindromic
» C program to find factorial of the given number
» C program to check whether the given number is even or odd
» C program to swap two numbers using a temporary variable
» C program to swap two numbers using bitwise operators
» C program to find the greatest of three numbers
» C program to find the greatest among ten numbers
» C program to check whether the given number is a prime
» How to create pyramid in c
» Fun with C language.
