1. Introduction
Ruby offers a variety of arithmetic operators to perform common mathematical operations. These operators are essential tools when you need to manipulate numeric data, whether they are integers or floating-point numbers.
2. Program Steps
1. Initialize sample variables.
2. Apply and demonstrate the arithmetic operators on the initialized variables.
3. Code Program
# Initialize sample variables
a = 15
b = 4
# Addition
addition_result = a + b
puts "Addition: #{a} + #{b} = #{addition_result}"
# Subtraction
subtraction_result = a - b
puts "Subtraction: #{a} - #{b} = #{subtraction_result}"
# Multiplication
multiplication_result = a * b
puts "Multiplication: #{a} * #{b} = #{multiplication_result}"
# Division
division_result = a.to_f / b.to_f # Convert to float for precise division
puts "Division: #{a} / #{b} = #{division_result}"
# Modulus
modulus_result = a % b
puts "Modulus: #{a} % #{b} = #{modulus_result}"
# Exponentiation
exponentiation_result = a ** b
puts "Exponentiation: #{a} ** #{b} = #{exponentiation_result}"
Output:
Addition: 15 + 4 = 19 Subtraction: 15 - 4 = 11 Multiplication: 15 * 4 = 60 Division: 15 / 4 = 3.75 Modulus: 15 % 4 = 3 Exponentiation: 15 ** 4 = 50625
Explanation:
1. The Addition (+) operator adds two numbers.
2. The Subtraction (-) operator subtracts the right operand from the left.
3. The Multiplication (*) operator multiplies two numbers.
4. The Division (/) operator divides the left operand by the right. Note that integer division will round down the result. For a precise division result, you should convert the numbers to floats.
5. The Modulus (%) operator returns the remainder of the division of the left operand by the right.
6. The Exponentiation () operator raises the number to the power of the right operand.
Comments
Post a Comment