Open In App

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

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

R




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 named number with the value 15, representing the number you want to check for divisibility.
  • divisor <- 3: You initialize a variable named divisor with the value 3, which represents the divisor you want to use for the divisibility check.
  • if (number %% divisor == 0) { ... } else { ... }:
  • This if-else statement checks whether the remainder of the division number %% divisor is equal to 0. If it is, it means that number is divisible by divisor.
  • If the condition is true, the code inside the if block will execute.
  • If the condition is false, the code inside the else block will execute.

Example 2: To check whether 16 is divisible by 3 or not

R




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 named number with the value 15, representing the number you want to check for divisibility.
  • divisor <- 3: You initialize a variable named divisor with the value 3, which represents the divisor you want to use for the divisibility check.
  • if (number %% divisor == 0) { ... } else { ... }:
  • This if-else statement checks whether the remainder of the division number %% divisor is equal to 0. If it is, it means that number is divisible by divisor.
  • If the condition is true, the code inside the if block will execute.
  • If the condition is false, the code inside the else block will execute.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads