-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex22 - User Defined Functions.rb
63 lines (53 loc) · 1.26 KB
/
ex22 - User Defined Functions.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# User Define Functions
# Function to say Hello to person
def say_hello(name)
return "Hello, #{name}!"
end
# Function to Square of Number
def square(x)
return x * x
end
# Function to calculate the sum of two numbers
def add(a, b)
return a + b
end
# Function to calculate the sub of two numbers
def sub(a, b)
return a - b
end
# Function to check if a number is even
def is_even(number)
return number % 2 == 0
end
# Function to check if a number is odd
def is_odd(number)
return number % 2 != 0
end
# Function to calculate the factorial of a number(Recursion)
# function calls itself in order to solve smaller instances of
# the same problem until it reaches a base case, where the solution can be
# determined directly without further recursion. Recursion is often used
# to solve problems that can be broken down into smaller, similar subproblems.
def factorial(n)
if n == 0
return 1
else
return n * factorial(n-1)
end
end
# Function to find the maximum of two numbers
def max_number(a, b)
if a > b
return a
else b
end
end
# Calling the functions
puts say_hello("Ahmed")
puts square(5)
puts add(2, 5)
puts sub(10, 5)
puts is_even(6) # Boolean (True or False)
puts is_odd(5) # Boolean (True or False)
puts factorial(5)
puts max_number(99, 909)