R Programming
R Programming
2. Program that asks the user for a number n and prints the sum of the
numbers 1 to n
R
Copy code
# Program to sum numbers from 1 to n
sum_to_n <- function() {
n <- as.integer(readline(prompt="Enter a number: "))
sum <- sum(1:n)
print(paste("The sum of numbers from 1 to", n, "is", sum))
}
sum_to_n()
multiplication_table()
# Example usage
lst <- c(3, 5, 7, 2, 8, 1)
print(largest_element(lst))
# Example usage
lst <- c(1, 2, 3, 4, 5)
print(running_total(lst))
# Example usage
str <- "radar"
print(is_palindrome(str))
Selection Sort
R
Copy code
# Selection Sort implementation
selection_sort <- function(lst) {
n <- length(lst)
for (i in 1:(n-1)) {
min_index <- i
for (j in (i+1):n) {
if (lst[j] < lst[min_index]) {
min_index <- j
}
}
if (min_index != i) {
temp <- lst[i]
lst[i] <- lst[min_index]
lst[min_index] <- temp
}
}
return(lst)
}
# Example usage
lst <- c(64, 25, 12, 22, 11)
print(selection_sort(lst))
Insertion Sort
R
Copy code
# Insertion Sort implementation
insertion_sort <- function(lst) {
n <- length(lst)
for (i in 2:n) {
key <- lst[i]
j <- i - 1
while (j > 0 && lst[j] > key) {
lst[j + 1] <- lst[j]
j <- j - 1
}
lst[j + 1] <- key
}
return(lst)
}
# Example usage
lst <- c(12, 11, 13, 5, 6)
print(insertion_sort(lst))
Bubble Sort
R
Copy code
# Bubble Sort implementation
bubble_sort <- function(lst) {
n <- length(lst)
for (i in 1:(n-1)) {
for (j in 1:(n-i)) {
if (lst[j] > lst[j + 1]) {
temp <- lst[j]
lst[j] <- lst[j + 1]
lst[j + 1] <- temp
}
}
}
return(lst)
}
# Example usage
lst <- c(5, 1, 4, 2, 8)
print(bubble_sort(lst))
# Example usage
lst <- c(2, 3, 4, 10, 40)
x <- 10
print(linear_search(lst, x))
# Example usage
lst <- c(2, 3, 4, 10, 40)
x <- 10
print(binary_search(lst, x))
Matrix Addition
R
Copy code
# Matrix Addition implementation
matrix_addition <- function(mat1, mat2) {
return(mat1 + mat2)
}
# Example usage
mat1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)
mat2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2)
print(matrix_addition(mat1, mat2))
Matrix Subtraction
R
Copy code
# Matrix Subtraction implementation
matrix_subtraction <- function(mat1, mat2) {
return(mat1 - mat2)
}
# Example usage
mat1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)
mat2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2)
print(matrix_subtraction(mat1, mat2))
Matrix Multiplication
R
Copy code
# Matrix Multiplication implementation
matrix_multiplication <- function(mat1, mat2) {
return(mat1 %*% mat2)
}
# Example usage
mat1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)
mat2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2)
print(matrix_multiplication(mat1, mat2))