PHP Program to Print an Arithmetic Progression Series

An arithmetic progression (AP) is a sequence of numbers in which the difference between any two consecutive terms is constant.

In this PHP program, we'll use inbuilt functions to generate and print an arithmetic progression series.

We'll also allow the user to specify the starting term, common difference, and the number of terms in the series.

PHP Program to Print an Arithmetic Progression Series

Here's the PHP program to print an arithmetic progression series using inbuilt functions:

<?php
// ap_series.php

// Function to generate and print an AP series
function printAP($a, $d, $n) {
    // Calculate the first 'n' terms of the AP series
    $apSeries = range($a, $a + ($n - 1) * $d, $d);

    // Print the AP series
    echo "Arithmetic Progression Series: ";
    echo implode(', ', $apSeries);
}

// Input from the user
$startTerm = readline("Enter the first term (a): ");
$commonDifference = readline("Enter the common difference (d): ");
$numberOfTerms = readline("Enter the number of terms (n): ");

// Convert input to integers
$startTerm = intval($startTerm);
$commonDifference = intval($commonDifference);
$numberOfTerms = intval($numberOfTerms);

// Call the function to print the AP series
printAP($startTerm, $commonDifference, $numberOfTerms);
?>

How the Program Works

  1. We define a function called printAP($a, $d, $n) that takes three arguments: the first term a, the common difference d, and the number of terms n.
  2. Inside the function, we calculate the first 'n' terms of the arithmetic progression series using the range() function. The range() function generates a range of values from the first term to the last term with the given step (common difference) between them.
  3. We then print the generated arithmetic progression series using the echo statement and implode() function to convert the array into a comma-separated string.
  4. Next, we take user input for the first term, common difference, and the number of terms using readline(). We convert the input to integers using intval().
  5. Finally, we call the printAP() function with the user-provided values to generate and print the arithmetic progression series.

Running the Program

To run this program, save it to a PHP file (e.g., ap_series.php) and execute it using the PHP command-line interface:

php ap_series.php

The program will prompt you to enter the first term, common difference, and the number of terms in the arithmetic progression series. After entering the values, the program will display the generated series.

Example Output

Here's an example of running the program:

Enter the first term (a): 2
Enter the common difference (d): 3
Enter the number of terms (n): 5
Arithmetic Progression Series: 2, 5, 8, 11, 14

In this example, we entered the first term 2, the common difference 3, and the number of terms 5, resulting in the arithmetic progression series 2, 5, 8, 11, 14.