w3resource

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


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

Go to:


PREV : 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.

Ruby Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.