Home >Backend Development >PHP Tutorial >PHP Program to Print Multiplication Table
Multiplication tables are fundamental mathematical tools used to display the products of a number multiplied by a range of values, typically from 1 to 10. This article explores several PHP methods for generating and displaying these tables.
The core formula for generating a multiplication table is straightforward:
<code>Result = Number × Multiplier</code>
Where:
Let's illustrate with examples:
Example 1:
Example 2:
Example 3:
Below, we'll examine different PHP approaches for generating multiplication tables.
Method 1: Direct Loop
This simple method uses a for
loop to iterate and calculate each multiple. It's efficient for smaller ranges.
Implementation:
<code class="language-php"><?php $number = 5; for ($i = 1; $i <= 10; $i++) { $result = $number * $i; echo "$number x $i = $result\n"; } ?></code>
Output: (Note the n
provides a newline character for better formatting)
<code>5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50</code>
Time Complexity: O(n) Space Complexity: O(1)
Method 2: Using a Function
This approach employs a function for reusability and better code organization.
Implementation:
<code class="language-php"><?php function generateTable($number) { for ($i = 1; $i <= 10; $i++) { echo "$number x $i = " . ($number * $i) . "\n"; } } $number = 7; generateTable($number); ?></code>
Output:
<code>7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70</code>
Time Complexity: O(n) Space Complexity: O(1)
Practical Applications:
Multiplication tables are essential in:
This article provided two clear and efficient ways to generate multiplication tables in PHP, catering to different programming styles and needs. The choice between a direct loop and a function depends on the context of your application.
The above is the detailed content of PHP Program to Print Multiplication Table. For more information, please follow other related articles on the PHP Chinese website!