w3resource logo


php exercises

PHP Challenges: Check a sequence of numbers is an arithmetic progression or not

PHP Challenges - 1: Exercise-15 with Solution

Write a PHP program to check a sequence of numbers is an arithmetic progression or not.

Input : array(5, 7, 9, 11)
Output : An arithmetic sequence

In mathematics, an arithmetic progression or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant.
For example, the sequence 5, 7, 9, 11, 13, 15 ... is an arithmetic progression with common difference of 2.

Explanation :

PHP: Check a sequence of numbers is an arithmetic progression or not

Sample Solution :-

PHP Code :

<?php
function is_arithmetic($arr)
  {
   $delta = $arr[1] - $arr[0];
   for($index=0; $index<sizeof($arr)-1; $index++)
    {
        if (($arr[$index + 1] - $arr[$index]) != $delta)
        {
             
             return "Not an arithmetic sequence";
        }       
    }
    return "A arithmetic sequence";
}
$my_arr1 = array(6, 7, 9, 11);
$my_arr2 = array(5, 7, 9, 11);

print_r(is_arithmetic($my_arr1)."\n");
print_r(is_arithmetic($my_arr2)."\n");
?>

Output :

 Not an arithmetic sequence                                  
A arithmetic sequence  

Flowchart:

PHP Flowchart: Check a sequence of numbers is an arithmetic progression or not

PHP Code Editor:

<?php
function is_arithmetic($arr)
  {
   $delta = $arr[1] - $arr[0];
   for($index=0; $index<sizeof($arr)-1; $index++)
    {
        if (($arr[$index + 1] - $arr[$index]) != $delta)
        {
             
             return "Not an arithmetic sequence";
        }       
    }
    return "A arithmetic sequence";
}
$my_arr1 = array(6, 7, 9, 11);
$my_arr2 = array(5, 7, 9, 11);

print_r(is_arithmetic($my_arr1)."\n");
print_r(is_arithmetic($my_arr2)."\n");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.