I am trying to run the below code using for loop but i am getting syntax error. Please help.
Input Format: The first line of the input contains an i
This will work. However you should insert some helper messages inside:
#!/bin/bash
read n
sum=0
for (( i=1; i<=n; i++ ))
do
read val
((sum^=val))
done
echo $sum
The printf "%s" "$n" | hexdump -C
shows that the CR is contained in the input rather than in the script file, so running dos2unix
on the script won't help anyway. A simple means to get rid of it is setting IFS=$'\r'
.
Then, read val
in a loop is unfit to read space-separated integers, since read
reads a whole line at a time. But for the task of bitwise exclusive ORing those N space-separated integers we don't need an explicit loop - we can just replace all spaces with the desired operator and evaluate the result.
#!/bin/bash
IFS=$'\r'
read n
read a
((sum = ${a// /^}))
echo $sum