4

I have to submit a script which adds two values within an for loop and puts every result in an array. I put together a script (which is not working) but I cannot figure out how to get it started.

#!/bin/sh

val1=$1
val2=$2
for i in 10
    do
        ${array[i]}='expr $val1+$val2'
        $val1++
    done    
echo ${array[@]}

2 Answers 2

5

Perhaps you mean this?

val1=$1
val2=$2
for i in {1..10}; do
    array[i]=$(( val1 + val2 ))
    (( ++val1 ))
done    
echo "${array[@]}"

If you bash doesn't support {x..y}, use this format:

for (( i = 1; i <= 10; ++i )); do

Also simpler form of

    array[i]=$(( val1 + val2 ))
    (( ++val1 ))

Is

    (( array[i] = val1 + val2, ++val1 )) ## val1++ + val2 looks dirty
Sign up to request clarification or add additional context in comments.

1 Comment

And please let us know what grade you get after you submit it :-).
2

konsolebox's answer is right, but here are some alternatives:

val1=$1
val2=$2
for i in {0..9}; do
    (( array[i]=val1 + val2 + i ))
done
echo "${array[@]}"


val1=$1
val2=$2
for (( i=val1 + val2; i < val1 + val2 + 10; i++ )); do
    array+=("$i")
done
echo "${array[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.