Find the answer to your Linux question:
Results 1 to 3 of 3
How do I write a script that reads in ten numbers (either one at a time during script execution or as parameters) and prints to the screen the sum of ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Nov 2005
    Posts
    1

    NEWBIE: SCRIPT HELP


    How do I write a script that reads in ten numbers (either one at a time during script execution or as parameters) and prints to the screen the sum of these numbers?

    How do I then alter the script to allow it to work for arbitrary lists of numbers?

    THANX GUYS

  2. #2
    Linux User nalg0rath's Avatar
    Join Date
    Sep 2004
    Location
    Stockholm
    Posts
    303
    bash script:
    Code:
    #!/bin/bash
    echo `expr $1 + $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10`;
    pseudorandom numbers:
    Code:
    #!/bin/bash
    echo `expr $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM + $RANDOM`;
    (I think)

  3. #3
    Just Joined!
    Join Date
    Oct 2005
    Posts
    31
    By arbitrary I think you mean of variable length, am I correct? If you want a script that will take any number of paramaters and add them together, I would do it like this.

    #!/usr/local/bin/ruby
    sum = 0
    ARGV.each{|i| sum+= i.to_f}
    puts sum.to_s

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •