Ruby program to add two integer numbers

Adding two numbers in Ruby

To add numbers in ruby we will use below methods

puts: This method is used to display some message to the user.
gets: This method is used to take input from the user.
.to_i: Convert String to Integer.
+: It is a mathematical operator which accepts two numerical parameters and returns a numerical value. A binary operator to add two values

 

# input the numbers and converting 
# them into integer 
puts "Enter first value: "
num1=gets.chomp.to_i
puts "Enter second value: "
num2=gets.chomp.to_i

# finding sum 
sum=num1+num2

# printing the result
puts "The sum is #{sum}"

 

Code Explantion:

Step 1: User Enter the first number and assign it to num1

Step 2: User Enter the second number and assign it to num2

Step 3: By using the addition operator "+" we will add num1+num2 and assign the result value to sum

Step 4: Print the addition of two numbers as sum

 

Output

First run:
Enter first value:
123
Enter second value:
234
The sum is 357

Second run:
Enter first value:
-123
Enter second value:
100
The sum is -23

 

 

Ruby Program to Sum of All Even Numbers

 

=begin
Ruby program to calculate the sum of even numbers upto n
=end

sum=0

puts "Enter number to calculate sum of even numbers:"
n=gets.chomp.to_i

i=1
while(i<=n)
    if(i%2==0)     #using % operator
        sum=sum+i
        i=i+1
    else
        i=i+1
    end
end

puts "The sum of even numbers below #{n} is #{sum}"

 

Output:

The sum of even numbers below 24 is 156