i

R Programming Complete Tutorial

R for loop

Loop Operation

Loops are one of the most basic and powerful programming concepts. A loop is an instruction that repeats until a specified condition is reached. In a loop structure, it asks a question. If the answer requires action, it is executed. It may continue until no further action is required. In R programming, the environment we use for, while, and repeat for loop operation. Now we will follow them one by one.

In every section, we will start with basic syntax, then learn the flow diagram and finally finish with an example.

for loop

Let's begin with for loop. A for loop is useful when iterating over a list of elements or a range of numbers. This loop can be used to iterate over a vector, matrix, list, data frame, or any other object.

Flow Diagram:

Initially, for loop takes a sequence expression. In each iteration, this will be evaluated statement. This flow diagram will tell the same graphically.

A code may contain some initial expression, and then it checks the condition or test expression. If this is true, it will go to the main for loop body, then return to test expression. It will continue until the test result is true. In case of FALSE, it will exit the loop.

Syntax:

Example:

In this example, we will print the addition of a series of 1 to 100.

First, we initialize 0 to sum.

This for loop will start from 1, and the exit criteria is i= 100. In the first iteration sum=0, i=1, after the addition, the sum will be updated to 1. The second iteration, sum 1, i=2, the sum will store 3. In the next iteration, sum 3, i=3, the sum will be updated with 6. It will continue until i is 100.