Q:

# Ruby program to print multiplication table of a number

This requires a very simple logic where we only have to multiply the number with digits from 1 to 10. This can be implemented by putting the multiplication statement inside a loop. We have mentioned two ways: one is by using while loop and the second one is by making use of for loop. When you are using while loop, first you will have to initialize i with 1 and increment it by 1 inside the loop. for loop, the method is simpler as it only requires the specification of for keyword along with the range on which the loop is going to work.

Methods used:

• puts: This is a predefined method which is used to put the string on the console.
• gets: This is also a predefined method in Ruby library which is used to take input from the user through the console in the form of string.
• *: This is an arithmetic operator commonly known as multiplication operator which takes two arguments and process them by giving out their product as a result.

Variables used:

• num: This variable is used to store the integer provided by the user.
• mult: This is storing the result for i*num.
• i: This is a loop variable which is initialized by 1.

### Ruby code to print multiplication table of a number

``````=begin
Ruby program to print multiplication table of
a number(by using for loop)
=end

puts "Enter the number:"
num=gets.chomp.to_i

for i in 1..10
mult=num*i
puts "#{num} * #{i} = #{mult}"
end
``````

Output

```Enter the number:
13
13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130
```

Method 2:

``````=begin
Ruby program to print multiplication table of a
number(by using while loop)
=end

puts "Enter the number:"
num=gets.chomp.to_i

i=1
while (i<=10)
mult=num*i
puts "#{num} * #{i} = #{mult}"
i+=1
end
``````

Output

```Enter the number:
16
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160
```

Code explanation:

The logic of code is pretty simple. In the first method, we are using while loop for the process and in the second one, we are using for loop. We have a variable mult in which we are multiplying the number with the i. The loop will terminate when i becomes equal to 10.