For a better understanding of this C program example, we always recommend you to learn the basic topics of C programming listed below:
This C program is to check whether a number is an odd or even number. The logic behind this program is to divide the number by two until it cannot be further divisible, and check for the remainder and see if it is zero or one. For checking this in C language, we use the "MOD operator" which divides the number with 2 until it cannot be further divisible. Finally, if the remainder is one the given number is odd else even.
The user has to input an Integer using printf
and scanf
statements. Now we use the Mod operator to check the remainder whether zero or one and print the output. Let's take some simple examples to understand more about this.
Let the entered value be 'a' = 5. According to the logic, we described the program if '(a%2 = 0)',then a is an even number otherwise odd. Here 'a = 5',then we have (5%2 not equal to zero),so the given number is odd
Let entered value 'a = 6'. In accordance with the program if (a%2 == 0),then a is an even number otherwise odd. Here 'a = 6',then we have (6%2 = 0),so the given number is even.
Let us check how we have implemented this logic in C, after importing the header libraries we accept the number from the user and save that into a variable. After that, we use the mod operator to divide the number by 2 and check if the remainder is zero or not using 'if
operator'. If the remainder is zero then print its an even number else it's an odd number.
STEP 1: Import the header libraries into the C program to use the built-in Functions.
STEP 2: Start the main() to start the execution of the program,
STEP 3: Initialize the variables for the remainder and user input values using int
datatype.
STEP 4: Accept the number from the user using printf
and scanf
and save that in a variable.
STEP 5: Use the mod operator with 2 and store the value of the remainder in a variable.
STEP 6: Use the if condition to check the remainder is zero or not. if the remainder is zero then print its an even number, else print its an odd number.
#include <stdio.h>
void main() {
int ival, remainder;
printf("Enter an integer :");
scanf("%d", & ival);
remainder = ival % 2;
if (remainder == 0)
printf("%d, is an even integer\n", ival);
else
printf("%d, is an odd integer\n", ival);
}
Enter an integer:13 13, is an odd integer RUN2 Enter an integer:24 24, is an even integer