1a.For loop that calculates 13-factorial:
x<-13 #initialize x = 13
running_total <-1 #create variable for running total, set = 1
while(x>=1) #while x is greater than or equal to 1
{
#multiply runningtotal by x, starting from 13 and add to running total
running_total <- running_total * x
x <- x-1 #decrement x by 1
}
print(running_total)
## [1] 6227020800
1b. For loop to calculate factorial
y <- 1 #initialize y = 1
#for each iteration between 1-13, multiply y and loop through, adding to y variable
for(i in 1:13)
{
y <-y*((1:13)[i])
}
print(y)
## [1] 6227020800
num_vect <- c() #blank vector
numbers <- 1:50 #range through 50
for(i in numbers) #iterate through numbers 1-50
{
if(i%%5==0 && i>=10) #if integer in numbers is divisible by 5 and greater than or equal to 10
{
num_vect[i] <- numbers[i] #add number to empty vector
}
num_vect <- num_vect[!is.na(num_vect)] #remove NAs
}
print(num_vect)
## [1] 10 15 20 25 30 35 40 45 50
#initialize variables
distance <- 0.0
slope <- 0.0
y_int <- 0.0
#read in input coordinates from user
{
x1 <- readline("Enter first x-coordinate : ")
y1 <- readline("Enter first y-coordinate : ")
x2 <- readline("Enter second x-coordinate: ")
y2 <- readline("Enter second y-coordinate: ")
}
## Enter first x-coordinate :
## Enter first y-coordinate :
## Enter second x-coordinate:
## Enter second y-coordinate:
#set each coordinate as numeric
x1 <- as.numeric(x1)
y1 <- as.numeric(y1)
x2 <- as.numeric(x2)
y2 <- as.numeric(y2)
#create a list of points from the values above
points <- list(c(x1,y1),c(x2,y2))
#create a function, lines, accessing values from the points list to calculate
#distance, slope and y intercept. Print values
lines <- function(points)
{
distance <- sqrt((points[[2]][1]-points[[1]][1])^2 + (points[[2]][2]-points[[1]][2])^2)
slope <- (points[[2]][2]-points[[1]][2])/(points[[2]][1]-points[[1]][1])
y_int <- points[[2]][2] - (slope*points[[2]][1])
print(paste("Distance:", distance))
print(paste("Slope:", slope))
print(paste("Y-Intercept:", y_int))
}
lines(points)
## [1] "Distance: NA"
## [1] "Slope: NA"
## [1] "Y-Intercept: NA"