0% found this document useful (0 votes)
6 views4 pages

Looping Statement (Printout)

The document provides a comprehensive overview of various programming control structures in R, including IF, ELSE, SWITCH, WHILE, and FOR statements. It includes examples for checking conditions, categorizing data, and performing calculations like discounts and BMI. Additionally, it covers nested loops and how to handle user input for tasks such as reversing strings and finding common elements between vectors.

Uploaded by

bsahulga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Looping Statement (Printout)

The document provides a comprehensive overview of various programming control structures in R, including IF, ELSE, SWITCH, WHILE, and FOR statements. It includes examples for checking conditions, categorizing data, and performing calculations like discounts and BMI. Additionally, it covers nested loops and how to handle user input for tasks such as reversing strings and finding common elements between vectors.

Uploaded by

bsahulga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

I. IF ELSE LOOPING STATEMENTS 3. Check if an element is in the vector.

fruits <- c("apple", "banana", "mango", "orange")


Different looping statements utilizing IF ELSE
statement. fruit_to_check <- "mango"
❖ IF STATEMENT (3 EXAMPLES) if (fruit_to_check %in% fruits) {
1. Check if the number is positive. print("The fruit is available.")
num <- 10
} else {
if (num > 0) {
print("The fruit is not available.")
print("The number is positive.")
}
}
❖ NESTED IF ELSE STATEMENT (3 EXAMPLES)
2. Check for a high score.
score <- 95 1. Check for PASS or FAIL.
score <- 85
if (score >= 90) {
if (score >= 50) {
print("Congratulations! You got an A.")
if (score >= 90) {
}
print("You passed with High Distinction!")
3. Check if values is in a vector.
numbers <- c(1, 3, 5, 7, 9) } else {

if (5 %in% numbers) { print("You passed.")

print("Number 5 is in the list!") }

} } else {
print("You failed.")
❖ IF ELSE STATEMENT (3 EXAMPLES)
}
1. Categorizing age groups.
age <- 25 2. Check for voting age.
age <- 20
if (age < 13) {
if (age < 13) {
category <- "Child"
print("You are a Child.")
} else if (age >= 13 & age <= 19) {
} else if (age >= 13 & age <= 19) {
category <- "Teenager"
print("You are a Teenager.")
} else if (age >= 20 & age <= 59) {
} else {
category <- "Adult"
if (age >= 18) {
} else {
print("You are an Adult and eligible to vote.")
category <- "Senior"
} else {
}
print("You are not eligible to vote yet.")
print(paste("Age group:", category))
}
2. Checking if number is PRIME.
num <- 11 }

if (num > 1 && all(num %% 2:(num - 1) != 0)) { 3. Check for a discount.


purchase_amount <- 1200
print("The number is prime.")
if (purchase_amount >= 1000) {
} else {
if (purchase_amount >= 5000) {
print("The number is not prime.")
print("You get a 20% discount!")
}
} else { bmi <- weight / (height^2) #calculations
print("You get a 10% discount!") if (bmi < 18.5) {
} print("You are Underweight.")
} else if (purchase_amount >= 500) { } else if (bmi >= 18.5 & bmi < 24.9) {
print("You get a 5% discount!") print("You have a Normal weight.")
} else {
} else if (bmi >= 25 & bmi < 29.9) {
print("No discount available.")
print("You are Overweight.")
}
} else {
❖ IF ELSE IF ELSE STATEMENT (3 EXAMPLES)
print("You are Obese.")
1. Classifying student grades.
score <- 75 }

if (score >= 90) { ❖ IFELSE() STATEMENT (3 EXAMPLES)

print("Grade: A") 1. Checking for even && odd.


} else if (score >= 80) { cat("Please enter a number: ")

print("Grade: B") num <- scan(what = integer(), nmax = 1)

} else if (score >= 70) { result <- ifelse(num %% 2 == 0, "Even", "Odd")

print("Grade: C") print(result)

} else if (score >= 60) { 2. Checking Positive, Negative, or Zero Number.

print("Grade: D") cat("Please enter a number: ")

} else { num <- scan(what = integer(), nmax = 1)

print("Grade: F") result <- ifelse(num > 0, "Positive",


ifelse(num < 0, "Negative", "Zero"))
}
print(result)
2. Checking for a discount.
purchase_amount <- 200 3. Categorize age group.
cat("Please enter your age: ")
if (purchase_amount >= 1000) {
age <- scan(what = numeric(), nmax = 1)
print("You receive a 20% discount.")
age_group <- ifelse(age < 13, "Child",
} else if (purchase_amount >= 500) {
ifelse(age >= 13 & age <= 19, "Teenager",

print("You receive a 10% discount.") ifelse(age >= 20 & age <= 59, "Adult",

} else if (purchase_amount >= 100) { "Senior")))

print("You receive a 5% discount.") cat("You belong to the", age_group, "age group.")

} else {
print("No discount available.")
}

3. BMI calculation.
weight <- 70
height <- 1.75
II. SWITCH() STATEMENTS )

