Q:

Write a Ruby program to compute the sum of the first 2 elements of a given array of integers

0

Write a Ruby program to compute the sum of the first 2 elements of a given array of integers. If the array length is less than 2, just sum up the elements that exist, returning 0 if the length of the array is 0.

All Answers

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

def check_array(nums)
    if(nums.length >= 2)
		return (nums[0] + nums[1])
	end
	if(nums.length == 1)
		return nums[0];
	end
	return 0;

end
print check_array([1, 2, 5]),"\n" 
print check_array([4, 2, 3]),"\n" 
print check_array([1])
 Output:
3
6
1

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

total answers (1)

Similar questions


need a help?


find thousands of online teachers now