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. # input the numbers and converting # finding sum # printing the result 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: Second run: Ruby Program to Sum of All Even Numbers =begin sum=0 puts "Enter number to calculate sum of even numbers:" i=1 puts "The sum of even numbers below #{n} is #{sum}" Output:
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
# them into integer
puts "Enter first value: "
num1=gets.chomp.to_i
puts "Enter second value: "
num2=gets.chomp.to_i
sum=num1+num2
puts "The sum is #{sum}"
Enter first value:
123
Enter second value:
234
The sum is 357
Enter first value:
-123
Enter second value:
100
The sum is -23
Ruby program to calculate the sum of even numbers upto n
=end
n=gets.chomp.to_i
while(i<=n)
if(i%2==0) #using % operator
sum=sum+i
i=i+1
else
i=i+1
end
end
How to Replace array elements in Ruby?
Ruby program to check whether the given number is palindrome
How to Get Input with Gets in Ruby
Ruby program to generate random numbers
Ruby program to Calculate the factorial of given number
How to Sort Array in Ruby?
Ruby program to reverse a string
Ruby program to add two integer numbers
What are #method_missing and #send? Why are they useful?
Ruby program to check whether the given number is prime or not
How to get index of array element in Ruby
What's the difference between a lambda, a block and a proc?
Program to Print Triangle of Numbers in Ruby
Ruby program to check whether the given number is Armstrong
Ruby program to print Fibonacci series
What are the various Ruby runtimes, and how are they different?
Ruby program to print an array
How to create two dimensional array in ruby?
Creating Array with Array.new(size, obj) in Ruby
How to add/remove elements to Array in Ruby?
What are some of your favorite gems? What are their alternatives?
How to shuffle an array in Ruby?
how to create an array with Array.[](*args) in Ruby ?