Open In App

R Program to Check if a number is divisible by another number

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"

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"

Article Tags :