Haskell Program to check the given number is an Odd number using library function


In Haskell, we have library function like, by using Mod and Rem function to check if the given number is odd or not. In the first example, we are going to use (isOdd n = n `mod` 2 /= 0) function and in the second example, we are going to use (isOdd n = (n `rem` 2) == 1) function.

Algorithm

  • Step 1 − The isOdd function is defined using mod function as, isOdd n = n `mod` 2 /= 0.

  • Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. It calls the isOdd function with the value to check if it is Odd or not and prints the result to the console.

  • Step 3 − The variable named, “num” is being initialized. It will hold the value to check if the value is odd or not.

  • Step 4 − The result is printed to the console using ‘putStrLn’ statement after checking the integer.

Example 1

In this example, we are going to see that how we can check if the given number is an odd or not. This can be done by using mod function.

isOdd :: Integral a => a -> Bool
isOdd n = n `mod` 2 /= 0

main :: IO ()
main = do
   let num = 7
   print (isOdd num)

Output

True

Example 2

In this example, we are going to see that how we can check if the given number is an odd or not. This can be done by using mod function. In Haskell, we can use the mod function to check if a number is odd by checking if its remainder when divided by 2 is equal to 1.

isOdd :: Integral a => a -> Bool
isOdd n = n `mod` 2 == 1

main :: IO ()
main = do
   let num = 7
   print (isOdd num)

Output

True

Example 3

In this example, we are going to see that how we can check if the given number is an odd or not. This can be done by using rem function.

import Data.Bits

isOdd :: Integral a => a -> Bool
isOdd n = (n `rem` 2) == 1

main :: IO ()
main = do
   let num = 7
   print (isOdd num)

Output

True

Example 4

In this example, we are going to see that how we can check if the given number is an odd or not. This can be done by using rem function. The function uses the mod function to check if the given number is odd by checking if the remainder of the number divided by 2 is not equal to 0.

isOdd :: Integral a => a -> Bool
isOdd n = n `mod` 2 /= 0

main :: IO ()
main = do
   let num = 7
   print (isOdd num)

Output

True

Conclusion

An odd number is a number that is not divisible by 2. The property of being odd or even is called parity. In Haskell, you can use the modulo operator (mod) to check if a number is odd or even. The modulo operator returns the remainder of the division of the first operand by the second operand. If the remainder is 0, the number is even, otherwise, it's odd. Also, we can use rem function to check if the given number is an odd or not, in Haskell.

Updated on: 13-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements