while loop : In R, a while loop iterates as long as a specified condition evaluates to TRUE. Here’s the general syntax:
while (logical_expression) { #Body of the loop }
Explanation:
logical_expression: This is a logical condition. As long as this condition isTRUE, the loop continues to execute. If it becomesFALSE, the loop terminates.Body of the loop: This is the code block that executes repeatedly as long as the condition remainsTRUE

Now, let’s explain what this program does:
This R program initializes a variable called number with the value 1. Then, it enters a while loop with the condition number < 5, meaning the loop will continue executing as long as the value of number is less than 5.
Within the loop:
- The current value of number is printed using the print() function.
- number is incremented by 1 using the statement number <- number + 1.
The loop continues to execute until the value of number becomes 5 or greater. At that point, the condition number < 5 becomes FALSE, and the loop terminates.
In summary, this program prints the numbers 1, 2, 3, and 4, each on a separate line, because those are the values of number before it reaches 5.
for Loop : In R, a for loop iterates over a sequence of values. Here’s the general syntax:
for (iteration in sequence) {
# Body of the loop
}
Explanation:
- iteration: This represents the current value in the sequence being iterated over.
- sequence: This is a sequence of values over which the loop iterates.
- Body of the loop: This is the code block that executes repeatedly for each value in the sequence.

Now, let’s explain what this program does:
This R program creates a sequence of numbers from 1 to 5 and stores it in a variable called number using the 1:5 notation. Then, it enters a for loop where the loop variable i iterates over each value in the sequence stored in number.
Within the loop:
- The current value of i is printed using the print() function.
The loop iterates over each value in the sequence 1:5, printing each value in turn. Consequently, the output will display the numbers 1 through 5, each on a separate line.
Leave a comment