Introduction
Generating a multiplication table is a common exercise in programming, often used to practice loops and iteration. In R, you can generate a multiplication table for any given number using a for
loop. This guide will walk you through writing an R program that generates and displays the multiplication table for a user-specified number.
Problem Statement
Create an R program that:
- Prompts the user to enter a number.
- Uses a
for
loop to generate the multiplication table for the given number. - Displays the multiplication table.
Example:
- Input: Number:
5
- Output: Multiplication table for
5
from1
to10
.
Solution Steps
- Prompt the User for Input: Use the
readline()
function to take a number as input from the user. - Generate the Multiplication Table: Use a
for
loop to iterate through the numbers1
to10
and calculate the products. - Display the Multiplication Table: Use the
print()
function to display the results.
R Program
# R Program to Generate Multiplication Table Using for Loop # Step 1: Prompt the user to enter a number number <- as.numeric(readline(prompt = "Enter a number: ")) # Step 2: Generate and display the multiplication table using a for loop print(paste("Multiplication Table for", number, ":")) for (i in 1:10) { result <- number * i print(paste(number, "x", i, "=", result)) }
Explanation
Step 1: Prompt the User to Enter a Number
- The
readline()
function prompts the user to enter a number, which is then converted to a numeric value usingas.numeric()
and stored in the variablenumber
.
Step 2: Generate and Display the Multiplication Table Using a for Loop
- The program uses a
for
loop to iterate through the numbers1
to10
. - For each iteration, the loop calculates the product of
number
and the loop variablei
. - The
print()
function is used to display the result of each multiplication in the format:number x i = result
.
Output Example
Example:
Enter a number: 5 [1] "Multiplication Table for 5 :" [1] "5 x 1 = 5" [1] "5 x 2 = 10" [1] "5 x 3 = 15" [1] "5 x 4 = 20" [1] "5 x 5 = 25" [1] "5 x 6 = 30" [1] "5 x 7 = 35" [1] "5 x 8 = 40" [1] "5 x 9 = 45" [1] "5 x 10 = 50"
Example with a Different Number:
Enter a number: 7 [1] "Multiplication Table for 7 :" [1] "7 x 1 = 7" [1] "7 x 2 = 14" [1] "7 x 3 = 21" [1] "7 x 4 = 28" [1] "7 x 5 = 35" [1] "7 x 6 = 42" [1] "7 x 7 = 49" [1] "7 x 8 = 56" [1] "7 x 9 = 63" [1] "7 x 10 = 70"
Conclusion
This R program demonstrates how to generate a multiplication table using a for
loop. It covers essential concepts such as user input, loops, and basic arithmetic operations. Generating a multiplication table is a useful exercise for understanding loops and iteration, making this example valuable for beginners learning R programming.