Ruby Array Exercises: Compute the sum of the numbers of a given array except the number 17 and numbers that come immediately after a 17
Ruby Array: Exercise-32 with Solution
Write a Ruby program to compute the sum of the numbers of a given array except the number 17 and numbers that come immediately after a 17. Return 0 for an empty array.
Ruby Code:
def check_array(nums)
sum = 0
i = 0
while i < nums.length
if(nums[i] == 17)
i= i + 1
else
sum = sum + nums[i]
end
i += 1
end
return sum
end
print check_array([3, 5, 17, 6]),"\n"
print check_array([3, 5, 1, 17]),"\n"
print check_array([3, 17, 1, 7]),"\n"
Output:
8 9 10
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to compute the average values of a given array, except the largest and smallest values. The array length must be 3 or more.
Next: Write a Ruby program to check whether the sum of all the 3's of a given array of integers is exactly 9.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/ruby-exercises/array/ruby-array-exercise-32.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics