In: Computer Science
Consider a numeric vector x (e.g., x=c(2,3,-1,1.2,2.6,0)), write the R code that determine whether each element of x is (Verify that your code work correctly):
(a) positive
(b) non-positive
(c) even or odd
(d) an integer
Given code is in R:
x <- c(2,3,-1,1.2,2.6,0)
for(i in x){ #iterating through the vector.
if(i > 0){ #to check if the number is positive.
print(paste(i, " is positive."))
}
if(i <= 0){ #to check if the number is not positive.
print(paste(i, " is non-positive."))
}
if(i == round(i)){ #to check if the number is integer, if yes check for odd and even.
if(i%%2 == 0){
print(paste(i, " is even."))
}
if(i%%2 != 0){
print(paste(i, " is odd."))
}
}
if(i == round(i)){
print(paste(i, " is an integer."))
}
}
Output is as follows:
Every case has been divided into if cases so that it can be easily understood.
Kindly like if this helps :)