R Program to Check for Leap Year
Checks leap year using standard rules.
isLeap <- function(y) {
(y %% 4 == 0 & y %% 100 != 0) | (y %% 400 == 0)
}
print(isLeap(2000))[1] TRUE
Key takeaway: Practice R with 53+ runnable code examples — vectors, strings, math, data frames, recursion, and sampling — with expected output to verify instantly.
R is a programming language for statistical computing and data analysis. These examples are for data science students, researchers, analysts, and anyone learning R for coursework or work projects.
Last updated: October 2026 · 53 examples · All platforms
Interactive Tool:Online R Compiler & Editor · Related:All R Examples · Python Examples · Java Examples · C Examples
Checks leap year using standard rules.
isLeap <- function(y) {
(y %% 4 == 0 & y %% 100 != 0) | (y %% 400 == 0)
}
print(isLeap(2000))[1] TRUE
Computes factorial using a for loop.
n <- 5 fact <- 1 for (i in 2:n) fact <- fact * i print(fact)
[1] 120
Prints a multiplication table for a given number.
n <- 5
for (i in 1:10) {
cat(n, "x", i, "=", n * i, "\n")
}5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
Checks primality with trial division.
isPrime <- function(n) {
if (n < 2) return(FALSE)
if (n %% 2 == 0) return(n == 2)
for (i in 3:floor(sqrt(n))) {
if (n %% i == 0) return(FALSE)
}
TRUE
}
print(isPrime(29))[1] TRUE
Checks if a number equals sum of cubes of its digits.
isArmstrong <- function(n) {
digits <- as.integer(strsplit(as.character(n), "")[[1]])
sum(digits^3) == n
}
print(isArmstrong(153))[1] TRUE
Generates Fibonacci numbers iteratively.
n <- 10
a <- 0; b <- 1
out <- integer(n)
for (i in 1:n) {
out[i] <- a
t <- a + b
a <- b; b <- t
}
print(out)[1] 0 1 1 2 3 5 8 13 21 34
Computes factorial recursively.
fact <- function(n) if (n <= 1) 1 else n * fact(n - 1) print(fact(5))
[1] 120
Generates first N Fibonacci numbers using recursion.
fib <- function(n) if (n < 2) n else fib(n-1) + fib(n-2) out <- sapply(0:9, fib) print(out)
[1] 0 1 1 2 3 5 8 13 21 34
Finds greatest common divisor via Euclidean algorithm.
gcd <- function(a, b) { while (b != 0) { t <- b; b <- a %% b; a <- t } a }
print(gcd(24, 36))[1] 12
Computes least common multiple using GCD.
gcd <- function(a, b) { while (b != 0) { t <- b; b <- a %% b; a <- t } a }
lcm <- function(a, b) abs(a*b) / gcd(a, b)
print(lcm(12, 18))[1] 36
Concatenates strings using paste0.
a <- "Hello" b <- "World" print(paste0(a, " ", b))
[1] "Hello World"
main.R, run Rscript main.R. Or use RStudio. R ranks among the top 20 languages on the TIOBE Index, dominant in academia and data science.
Practice Online:Online R Compiler & Editor (/tools/r-compiler-editor) · Related:All R Examples · Python Examples