For Loop/PHP

Ads
 

For Loop/PHP

Write a class called math. It is to have one property called num. It also has one method called factorial. This method is to start at 1 and multiply all of the integers to num. If num is 5 then you would multiply 12345. How would you write this as a loop? Would I need to use the for loop or do/while loop?

View Answers

September 27, 2012 at 11:28 AM

PHP Factorial Example:

<?php 
$n = 5;
$i = 1;
$f = 1;
while($i<$n){
$i = $i + 1;
$f = $f * $i;
}
echo $f; 
?>

September 27, 2012 at 11:29 AM

Here is a java example that finds the factorial of a number.

public class math{
public static long factorial(int n){
if(n <= 1) 
return 1;
else
return n * factorial(n - 1);
}
public static void main(String [] args){
    int num=5;
System.out.println(factorial(num));
}
}

Ads









Related Tutorials/Questions & Answers:
How to call Array Length for loop in PHP
How to call Array Length for loop in PHP  Hello, I am learner in PHP scripting Language. How can I use the array length for loop in PHP programming language? Kindly provides online help guide or reference links. Thanks
For Loop/PHP
12345. How would you write this as a loop? Would I need to use the for loop or do/while loop?   PHP Factorial Example: <?php $n = 5; $i = 1; $f...For Loop/PHP  Write a class called math. It is to have one property
Advertisements
foreach Loop
foreach Loop In PHP, for & foreach loop executes code block a specific number of times, or until condition fails. The for Loop The for loop executes... to loop. Given below the example : <html> <body> <?php
while & do..while Loop
while & do..while Loop while loop The while loop iterate until provided...; <?php $j=1; while($j<=3) { echo "Value of j" . $j . "<... loop always executes its block of code at least once. Given below the syntax
PHP Regular Expression
& POST PHP Loop PHP Arrays PHP Strings PHP Date...PHP regular expression allows programmer to perform various task like... strings. PHP Regular expression also allows you to validate a email, phone

Ads