Multiplication Table with For loop in R
R Programming: Control Structure Exercise-6 with Solution
Write a R program to print the multiplication table of a given number using a for loop.
Sample Solution :
R Programming Code :
# Define a function to print the multiplication table of a given number
print_multiplication_table <- function(number) {
# Print the header
cat("Multiplication table of", number, "is:\n")
# Iterate through numbers from 1 to 10
for (i in 1:10) {
# Calculate the product
product <- number * i
# Print the multiplication table entry
cat(number, "x", i, "=", product, "\n")
}
}
# Test the function with an example input
number <- 10 # Example number to print its multiplication table
print_multiplication_table(number)
Output:
Multiplication table of 10 is: 10 x 1 = 10 10 x 2 = 20 10 x 3 = 30 10 x 4 = 40 10 x 5 = 50 10 x 6 = 60 10 x 7 = 70 10 x 8 = 80 10 x 9 = 90 10 x 10 = 100
Explatnaion:
In the exercise above,
- The code defines a function named "print_multiplication_table()" using the function() keyword. This function takes one parameter 'number', which represents the number whose multiplication table will be printed.
- Print the header:
- Inside the function, a header message is printed using "cat". This message indicates that the following output represents the multiplication table of the given number.
- Iterate Through Numbers:
- The code uses a for loop to iterate through numbers from 1 to 10 (1:10).
- For each iteration, the loop variable 'i' takes on the values from 1 to 10.
- Calculate the product:
- Within the loop, the product of the given 'number' and the current loop variable 'i' is calculated and stored in a variable named 'product'.
- Print the Multiplication table entry:
- Using 'cat', each entry of the multiplication table is printed in the format "number x i = product", where 'number' is the given number, i is the current iteration value, and 'product' is the calculated product.
- Test the Function:
- Outside the function, an example input 'number' is specified (in this case, number is set to 10).
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Check Prime number with While loop in R.
Next: Fibonacci nth term with Recursion in R.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics