Friday, September 19, 2008

Small math ( factorial ) basic program with perl

Hi guys , today we are going to some math programs

for development of our logical ability in that way we need to think of the programming ways


Simple Factorial Calculations

The definition of a factorial:

n! = n x (n-1) x (n-2) x ... x 1

Calculate the factorial of 6:

#!/usr/bin/perl
#Factorial of 6
print 6*5*4*3*2*1;
print "\n";

Now, let's use a variable!

#!/usr/bin/perl
#Factorial of 6
$n = 6;
print $n * ($n-1) * ($n-2) *
($n-3) * ($n-4) * ($n-5);
print "\n";

Now, lets use 2 variables:

#!/usr/bin/perl
#Factorial of 6
$f = 1;
$n = 6; $f = $f * $n;
$n = $n - 1; $f = $f * $n;
$n = $n - 1; $f = $f * $n;
$n = $n - 1; $f = $f * $n;
$n = $n - 1; $f = $f * $n;
$n = $n - 1; $f = $f * $n;
print "$f\n";

This is great, we can actually calculate something; however, our script depends on what the input number is! We have to modify the script for every factorial -- bad!

We need ways to automate this script!



Basic Looping

Let's learn the white loop today. It looks like this...

while (condition) {
instructions;
}

The curly brackets, { and } are crucial and required. The instructions can be any number of Perl statements, like print: they are grouped together by the curly brackets. The condition is a statement that tells Perl under what conditions to execute the instructions.

When Perl gets to the while loop, it checks the condition. If it is "true", then it executes the instructions. When it is done with the instructions, it checks the condition again, etc. It never stops this "loop" until the condition is "false".

Examples: are the following True or False?

false:    0
true: -12.5
true: 1 == 3-2
true: $x = 4
true: $x <= $x ** 2 / 4
true: $x == 4
false: $x > 0 && $x < 0

true: $my = "Hero"
false: "Dog" eq $my
false: "Dog" eq $hero # $hero is undefined!
true: $hero eq undef
false: !($my ne $hero)

false: 4==4 && 5==3 || 1==0
false: 4==4 && (5 == 3 || 1 == 0)
true: 4==4 && !(5 == 3 || 1 == 0)

What are conditions?

Boolean logic that evaluates to "true" or "false".

Numerical: Zero is "false" and non-zero is "true". Comparison operators: ==, !=, <, <=, >, =>

Text: undefined is "false" and defined is "true". Comparison operators: eq, ne, lt, le, gt, ge

Logical grouping
Or: ||
And: &&
Not: !
Grouping: ( ... )

Order of operations

**
! -
* /
+ - .
< > >= <= lt gt le ne
== != eq ne
&&
||

Basic Looping Part 2

Now we can write a better factorial program!

#!/usr/bin/perl
$n = 6;
$f = 1;
while ($n > 0) {
$f = $f * $n;
$n = $n - 1;
}
print "$f\n";

Another example, print out your name 100 times

#!/usr/bin/perl
$n = 0;
while ($n < 100) {
print "Your Name\n";
$n = $n + 1;
}

Print a 2D table of numbers:

#!/usr/bin/perl
$n = 0;
while ($n < 10) {
$m = 0;
while ($m < 10) {
$mult = $n * $m;
print "$mult ";
$m = $m + 1;
}
print "\n";
$n = $n + 1;
}

No comments: