# Input Format
# The first line contains an integer, N, denoting the size of the array.
# The second line contains N space-separated integers representing the array's elements.
# Output Format
# Print the sum of the array's elements as a single integer.
puts "Enter the size of array :"
n = gets.strip.to_i
puts "Enter the elements with one space :"
arr = gets.strip
# 1st method :
arr = arr.split(' ').map(&:to_i)
sum = 0
arr.each{|i| sum+=i}
puts sum
# 2nd method :
puts arr.inject(:+)
# 3rd method :
puts arr.inject(0){|k,v| k+v}
# Passed 0 in inject method(inject(0)) because it will return 0 if we pass an empty array otherwise it will return null.
# The first line contains an integer, N, denoting the size of the array.
# The second line contains N space-separated integers representing the array's elements.
# Output Format
# Print the sum of the array's elements as a single integer.
puts "Enter the size of array :"
n = gets.strip.to_i
puts "Enter the elements with one space :"
arr = gets.strip
# 1st method :
arr = arr.split(' ').map(&:to_i)
sum = 0
arr.each{|i| sum+=i}
puts sum
# 2nd method :
puts arr.inject(:+)
# 3rd method :
puts arr.inject(0){|k,v| k+v}
# Passed 0 in inject method(inject(0)) because it will return 0 if we pass an empty array otherwise it will return null.
No comments:
Post a Comment