cat("Meal suggestion:", meal_suggestion)


1. Day of the week.
cat("Enter a number between 1 and 7 to get III. WHILE LOOP STATEMENTS
the corresponding day of the week: ")
1. Guessing number.
day_number <- scan(what = integer(), nmax = 1)
set.seed(123)
day_of_week <- switch(day_number, target_number <- sample(1:100, 1)
"1" = "Monday", guess <- -1
"2" = "Tuesday", cat("Guess the number between 1 and 100:\n")

"3" = "Wednesday", while (guess != target_number) {

"4" = "Thursday", guess <- scan(what = numeric(), nmax = 1)

"5" = "Friday", if (guess < target_number) {

"6" = "Saturday", cat("Too low! Try again:\n")

"7" = "Sunday", } else if (guess > target_number) {

cat("Too high! Try again:\n")


"Invalid number. Please enter a number
between 1 and 7." } else {

) cat("Correct! The number was",


target_number, "\n")
cat("The day of the week is:", day_of_week)
}
2. Roman numerals to integer.
cat("Enter a Roman numeral (I, II, III, IV, V): ") }

roman_numeral <- scan(what = character(), nmax = 1) 2. Countdown to 1.


cat("Enter a number to start the countdown: ")
integer_value <- switch(roman_numeral,
n <- scan(what = numeric(), nmax = 1)
"I" = 1,
while (n > 0) {
"II" = 2,
cat(n, "\n")
"III" = 3,

"IV" = 4, n <- n - 1

"V" = 5, }

"Invalid Roman numeral. Please enter I, II, cat("Blast off!\n")


III, IV, or V."
3. Find the factorial.
) cat("Enter a number to calculate its factorial: ")

cat("The integer value is:", integer_value) num <- scan(what = numeric(), nmax = 1)
3. Time of the day. factorial <- 1
cat("Enter the time of day (0 to 23): ")
count <- 1
time_of_day <- scan(what = numeric(), nmax = 1)

meal_suggestion <- switch(TRUE, while (count <= n) {

time_of_day >= 5 && time_of_day < 10 = factorial <- factorial * count


"Breakfast",
count <- count + 1
time_of_day >= 11 && time_of_day < 15 = "Lunch",

time_of_day >= 16 && time_of_day < 21 = "Dinner",


}
cat("The factorial of", num, "is:", factorial, "\n")
(time_of_day >= 22 || time_of_day < 5) = "Snack",

"Invalid input. Please enter a valid time between 0


and 23."
III. FOR LOOP STATEMENTS for (j in 1:n) {

❖ FOR LOOP matrix_input[i, j] <- scan(what =


numeric(), nmax = 1)
1. Sum of even numbers from 1.
}
cat("Enter a number: ")
}
num <- scan(what = numeric(), nmax = 1)
cat("The matrix you entered is:\n", matrix_input)
sum_even <- 0
2. Sum of elements in 2D Matrix
for (i in 1:num) { matrix_4x4 <- matrix(1:16, nrow = 4, ncol = 4)

if (i %% 2 == 0) { cat("Original Matrix:\n")

sum_even <- sum_even + i print(matrix_4x4)

} sum_elements <- 0

} for (i in 1:4) {

cat("The sum of all even numbers from 1 for (j in 1:4) {


to", n, "is:", sum_even, "\n")
sum_elements <- sum_elements +
2. Multiplication table for the input. matrix_4x4[i, j]

cat("Enter a number to display its multiplication table: ") }


n <- scan(what = numeric(), nmax = 1) }
cat("Multiplication table for", n, "is:\n") cat("The sum of all elements in the matrix
is:", sum_elements, "\n")
for (i in 1:10) {
3. Common elements between 2 vectors.
cat(n, "x", i, "=", n * i, "\n")
cat("Enter the first vector (separate by spaces): ")
}
vector1 <- scan(what = numeric(), nmax = 1)
3. Reverse a string.
cat("Enter the second vector (separate by spaces): ")
cat("Enter a string to reverse: ")
input_string <- scan(what = character(), nmax = 1) vector2 <- scan(what = numeric(), nmax = 1)

reversed_string <- "" common_elements <- c()

for (i in nchar(input_string):1) { for (i in 1:length(vector1)) {

reversed_string <- for (j in 1:length(vector2)) {


paste0(reversed_string,
if (vector1[i] == vector2[j]) {
substr(input_string, i, i))
common_elements <- c(common_elements, vector1[i])
}
}
cat("The reversed string is:", reversed_string, "\n")
}
❖ NESTED FOR LOOP
}
1. Create a 2D array from input.
cat("Enter the number of rows (m: ") cat("Common elements between the two vectors are:\n")

m <- scan(what = numeric(), nmax = 1) print(common_elements)

cat("Enter the number of columns (n): ")


n <- scan(what = numeric(), nmax = 1)
matrix_input <- matrix(0, nrow = m, ncol = n)

cat("Enter the values for the matrix:\n")


for (i in 1:m) {

You might also like