How to know if a number is EVEN or ODD in programming

Introduction

In this article we will see how to tell if an integer is odd or even using programming. We solve the algorithm in C# language for Unity.

An even number is a number that is a multiple of 2, that is we can express that number as 2 multiplied by another number and the whole expression will be equivalent. An odd number is a number that is not a multiple of 2.

It can also be said that an even number is divisible by 2, meaning that when you divide the number by 2 the remainder of the division is 0, whereas division between an odd number and 2 will always have remainder 1. We can use this fact to create an algorithm that checks whether a number is odd or even.

Prepare the scene for testing

To test the code to verify if an integer is odd or even we’ll create a script with any name, in my case I used “EvenOrOdd”, then we create an empty GameObject in the hierarchy (figure 1) and assign that script in the inspector (figure 2), that way when we enter the game mode the script will run and we can test the code.

Fig. 1: Creating an Empty GameObject in the hierarchy in Unity
Fig. 2: Assigning the script to the GameObject

Module Operator

The module operator allows us to know how much the rest is worth when making a division.

Let’s consider a division operation between two integers, for example 5 divided by 3, the integer result of this division is 1 and the rest of the division is 2, we can see that: 3 x 1 + 2 = 5.

Then, taking into account what we said in the introduction about even numbers and divisibility by 2, if we apply the operation module 2 to any number and the result is equal to 0, we can say that the number is divisible by 2 and consequently is an even number. If the result is not 0, then the number is odd.

The programming of this algorithm can be seen below in figure 3, in line 10 a random number between 0 and 100 is generated, then in line 12 we make this check if the module 2 of that number is equal to 0 and we assign that logical result to the logic variable “esPar”. Finally, using the if statement, we check if the condition is true or false and print a message according to each case.

algoritmo para saber si un numero entero es par o impar en lenguaje c# en unity
Fig. 3: Algorithm to know if an integer is odd or even in C#, Unity.

When entering the game mode, the code defined in the Start method is executed, in figures 4 and 5 you can see two different executions of this algorithm, one for an even number and another for an odd number.

Fig. 4: Console message indicating that the generated number is even.
Fig. 5: Console message indicating that the generated number is odd.

Scroll to Top
Secured By miniOrange