LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   using vi for scripting (https://www.linuxquestions.org/questions/linux-newbie-8/using-vi-for-scripting-4175423460/)

ajjc2005 08-22-2012 12:04 PM

using vi for scripting
 
I need to write a program that takes a number and shows the result of n!

Example: 5!=1*2*3*4*5

Thank you in advance for your help.

jkirchner 08-22-2012 12:16 PM

Hmmm, is this homework? If so, please post what you have done so far.

Also, VI is an editor, what programming language are you supposed to be writing this program in?

ajjc2005 08-22-2012 12:23 PM

I'm not sure if I should be using if or a while loop or something else


echo "Please enter a number"
read num
count=0
total=0
if test $count -lt $num
then
let count=$count+1
let total=$num*$count
fi
echo $total

TB0ne 08-22-2012 01:35 PM

Quote:

Originally Posted by ajjc2005 (Post 4761292)
I need to write a program that takes a number and shows the result of n!

Example: 5!=1*2*3*4*5

Thank you in advance for your help.

You don't have anything in your script to ask for a second (or subsequent) value. You should prompt the user for more input, and tell them something like "Press Z to multiply your values", so the user can decide when they're done. Something like this:
Code:

#!/bin/Bash
echo "Enter the numbers to be Multiplied:"
read n1
read n2
answer=`expr $n1 \* $n2`
echo $answer

...may give you an idea. It's only two variables now, but can be expanded.

WzJazz 08-22-2012 01:37 PM

Also, do a google search on factorial, factorial bash or factorial programming.

chrism01 08-22-2012 06:03 PM

Hi TB0ne,
the OP is asking about factorial calcs https://en.wikipedia.org/wiki/Factorial, not just any multiplication set. ;)

Vegan 08-22-2012 10:36 PM

Quote:

Originally Posted by ajjc2005 (Post 4761305)
I'm not sure if I should be using if or a while loop or something else


echo "Please enter a number"
read num
count=0
total=0
if test $count -lt $num
then
let count=$count+1
let total=$num*$count
fi
echo $total

A while loop will be perfect for what you are trying to achieve

David the H. 08-22-2012 11:40 PM

I'm curious what you mean about "using vi", for scripting. As mentioned, vi is just a text editor. However it is possible to write scripted input for it to edit files automatically.

None of that has much to do with shell arithmetic, however. Probably the easiest way to do a factorial (assuming integer input, of course), is with a simple c-style for loop.

clocker 08-23-2012 08:13 AM

if you need help on using vi, i can help but otherwise you should put your thread on the programming forum.


All times are GMT -5. The time now is 11:35 PM.