Monday 26 October 2015

C LANGUAGE PROGRAM TO DECIDE EITHER NUMBER IS ODD OR EVEN

WRITE A PROGRAM THAT TAKES INPUT FROM USER, AND DECIDE EITHER THIS NUMBER IS EVEN OR ODD

#include<stdio.h>       // Header file  “Standard Input and Output”
#include<conio.h>      //Header file “Console input and output”
void main ()
{
            clrscr();                                                // Clear the output screen
            int number, remainder;                        // Variable declaration
            printf(“Enter any number = “);           // Display prompt for number
            scanf(“%d”,&number);                       // Take input from user
           
            remainder = number % 2;                    // Divide the number with 2, and calculate the remainder
            if (remainder == 0)                              // Decide if remainder is zero its mean it is an even number
                        printf(“This number is even”);           
            else                                                      // otherwise if the remainder is 1, it is an odd number
                        printf(“This number is odd”);

getch();
}

OUTPUT

Enter any number = 24
The number is even

Enter any number = 57
The number is odd

EXPLANATION

The logic I have used in this program is that I did not divide the number by 2, but I have taken the remainder of the input number. You know that even numbers are fully divided by 2 and the remainder becomes zero (0), and if the number is odd the remainder becomes always 1.


This remainder is then used to take decision that when the remainder will be zero, it is even number and if the remainder is 1 the number will be odd. 

No comments:

Post a Comment