Control structures are divided into 2 types :
if-else Family statements.for loop, while loop etc.if-else Familyif, if-else and if-elseif-else are a family of constructs where
if ConstructSyntax :
if(condition){
statements..
}
if-else ConstructSyntax :
if(condition){
statements
} else{
alternate statements
}
if-elseif-else ConstructSyntax :
if(condition){
statements
} else if(condition){
alternate statements
} else{
alternate statements
}
Example :
Let’s write the R-code for the following problem :
- If \(x\) is greater than \(7\),then, operations within the curved braces will occur. - Else the next condition,i.e., \(x>8\) would be checked and if this is not true - Final else condition is checked and if that too is false, then, there will be no change is \(x\).
Let’s assume the initial value of \(x=6\). So, the code would be :
x = 6
if(x>7){
x = x+1
}else if(x>8){
x=x+2
}else{
x = x+3
}
print(x)
## [1] 9
for Loop ConstructThe structure of a for loop construct comprises :
iter is an element of the sequenceBefore understanding the for loop, we first need to understand the Sequence function.
for loop.seq(from, to, length)
The sequence function creates an equi-spaced points between from and to - from : Starting Number - to : Ending Number - by : Increment/Decrement (width) - length : Number of elements required
Example :
seq(from = 1, to = 10, by = 2)
## [1] 1 3 5 7 9
seq(from = 1, to = 10, length = 4)
## [1] 1 4 7 10
for LoopSyntax :
for(iter in sequence){
statements
}
for LoopWhen one or, more for loop constructs are located within one another then, its known as “Nested for Loop”
Syntax :
for(iter_1 in sequence_1){
for(iter_2 in sequence_2){
statements
}
}
Example :
n = 5
sum = 0
for(i in seq(1,n,1)){
sum = sum + i
print(c(i,sum))
}
## [1] 1 1
## [1] 2 3
## [1] 3 6
## [1] 4 10
## [1] 5 15
for Loop with if-breakA break statement once executed, program exits the loop even before the iterations are complete.
break command comes out of the innermost loop for nested loops.
Example : Let’s say we want to terminate the looping when sum is greater than \(15\) :
n = 100
sum = 0
for (i in seq(1,n,1)){
sum = sum + i
print(c(i, sum))
if(sum >= 15){
break
}
}
## [1] 1 1
## [1] 2 3
## [1] 3 6
## [1] 4 10
## [1] 5 15
While LoopA while loop is used whenever we want to execute statements until a specific condition is violated.
Example : Consider a sequence of natural numbers.
What is the value of the natural number up to which the calculated sum is less than the specified Fin_sum ?
1+2+3+…..+n = Fin_sum(15)
sum = 0
i = 0
Fin_sum = 15
while(sum < Fin_sum){
i = i+1
sum = sum+i
print(c(i,sum))
}
## [1] 1 1
## [1] 2 3
## [1] 3 6
## [1] 4 10
## [1] 5 15