Ruby Program to Check Even or Odd Number
In Ruby, you can check if a number is even or odd using
number.even? or number.odd? methods. For example, puts 4.even? ? 'Even' : 'Odd' prints 'Even'.Examples
Input4
OutputEven
Input7
OutputOdd
Input0
OutputEven
How to Think About It
To check if a number is even or odd, think about dividing it by 2. If the number divides evenly with no remainder, it is even; otherwise, it is odd. Ruby provides simple methods to check this directly.
Algorithm
1
Get the input number.2
Check if the number is divisible by 2 without remainder.3
If yes, print 'Even'.4
Otherwise, print 'Odd'.Code
ruby
puts 'Enter a number:' number = gets.to_i if number.even? puts 'Even' else puts 'Odd' end
Output
Enter a number:
4
Even
Dry Run
Let's trace the input 4 through the code
1
Input number
User enters 4, stored in variable number = 4
2
Check even?
4.even? returns true because 4 % 2 == 0
3
Print result
Since true, prints 'Even'
| Step | number | number.even? | Output |
|---|---|---|---|
| 1 | 4 | true | Even |
Why This Works
Step 1: Getting input
We ask the user to enter a number and convert it to an integer with gets.to_i.
Step 2: Checking evenness
The even? method returns true if the number divides by 2 with no remainder.
Step 3: Printing result
If even? is true, we print 'Even'; otherwise, we print 'Odd'.
Alternative Approaches
Using modulo operator
ruby
puts 'Enter a number:' number = gets.to_i if number % 2 == 0 puts 'Even' else puts 'Odd' end
This uses the modulo operator to check remainder; it is more manual but works the same.
Using ternary operator
ruby
puts 'Enter a number:' number = gets.to_i puts number.even? ? 'Even' : 'Odd'
This is a shorter way using a one-line conditional expression.
Complexity: O(1) time, O(1) space
Time Complexity
Checking if a number is even or odd is a simple arithmetic operation that takes constant time.
Space Complexity
The program uses a fixed amount of memory regardless of input size.
Which Approach is Fastest?
Using even? or modulo operator both run in constant time; even? is more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using even? method | O(1) | O(1) | Readability and simplicity |
| Using modulo operator | O(1) | O(1) | Manual control and understanding basics |
| Using ternary operator | O(1) | O(1) | Concise code for simple checks |
Use Ruby's built-in
even? and odd? methods for clear and simple checks.Beginners often forget to convert input to integer with
to_i, causing errors when checking even or odd.