Professional Documents
Culture Documents
R Program which gets the input from user and print the fibonacci sequence
n = as.integer(readline(prompt="Enter the number of terms: "))
a = 0 # first number
b = 1 # second number
print("Fibonacci sequence:")
print(a)
print(b)
for(x in 2 : n)
{
c=a+b;
print(c);
a=b;
b=c;
}
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
ARMSTRONG NUMBER
n = as.integer(readline(prompt="Enter a number: "))
sum = 0
temp = n
while(n > 0)
r = n %% 10
sum = sum + (r ^ 3)
n = floor(n / 10)
if(temp == sum)
print(paste(temp, "is an Armstrong number"))
} else
print(paste(temp, "is not an Armstrong number"))
PRIME NUMBERS
num = as.integer(readline(prompt="Enter a number: "))
flag = 0
# prime numbers are greater than 1
if(num > 1) {
flag = 1
for(i in 2:(num-1))
if ((num %% i) == 0)
flag = 0
break
}
if(num == 2)
flag = 1
if(flag == 1) {
print(paste(num,"is a prime number"))
} else {
print(paste(num,"is not a prime number"))
Enter a number: 12
R program to print the numbers from 1 to 100 and print "Fizz" for multiples of 3, ** **print "Buzz"
for multiples of 5, and print "FizzBuzz" for multiples of both.
n=as.integer(readline(prompt="Enter the number:"))
for (n in 1:100)
if (n %% 3 == 0 & n %% 5 == 0)
print("FizzBuzz")
else if (n %% 3 == 0)
print("Fizz")
else if (n %% 5 == 0)
print("Buzz")
else
print(n)
[1] 1
[1] 2
[1] "Fizz"
[1] 4
[1] "Buzz"
[1] "Fizz"
[1] 7
[1] 8
[1] "Fizz"
[1] "Buzz"
[1] 11
[1] "Fizz"
[1] 13
[1] 14
[1] "FizzBuzz"
[1] 16
[1] 17
[1] "Fizz"
[1] 19
[1] "Buzz"
[1] "Fizz"
[1] 22
[1] 23
[1] "Fizz"
[1] "Buzz"
[1] 26
[1] "Fizz"
[1] 28
[1] 29
[1] "FizzBuzz"
[1] 31
[1] 32
[1] "Fizz"
[1] 34
[1] "Buzz"
[1] "Fizz"
[1] 37
[1] 38
[1] "Fizz"
[1] "Buzz"
[1] 41
[1] "Fizz"
[1] 43
[1] 44
[1] "FizzBuzz"
[1] 46
[1] 47
[1] "Fizz"
[1] 49
[1] "Buzz"
[1] "Fizz"
[1] 52
[1] 53
[1] "Fizz"
[1] "Buzz"
[1] 56
[1] "Fizz"
The road transport corporation (RTC) of a city wants to know whether a particular bus-route is
running on profit or loss. Assume that the following information are given: Price per litre of fuel =
70 Mileage of the bus in km/litre of fuel = 10 Price(Rs) per ticket = 80 The bus runs on multiple
routes having different distance in kms and number of passengers. Write a function to calculate
and return the profit earned (Rs) in each route. Return -1 in case of loss
new.function <- function(distance,passengers)
mileage=10
totalkm=70 * distance/mileage
totalcost=passengers*80
profit=totalcost-totalkm
if (profit>0)
print(profit)
else
print("-1")
distance=as.integer(readline(prompt="Enter the distance:"))
passengers=as.integer(readline(prompt="Enter the passengers:"))
new.function(distance,passengers)
[1] 890
PALINDROME
is_palindrome <- function(word) {
library(stringr)
split_word <- unlist((str_split(word, pattern = "")))
reverse_word <- split_word[str_length(word):1]
paste_word <- paste(reverse_word, collapse = "")
cat(word == paste_word)
str = readline(prompt = "Enter a String :")
is_palindrome(str)
TRUE