Open In App

Shell script to print table of a given number

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore the process of creating a simple yet powerful shell script that takes user input and generates number tables. Number tables are a common mathematical concept used to display the multiples of a given number up to a specified limit. We will illustrate this process with examples for better understanding.

Example:

Input: 5
Output:    5 * 1 = 5
           5 * 2 = 10
           5 * 3 = 15
           5 * 4 = 20
           5 * 5 = 25
           5 * 6 = 30
           5 * 7 = 35
           5 * 8 = 40
           5 * 9 = 45
           5 * 10 = 50
           
Explanation: Here the multiple of 5 are printed.
           

Input: 8
Output:   8 * 1 = 8
          8 * 2 = 16
          8 * 3 = 24
          8 * 4 = 32
          8 * 5 = 40
          8 * 6 = 48
          8 * 7 = 56
          8 * 8 = 64
          8 * 9 = 72
          8 * 10 = 80
          
Explanation: Here the multiple of 8 are printed.          

Here our task is to write a script to take the input integer variable and print its multiples till 10 or simply we can say that the below script prints the table of the input value till its 10th multiple. At the same time, the loop is used to iterate the loop till the 10th multiple. 

#!/bin/bash

# Input from user
echo "Enter the number -"
read n

# initializing i with 1
i=1
  
# Looping i, i should be less than
# or equal to 10 
while [ $i -le 10 ]
do
res=`expr $i \* $n`

# printing on console
echo "$n * $i = $res"
 
# incrementing i by one  
((++i))
  
# end of while loop  
done

Output:

Bash Script output

Bash Script output

The following screenshot of the test case of the code is executed, it accepts the input data from the user. The input will be in integer format and then print the desired table.


Last Updated : 31 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads