while loop in R
While loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the while loop checks for the condition before entering the body of the loop.
R- While loop Syntax:
while (test_expression) {
statement
update_expression
}
- Control falls into the while loop.
- The flow jumps to Condition
- Condition is tested. If the Condition yields true, the flow goes into the Body.
- If the Condition yields false, the flow goes outside the loop
- The statements inside the body of the loop get executed.
- Updation takes place.
- Control flows back to Step 2.
- The while loop has ended and the flow has gone outside.
- It seems to be that while the loop will run forever but it is not true, condition is provided to stop it.
- When the condition is tested and the result is false then the loop is terminated.
- And when the tested result is True, then the loop will continue its execution.
# while loop example
#print mec 5 time
i=1
while (i<5){
print("mec")
i=i+1
}
output:
[1] "mec"
[1] "mec"
[1] "mec"
[1] "mec"
# while loop example
#sum of the digits of a number
n=5432
s=0
while (n!=0){
d=n%%10
s=s+d
n=n%/%10
}
print(paste("sum of digits=",s))
output:
"sum of digits= 14"
Comments
Post a Comment