Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Ruby Basic Exercises: Compute and print the sum of two given integers

Ruby Basic: Exercise-44 with Solution

Write a Ruby program to compute and print the sum of two given integers, print 30 if the sum is in the range 20..30 (inclusive).

Ruby Basic Exercises: Compute and print the sum of two given integers

Ruby Code:

def sum(a,b)
    sum = a + b;
	if(sum >= 20 && sum <= 30)
		return 20;
	end	
	return sum;
end
print sum(9, 7),"\n"
print sum(12, 10),"\n"
print sum(22, 15)

Output:

16
20
37

Flowchart:

Flowchart: Compute and print the sum of two given integers

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check if the sequence of numbers 10, 20, 30 appears anywhere in a given array of integers.
Next: Write a Ruby program to check two given integers and return 11 if either one is 11. Return their sum or difference if sum or difference is 11.

What is the difficulty level of this exercise?