Quote:
Originally Posted by beginner101
value=0
for i in 1 2
do
for j in 1 2 3 4 5 do
value=`expr $i + $j`
echo -n "$value "
done echo done
|
Give someone a fish, you'll feed them for a day. Teach someone to fish, you'll feed them for a lifetime.
What you have here is code with two loops. The first loop (the outer loop) is for the variable i. It will run twice, once with i=1 and once with i=2. The second loop (the inner loop) is for the variable j. Each time the inner loop is run, it will run five times, for j=1 j=2 j=3 j=4 and j=5.
The inner loop is inside the outer loop, so it will run five times for the first run of the outer loop, and five times again for the second run of the outer loop. So the code that's inside the inner loop will run ten times total. Each time it runs, it will add the current values of i and j, and print the result.
The first five times will be during the first run of the outer loop:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 1, j = 5
Then the outer loop will increment i to 2, and run again, leading to another 5 runs of the inner loop
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 2, j = 4
i = 2, j = 5
Now that I've explained the code to you, do you think you can figure out what output it's going to give you?
Let me know if you have any questions! I'm not going to give you the answer, but I am happy to help you learn!