'Write a program to print the sum of all the elements of an array of size N where N can be any integer between 1 and 100 [closed]

Write a program to print the sum of all the elements of an array of size N where N can be any integer between 1 and 100. (1 \le N \le 100)

Instructions:

You have to take input variable N denoting the number of elements of the array. Then you have to Input the elements of an array in a single line. We have provided the code to get the input for the array elements. You have to write the logic to add the array elements. Print the sum. Sample input Sample output 3 1 2 3 6 Explanation of Sample I/O

N = 3 Array = 1 2 3

1 + 2 + 3 = 6

N = int(input())
nums = input()
# Get the input
numArray = map(int, input(),nums.split())

sum_integer = 0
# Write the logic to add these numbers here
for i in range(0,N):
    sum_integer = sum_integer[i]
# Print the sum
print (sum_integer)

Input:

3
1 2 3

Desired Output: 6

Actual Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    numArray = map(int, input(),nums.split())
EOFError: EOF when reading a line

what did i do wrong? question from: https://www.codingal.com/competitions/codewars-2021-all-problems/problems/4/

SOLVED:

N = int(input())

numArray = list(map(int, input().split()))

sum_integer = sum(numArray)

print (sum_integer)


Solution 1:[1]

map method takes two arguments first one is a lambda method for converting one data type to other data type and second is an iterable on with the first method operation will be performed.

before converting to int type using filter to remove the data like spaces

filter(lambda data:len(data.strip(), __iterables__)

After this operation calling map(int, __iterables__) which will convert data from str to int for all values in the __iterables__ and list(map(...)) converts the map to list.

N = int(input())
# Get the input
nums = input()
numArray = list(map(int,filter(lambda data:len(data.strip())>0,nums.split(' '))))
#print(numArray)

sum_integer = 0
# Write the logic to add these numbers here
for i in range(len(numArray)):
    sum_integer += numArray[i]
# Print the sum
print (sum_integer)
~

Output:

$ python test.py
3
1 2 3
6

Or Something like this:

input()

print(sum( list(map(int, filter(lambda data:len(data.strip())>0, input().split(' '))))))

Solution 2:[2]

I think this approach should work

arrlen = int(input());#length of the array
ele = [int(x) for x in input().split(' ')];
sumR = 0;
#This loop can be replaced by a simple sumR = sum(ele)
for i in range(arrlen):
     sumR+=ele[i];
print(sumR);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hiten Tandon