
R programming language provides the following kinds of loop to handle looping requirements.
for loop
- Like a while statement, except that it tests the condition at the end of the loop body.
while loop
- Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
repeat loop
- Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
In [6]:
for (i in 1:10)
{
print(i)
}
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10
In [35]:
for (i in 1:10)
{
cat(paste(i,""))
}
1 2 3 4 5 6 7 8 9 10
In [27]:
a=1
while (a <= 10)
{
print(a)
a = a + 1
}
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10
In [ ]:
a=1
while (a <= 10)
{
cat(paste(a,""))
a = a + 1
}
In [37]:
s="Itronix Solutions"
count = 1
repeat
{
print(s)
count = count+1
if(count > 5)
{
break
}
}
[1] "Itronix Solutions" [1] "Itronix Solutions" [1] "Itronix Solutions" [1] "Itronix Solutions" [1] "Itronix Solutions"
In [2]:
n=as.integer(readline(prompt="Enter Number: "))
s=0
for(i in 1:n)
{
s=s+i
}
print(s)
Enter Number: 10 [1] 55
In [4]:
n=as.integer(readline(prompt="Enter Number: "))
f=1
for(i in 1:n)
{
f=f*i
}
print(paste("Factorial:",f))
Enter Number: 5 [1] "Factorial: 120"
In [5]:
n=as.integer(readline(prompt="Enter Number: "))
mod=0
while(n!=0)
{
m=n%%10
n=n%/%10
mod=mod+m
}
print(mod)
Enter Number: 123 [1] 6
In [7]:
n=as.integer(readline(prompt="Enter Number: "))
rev=0
while(n!=0)
{
m=n%%10
n=n%/%10
rev=rev*10+m
}
print(rev)
Enter Number: 123 [1] 321
In [10]:
n=as.integer(readline(prompt="Enter Number: "))
org=n
rev=0
while(n!=0)
{
m=n%%10
n=n%/%10
rev=rev*10+m
}
if(org==rev)
{
print("No is Palindrome")
}else
{
print("No is Not Palindrome")
}
Enter Number: 121 [1] "No is Palindrome"
In [18]:
a=0
b=1
n=as.integer(readline(prompt="Enter Number for N Series: "))
cat(paste(a,b,""))
for(i in 3:n)
{
c=a+b
cat(paste(c,""))
a=b
b=c
}
Enter Number for N Series: 5 0 1 1 2 3
In [ ]: