w3resource

Sum of Even numbers using For loop in R

R Programming: Control Structure Exercise-3 with Solution

Write a R program function to find the sum of all even numbers between two given numbers using a for loop.

Sample Solution :

R Programming Code :

# Define a function to find the sum of even numbers between two given numbers
sum_of_even_numbers <- function(start_num, end_num) {
    # Initialize a variable to store the sum
    sum <- 0
    
    # Iterate through the range of numbers from start_num to end_num
    for (i in start_num:end_num) {
        # Check if the current number is even
        if (i %% 2 == 0) {
            # If the number is even, add it to the sum
            sum <- sum + i
        }
    }
    
    # Return the sum of even numbers
    return(sum)
}

# Test the function with example inputs
start_num <- 1
end_num <- 10
result <- sum_of_even_numbers(start_num, end_num)

# Print the result
cat("The sum of even numbers between", start_num, "and", end_num, "is", result, "\n")

Output:

The sum of even numbers between 1 and 10 is 30                  

Explatnaion:

In the exercise above,

  • Define the function:
    • The function "sum_of_even_numbers()" takes two parameters: 'start_num' and 'end_num', representing the range of numbers between which the sum of even numbers is to be calculated.
  • Initialization:
    • Inside the function, a variable 'sum' is initialized to store the sum of even numbers, initially set to 0.
  • For Loop:
    • A for loop iterates through each number in the range from 'start_num' to 'end_num'.
    • For each number in the range, the loop checks if it is even using the modulus operator %. If the remainder when divided by 2 is 0, it indicates that the number is even.
  • Summation:
    • If the current number is even, it is added to the 'sum'.
  • Return Result:
    • Once all numbers in the range have been processed, the function returns the calculated sum of even numbers.
  • Testing the Function:
    • The function is tested with example inputs, where 'start_num' is set to 1 and 'end_num' is set to 10.
    • The result of the function call is stored in the variable result.
  • Finally, the result is printed to the console using "cat".

R Programming Code Editor:



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

Previous: Calculate Factorial using While loop in R.
Next: Fibonacci series with While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-3.php