w3resource

Printing Numbers from 1 to 10 using For loop in R

R Programming: Control Structure Exercise-1 with Solution

Write a R program that creates a for loop to print numbers from 1 to 10.

Sample Solution :

R Programming Code :

# Initialize a for loop to iterate from 1 to 10
for (i in 1:10) {
    # Print the current value of 'i'
    print(i)
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10                       

Explatnaion:

In the exercise above,

  • for (i in 1:10) {: This line initializes a for loop in R. The loop variable i iterates over the sequence of numbers from 1 to 10, denoted by 1:10.
  • print(i): Within the loop, this line prints the current value of the loop variable i to the console.
  • The loop continues to iterate over the sequence 1:10, printing each value of i from 1 to 10 one by one.
  • Once the loop completes iterating over all values from 1 to 10, the program execution finishes.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: R Programming Control Structure Exercises Home.
Next: Calculate Factorial using While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.