w3resource

PHP Exercises: Check if a given positive number is a multiple of 3 or a multiple of 7

PHP Basic Algorithm: Exercise-10 with Solution

Write a PHP program to check if a given positive number is a multiple of 3 or a multiple of 7.

Sample Solution:

PHP Code :

<?php
// Define a function named "test" that takes a parameter $n
function test($n) 
{
    // Use the modulo operator to check if $n is divisible by 3 or 7
    return $n % 3 == 0 || $n % 7 == 0;
}

// Call the test function with argument 3 and var_dump the result
var_dump(test(3));

// Call the test function with argument 14 and var_dump the result
var_dump(test(14));

// Call the test function with argument 12 and var_dump the result
var_dump(test(12));

// Call the test function with argument 37 and var_dump the result
var_dump(test(37));
?>

Explanation:

  • Function Definition:
    • The function test takes one parameter, $n.
  • Divisibility Check:
    • Uses the modulo operator % to check if $n is divisible by either 3 or 7.
    • Returns true if $n is divisible by 3 ($n % 3 == 0) or by 7 ($n % 7 == 0); otherwise, returns false.
  • Function Calls and Output:
    • First Call: test(3)
      • 3 % 3 == 0, so it returns true.
    • Second Call: test(14)
      • 14 % 7 == 0, so it returns true.
    • Third Call: test(12)
      • 12 % 3 == 0, so it returns true.
    • Fourth Call: test(37)
      • 37 is not divisible by either 3 or 7, so it returns false.

Output:

bool(true)
bool(true)
bool(true)
bool(false)

Visual Presentation:

PHP Basic Algorithm Exercises: Check if a given positive number is a multiple of 3 or a multiple of 7.

Flowchart:

Flowchart: Check if a given positive number is a multiple of 3 or a multiple of 7.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string with the last char added at the front and back of a given string of length 1 or more.
Next: Write a PHP program to create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back. If the given string length is less than 3, use whatever characters are there.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-10.php