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
Ruby program to check whether the given number is palindrome
how to create an array with Array.[](*args) in Ruby ?
What's the difference between a lambda, a block and a proc?
How to Sort Array in Ruby?
What are some of your favorite gems? What are their alternatives?
How to add/remove elements to Array in Ruby?
Creating Array with Array.new(size, obj) in Ruby
How to Get Input with Gets in Ruby
What are the various Ruby runtimes, and how are they different?
Ruby program to print an array
Ruby program to reverse a string
How to get index of array element in Ruby
Ruby program to Calculate the factorial of given number
Ruby program to check whether the given number is Armstrong
Program to Print Triangle of Numbers in Ruby
How to shuffle an array in Ruby?
How to Replace array elements in Ruby?
Ruby program to print Fibonacci series
Ruby program to check whether the given number is prime or not
How to create two dimensional array in ruby?
What are #method_missing and #send? Why are they useful?
Ruby program to add two integer numbers
Ruby program to generate random numbers