Friday, February 6, 2015

Factorial Number Solver in PHP

This code will compute for the factorial value of the given number by our user. What is good about my code is that I included value validation to check if the given number is truly an integer not special character or letters or words before our program will solve the factorial equivalent of the number which is given by our user.

If you have some questions please send me an email at jakerpomperada@yahoo.com and jakerpomperada@gmail.com. People here in the Philippines who wish to contact me can reach me at my mobile number 09173084360.

Thank you very much and Happy Productive Programming.





Program Listing

<html>
<title> Factorial Number Solver </title>
<style>
body { 
  font-size:20px; 
  font-family:arial;
  color:blue;
  } 
</style>
<?php
error_reporting(0);

$values = $_POST['value'];

 // function to solve of the factorial value

 function factorial_solve($variable) {
    if ($variable == 0)
        return 1;
    else
        return($variable * factorial_solve($variable - 1));
}

if(isset($_POST['check'])) {

     if (ctype_alpha($values)) {
      echo "<script>";  
  echo "alert('PLEASE ENTER A NUMERIC VALUE.');";
  echo "</script>";
  $values="";
 }
 
else if(preg_match('#[^a-zA-Z0-9]#', $values)) {
      echo "<script>";  
  echo "alert('PLEASE ENTER A NUMERIC VALUE.');";
  echo "</script>";
        $values="";
      
}

    else  if ($values=="") {
      echo "<script>";  
  echo "alert('It Cannot Be Empty!!! Please enter a integer value.');";
  echo "</script>";
  $values="";
           }
else { 
      $title = "The factorial value of ".$values." is " .factorial_solve($values).".";
       }  
   }  

if(isset($_POST['clear'])) {
  $values=" "; 
  $title=" ";
  
}

?>
<body style='background-color:lightgreen'>
<div style='width:800px;margin:auto'>
  <br> <h1 align="center">Factorial Number Solver </h2>
  <br>
<form action="" method="post">
 Enter a Number : <input type="text" name="value"    value="<?php echo $values; ?>" autofocus  size=20/>
   <input type="submit" name="check" value="Find Factorial Value" 
  title="Click here to know the factorial value of the given number."/>
  <input type="submit" name="clear" value="Clear" 
  title="Click here to clear text box and values on the screen"/>
</form>

<br> <br>

<?php 
echo $title;
 ?>
  </body>

</html>


DOWNLOAD SOURCE CODE HERE

No comments:

Post a Comment