Home » Ruby programming » Ruby programs

Ruby program to add two integer numbers

Adding two numbers in Ruby: Here, we are going to learn how to add two integer numbers in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 06, 2019

Adding two numbers in Ruby

Given/Input two integer numbers and we have to find the addition of the integer numbers in Ruby.

In this problem, we will find out the way to add two integers in Ruby. Adding two numbers is not as easy as it seems because when we use gets method which stands for getting string, we get the value in the string. We will not get the appropriate result if we add those values.

Methods used:

  • 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: When we take input through gets method, it is a string. For further calculations, it is mandatory to convert it into an integer for exact results and this method returns the integer conversion of the given string.
  • +: It is a mathematical operator which accepts two numerical parameters and returns a numerical value. A binary operator to add two values.

Variables used:

  • num1: To store the first value
  • num2: To store the second value
  • sum: To store the sum i.e. result

Ruby code to add two integer numbers

=begin 
Ruby program to add two numbers.
=end

# 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}"

Output

First run:
Enter first value:
123
Enter second value:
456
The sum is 579

Second run:
Enter first value:
-120
Enter second value:
20
The sum is -100

Code explanation:

This program is to add two integer values and print the sum of these entered numbers. It takes two integers as input and stored them to variables, num1 and num2. Then using the + (arithmetic operator) to store the sum of these variables into the sum and stores this sum and then the puts method prints the sum value with the print statement The sum is $sum.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.