The "if-else" statement is a fundamental control structure in programming that allows us to make decisions in our code based on certain conditions. This statement is used to execute different sets of code depending on whether a specified condition is true or false.
In this article, we will discuss how to check if a number is divisible by another number with its working example in the R programming language.
Syntax:
if (number %% divisor == 0) {
# Code block executed if the number is divisible by the divisor
print("Number is divisible by divisor")
} else {
# Code block executed if the number is not divisible by the divisor
print("Number is not divisible by divisor")
}
Example 1: To check whether 15 is divisible by 3 or not
number <- 15
divisor <- 3
# Check if the number is divisible by the divisor
if (number %% divisor == 0) {
print(paste(number,"is divisible by",divisor))
} else {
print(paste(number,"is not divisible by",divisor))
}
Output:
[1] "15 is divisible by 3"number <- 15: You initialize a variable namednumberwith the value 15, representing the number you want to check for divisibility.divisor <- 3: You initialize a variable nameddivisorwith the value 3, which represents the divisor you want to use for the divisibility check.if (number %% divisor == 0) { ... } else { ... }:- This
if-elsestatement checks whether the remainder of the divisionnumber %% divisoris equal to 0. If it is, it means thatnumberis divisible bydivisor. - If the condition is true, the code inside the
ifblock will execute. - If the condition is false, the code inside the
elseblock will execute.
Example 2: To check whether 16 is divisible by 3 or not
number <- 16
divisor <- 3
# Check if the number is divisible by the divisor
if (number %% divisor == 0) {
print(paste(number, "is divisible by" ,divisor))
} else {
print(paste(number, "is not divisible by" , divisor))
}
Output:
[1] "16 is not divisible by 3"
number <- 16: You initialize a variable namednumberwith the value 15, representing the number you want to check for divisibility.divisor <- 3: You initialize a variable nameddivisorwith the value 3, which represents the divisor you want to use for the divisibility check.if (number %% divisor == 0) { ... } else { ... }:- This
if-elsestatement checks whether the remainder of the divisionnumber %% divisoris equal to 0. If it is, it means thatnumberis divisible bydivisor. - If the condition is true, the code inside the
ifblock will execute. - If the condition is false, the code inside the
elseblock will execute.