Many, many thanks to Franklin52, Murugaperumal, thillai_selvan, & Vivekraj. Franklin52's code is working great for me, and the other code is enlarging my shell knowledge base.
Does anyone know how I can code this for any number, x!?
Ex. "please enter a number: "
read some number
I don't know how to code the "some number" multiplication part.
Thank again,
Ccccc
I understand that "let" stores values in "var", and I theoritically understand that "++" increments the var values, but I don't really understand "++", or for that matter "--".
I know they are C operators, but I can't find any good explanations.
Is "++" saying "when you see me increase me by 1"??
Thanks,
Ccccc
increment(++) or decrement(--) value of var by 1(only).
If you want to increment/decrement the value of var by a different value you can use something like
i=0
while [ $i -lt 100 ]
do
let i+=10
echo $i
done
You can also use recursion to find the factorial of a number. In the following example the function factorial() calls itself repeatedly until it's argument is 1.
#!/bin/bash
factorial()
{
if (( $1 > 1 )); then
i=$(( $1 - 1 ))
j=$(factorial $i)
echo $(( $1 * $j ))
else
echo 1
fi
}
while :
do
read -p "Enter a number: " x
factorial $x
done
Try the following script
It will prompt the user to enter a number and perform the stuff
use strict;
use warnings;
print "Enter a number: ";
my $n = <>;#getting from stdin
my $i = 1;
my $res = 1;
$res *= $i++ while ($i <= $n) ;
print "Value: $res\n";
You can find the factorial of any number by following way.
f=1
echo "Enter a number"
read no
if [[ $no -le 1 ]];then
echo "Factorial of $no is:1"
else
#for fact in `seq $no`
for((fact=1;fact<=$no;fact++))
do
let f*=fact
done
echo "Factorial of $no is:$f"
fi