For calculating the sum of all even numbers up to n, first, we have to ask the user to enter the limit or n. Then in the second step, it is required to check whether the number is even or not and then if it is found to be even, the sum should be calculated. The logic mentioned can be implemented in a few lines of code. For checking whether the number is even or not, you can either use .even? method or %(mod) operator.
Methods used:
- puts: This is used to put a string on the console.
- gets: The method is used for taking input from the user.
- %: This is the mod operator. It is an arithmetic operator which takes two values as an argument and returns the remainder.
- .even?: This is a predefined method used to verify even number.
Ruby code to calculate the sum of all even numbers
Method 1 : Using the classical way using %2
Output
Explanation:
In this program, we will calculate the sum of all even numbers up to n. We have used the remainder operator for this %. As this is division by two, then the number will return only 0 or 1 which are directly test in the if condition. n is the number up to which the check is to be performed. The variable Sum stores the sum of all the even numbers. Which is returned by the program after all numbers till n are traversed using a loop (while loop in our program).
Method 2: Using the even method that returns true if the number is even
Output
Explanation:
In this program, we will calculate the sum of all even numbers up to n. We have used a Ruby method named even? to check if the number is even or not. The method returns true if the number is even. n is the number up to which the check is to be performed. The variable sum stores the sum of all the even numbers. Which is returned by the program after all numbers till n are traversed using a loop (while loop in our program).
need an explanation for this answer? contact us directly to get an explanation for this answer