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.

C Programming Language / Loop control in C Language

1332

Program:

#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:

Outpu 1:
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 . . .

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

Outpu 3:
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);
    }

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.