find the nth square number in php

To find the nth square number, we can use a simple formula: n^2. We can also use a loop to find the nth square number by iterating from 1 to n and squaring each number. Here's some sample code in PHP:

main.php
<?php
$n = 5; // the nth square number we want to find
$square = $n ** 2; // using the formula n^2 to find the nth square number
echo "The $n th square number is $square.";

// Using a loop to find the nth square number
$number = 1;
for ($i = 1; $i <= $n; $i++) {
   $square = $number ** 2;
   $number++;
}
echo "The $n th square number is $square.";
?>
354 chars
14 lines

In the above code, we assign the value of n as 5. We first calculate the nth square number using the formula n^2 and store it in the $square variable. Then, we use a loop and iterate from 1 to n, and for each iteration, we square the current value of $number and store it in $square. Finally, we print the nth square number using echo statement.

gistlibby LogSnag