Example 2: Sum of Even Numbers

Suppose we got a vector numbers containing a chain of numbers, and also you need to calculate the sum of even numbers inside that vector:

R




# Create a vector of numbers
numbers <- 1:10
 
# Initialize a sum variable
even_sum <- 0
 
# Use a for loop to calculate the sum of even numbers
for (num in numbers) {
  if (num %% 2 == 0) {  # Check if the number is even
    even_sum <- even_sum + num
  }
}
 
# Display the result
cat("The sum of even numbers in the vector is:", even_sum)


Output:

The sum of even numbers in the vector is: 30

In this example, we use an if statement inside the for loop to test if each variety is even (divisible by using 2) before adding it to the even_sum variable.

Sum of Vector Elements using a for Loop

R is a powerful programming language and surroundings used for facts analysis, statistical computing, and statistics visualization. One common assignment in facts analysis is calculating the sum of factors in a vector. A vector is a fundamental information structure in R Programming Language that shops a collection of values of the equal facts type. we might need to calculate the sum of factors in a vector for diverse reasons, such as finding the whole sales of a product, calculating the common rating of college students, or summarizing records for similar evaluation.

Similar Reads

Concepts Related to the Topic

Before diving into the practical implementation, it’s crucial to recognize some key principles associated with vectors and for loops in R....

Example 1: Sum of Numeric Elements

...

Example 2: Sum of Even Numbers

...

Example 3: Sum of Elements in a Vector of Prices

...