w3resource

Calculate Sum of Odd elements in Array using For loop in R

R Programming: Control Structure Exercise-14 with Solution

Write a R program to find the sum of all elements in an array using a for loop.

Sample Solution :

R Programming Code :

# Define a function to find the sum of all odd elements in an array using a for loop
sum_of_odd_elements <- function(arr) {
    # Initialize a variable to store the sum
    sum <- 0
    
    # Iterate through each element in the array
    for (element in arr) {
        # Check if the element is odd
        if (element %% 2 != 0) {
            # Add the odd element to the sum
            sum <- sum + element
        }
    }
    
    # Return the sum of odd elements
    return(sum)
}

# Test the function with an example array
array <- c(10, 20, 30, 41, 50, 60, 73, 80, 90, 101)
result <- sum_of_odd_elements(array)

# Print the result
cat("Sum of all odd elements in the array is:", result, "\n")

Output:

Sum of all odd elements in the array is: 215           

Explatnaion:

In the exercise above,

  • The "sum_of_odd_elements()" function takes an array 'arr' as input.
  • It initializes a variable 'sum' to store the sum of odd elements and sets it to 0.
  • Using a for loop, it iterates through each element in the array.
  • For each element, it checks if the element is odd by using the modulus operator (%%). If the remainder is not zero, it means the element is odd.
  • If the element is odd, it adds it to the 'sum'.
  • After iterating through all elements, it returns the 'sum' of odd elements.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Calculate Factorial with Recursion & Iteration in R.
Next: Check Perfect number using While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.