R Programs!

 1.Write R program that takes your name as an input and output each letter of your name as an output.

SOLUTION

{

name <- as.character ( readline(prompt="Input your name: "))

x <-nchar(name)

for ( i in x) {

output <- strsplit(name,"")

print(output)

}

i = i+1

}

2.Give one example that uses break statement within while loop.

SOLUTION

# while loop with break statement

i <- 1

while (i <= 6) {

if (i==4)

break;

print(i*i)

i = i+1

}

3.Give one example that uses next statement within for loop.

SOLUTION

#R Next Statement Example within for loop

number <- 1:20

for (val in number) {

if (val %% 2 != 0) {

print(paste("ODD Number = ", val, "(Skipped by Next Statement)"))

next

}

print(paste("EVEN Number = ", val))

}


4.Write R program that determine whether the given number by the user is odd or even.

SOLUTION

# A number is even, if divided by number 2 gives a remainder of 0.

# If remainder is 1, it is odd number.

#as. integer attempts to coerce its argument to be of integer type.

#Paste function in R is used to concatenate Vectors by converting them into character.

num <- as.integer (readline(prompt = "Enter a number: " ))

if((num %% 2) == 0) {

print(paste(num,"is Even"))

} else {

print(paste(num,"is Odd"))

}

5.VAT has different rate according to the product purchased. Imagine we have three different kinds of products with different VAT applied:

We can write a chain to apply the correct VAT rate to the product a customer bought.

SOLUTION

# Taking category A with price 10

category <- 'A'

price <- 10

if (category =='A'){

cat('A vat rate of 8% is applied.','The total price is',price *1.08)

} else if (category =='B'){

cat('A vat rate of 10% is applied.','The total price is',price *1.10)

} else {

cat('A vat rate of 20% is applied.','The total price is',price *1.20)

}

0 Comments