Q:

Ruby program to calculate the sum of all even numbers

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Ruby code to calculate the sum of all even numbers

Method 1 : Using the classical way using %2

=begin
Ruby program to calculate the sum of 
all even numbers upto n
=end

sum=0

puts "Enter n:-"
n=gets.chomp.to_i

i=1
while(i<=n)
	if(i%2==0) 	#using % operator
		sum=sum+i
		i=i+1
	else
		i=i+1
	end
end

puts "The sum is #{sum}"

Output

RUN 1:
Enter n:-
5
The sum is 6

RUN 2:
Enter n:-
60
The sum is 930

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

=begin
Ruby program to calculate the sum of 
all even numbers upto n
=end

sum=0

puts "Enter n:-"
n=gets.chomp.to_i

i=1
while(i<=n)
	if(i.even?) #using .even? method
		sum=sum+i
		i=i+1
	else
		i=i+1
	end
end

puts "The sum is #{sum}"

Output

Enter n:-
10
The sum is 30

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now