In: Statistics and Probability
Use the following two loop strategies to write a function that sums all even numbers before an odd number is observed in any given numeric vector, and test your code in R. For example, if the input vector is 2, 4, -2, 3, 4, 5, then the first odd number appears in the fourth position, which is 3. The output should be the sum of the first to the third numbers, which will be 2 + 4 − 2 = 4. If the first number of the input vector is an odd number, then the output should be 0.
• for(){}
• while(){}
R code, using for()
------------
#using for()
sumEven<-function(x){
#initialize the sum to 0
s<-0
#loop through all the elements
for (i in x) {
#check if the number of even
if (i%%2==0) {
#add the number
to sum
s<-s+i
} else {
#stop if the
number is odd
break
}
}
return(s)
}
#set the numeric vector
x<-c(2, 4, -2, 3, 4, 5)
#call the function
sumEven(x)
#return 0, if the first element is odd
x<-c(19,2, 4, -2, 3, 4, 5)
#call the function
sumEven(x)
----
Get this
using while()
-------------
#using while()
sumEven<-function(x){
#initialize the sum to 0
s<-0
#set the index to the first element
i<-1
#loop through the elements till odd
while (x[i]%%2==0) {
#add the number to sum
s<-s+x[i]
#increment the index
i<-i+1
}
return(s)
}
#set the numeric vector
x<-c(2, 4, -2, 3, 4, 5)
#call the function
sumEven(x)
#return 0, if the first element is odd
x<-c(19,2, 4, -2, 3, 4, 5)
#call the function
sumEven(x)
----
Get this