VOOZH about

URL: https://www.geeksforgeeks.org/r-language/counting-the-number-of-even-and-odd-elements-in-a-vector-using-a-for-loop/

⇱ Counting the number of even and odd elements in a vector using a for loop? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counting the number of even and odd elements in a vector using a for loop?

Last Updated : 23 Jul, 2025

In this article, we will discuss how to find the number of even and odd elements in a vector with its working example in the R Programming Language using R for loop.

Syntax:

vector <- c(...) # Replace ... with the vector elements
even_count <- 0
odd_count <- 0
for (element in vector) {
if (element %% 2 == 0) {
even_count <- even_count + 1
} else {
odd_count <- odd_count + 1
}
}
cat("Number of even elements:", even_count, "\n")
cat("Number of odd elements:", odd_count, "\n")

Example 1

Output:

Number of even elements: 5 Number of odd elements: 5
  • Create a vector with the given elements.
  • Initialize a variable even_count to store the count of even elements. Set its initial value to 0.
  • Initialize a variable odd_count to store the count of odd elements. Set its initial value to 0.
  • Start a for loop that iterates through each element in the vector.
  • Check if the current element is even (divisible by 2).
  • If the current element is even, increment the even_count by 1.
  • If the current element is not even (i.e., odd):
  • Increment the odd_count by 1.
  • Print the no. of even and odd count

Example 2

Output:

Number of even elements: 4 
Number of odd elements: 5

Example 3

Output:

Number of even elements: 2 Number of odd elements: 7
Comment
Article Tags:
Article Tags:

Explore