1

#! /bin/bash I omitted here though I have used it. I used bash shell only. first integer is the no of variables in the array. yes I did get syntax error.

need to read the array and sum of the array elements. given an array of integers of size N . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large.

Input Format:

The first line of the input consists of an integer N . The next line contains space-separated integers contained in the array (1<=N<=10, 0<=A[i]<=10000000000).

5
1000000001 1000000002 1000000003 1000000004 1000000005

Output Format:

Print a single value equal to the sum of the elements in the array.

5000000015

what I have done so far:

code:

#input array size
read N
while [ $N -ge 1 -a $N -le 10 ]
do
echo $N
break
done
for i in `seq 0 N-1`;
do 
read -a array[i]
if[ "${array[i]}" -ge 0 -a "${array[i]}" -le 10000000000 ]; then
echo "${array[i]}"
fi
done
#sum=expr `sum + ${ array[i] }`

Syntax error: operator expected

Could you please let me know where I went wrong?

  • 1
    Please edit your question and i) tell us how you ran this script, how did you give it input? There is no shebang line (e.g. #! /bin/sh or #! /bin/bash), what shell did you run this with? ii) tell us why the 1st integer is relevant, is it the number of integers on the next line? iii) show us the results you got and how they are different from what you expected. iv) running your script should result in several syntax error messages. Didn't you get any? – terdon Aug 13 '16 at 12:03
  • @terdon: hi, #! /bin/bash I omitted here though I have used it. I used bash shell only. first integer is the no of variables in the array. yes I did get syntax error. I want to know the problem with my code. – nishant jha Aug 13 '16 at 17:09
  • Please [edit] your question to add this information. Comments are hard to read and easy to miss. Make sure to include the syntax errors as well. – terdon Aug 13 '16 at 17:13
1

If we operate in bash we don't need to use indexes

#!/bin/bash
read N 
read -a A
for elem in "${A[@]::N}"; do
    ((ar_sum+=$elem))
done
echo $ar_sum

for-loop can be exchanged by

expr $(printf '%b + ' "${A[@]::N}"\\c)
  • Maybe: echo $(($(printf '%s + ' "${A[@]}" )0)). No expr called (faster), no %b used (less sensible to the input), no \c used (less cryptic). – Isaac Nov 18 '18 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.