Tech Support Guy banner
Status
Not open for further replies.

while loop problem

1K views 5 replies 4 participants last post by  Squashman 
#1 ·
Hello everyone,

I have this little for loop that I want to convert to a while loop. It accepts unknown number from the command line parameters and then add them all up and display the sum, here is the for loop:

HTML:
sum=0

for x in $*
do 
sum=`expr $sum + $argument`
done

echo $sum
it runs perfectly, any suggestions how to convert it to a while loop?

Thank you

Regards
 
#2 ·
Looks like homework to me.

I'll give you a hint. You use a while loop so that the loop occurs while some condition is satisfied. Now, what is the condition that must be satisfied for this while loop to keep running? It is that the user enters a number, right?
 
#5 ·
OK. Your total number of arguments is given by $#. So you can set up a counter starting at 1 and increment that counter until it is greater than the number of arguments. You convert the counter value into the name of the argument you want to look at, and you'll have it.

Take a look at how parameter expansions work. Pay attention to the discussion of indirection.

There is also an obscure brace expansion syntax that allows you to start at a specified point in an array and proceed for a specified number of elements. This works as well as a parameter expansion but you'll have a much harder time finding any information about it.

You can avoid the counter if you wish by looking at each command line variable, after you've obtained it by the appropriate expansion, and continue until you find an empty string for the variable.
 
Status
Not open for further replies.
You have insufficient privileges to reply here.
Top