Home / Programs / write a program that accepts an integer from a user and determine wheather it is an odd or even number. The program should validate the input and display an appropriate message to the user if the input is of wrong type, in which case the user should re-enter the integer until the input is correct.
Programming Example

write a program that accepts an integer from a user and determine wheather it is an odd or even number. The program should validate the input and display an appropriate message to the user if the input is of wrong type, in which case the user should re-enter the integer until the input is correct.

👁 1,448 Views
💻 Practical Program
📘 Step by Step Learning
write a program that accepts an integer from a user and determine whether it is an odd or even number. The program should validate the input and display an appropriate message to the user if the input

Program Code

#include<stdio.h> 
int main(){
int b=0;

while(1)
{
 int number ;
 printf("Enter a Number:  ");
 scanf("%d",&number);
    if(number%2==0)
    {
        printf("%d is a even number\n", number);
        b=1; 
    }
    else
    {
       printf("%d is a odd number \n ",number);
    }
    if(b==1)
    {
	break;
	}
 }
}

Output

<b>Outpu 1:</b>
Enter a Number:  5
5 is a odd number
 Enter a Number:  9
9 is a odd number
 Enter a Number:  7
7 is a odd number
 Enter a Number:  4
4 is a even number
Press any key to continue . . .

<b>Outpu 2:</b>
Enter a Number:  6
6 is a even number
Press any key to continue . . .

<b>Outpu 3:</b>
Enter a Number:  11
11 is a odd number
 Enter a Number:  19
19 is a odd number
 Enter a Number:  16
16 is a even number
Press any key to continue . . .

Explanation

Here we used a while loop for a infinite time, when user will enter a even nubmber, the value of b will be set and by the break condition the flow of the program goes out of the loop.

b = 0;
while(1)
{
 
    if(b==1)
     {
	break;
     }
 
}

To check odd even we used here % operator inside if condition

if(number%2==0)

If the condition will true, we printed that, the number which is entered by the user is a even number, and it will set b=1 to break the loop.

    if(number%2==0)
    {
        printf("%d is a even number\n", number);
        b=1; 
    }

If the condition will false then, we printed that, the number which is entered by the user is a odd number, and the give option to re-enter a another number using while loop.

    else
    {
       printf("%d is a odd number \n ",number);
    }

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.