Hacker Rank Solutions in PHP - Day 05 - Loops

30 Days of Code - Day 5: Loops

Task
Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1<= i <= 10) should be printed on a new line in the form: n x i = result.

Example
n = 3

The printout should look like this:

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30

 

Solution in PHP:

You can accomplish this task by using a simple for loop to iterate from 1 to 10 (or any desired number of multiples) and printing the result of multiplying the input integer $n with the loop variable. Here's the PHP code to do that:

<?php

   $n = intval(trim(fgets(STDIN)));

   for ($i = 1; $i <= 10; $i++) {

      $result = $n * $i;

      echo "$n x $i = $result\n";

   }

This code reads an integer input $n, and then it uses a for loop to iterate from 1 to 10. Inside the loop, it calculates the result by multiplying $n with the loop variable $i and prints the result in the desired format.

Press ESC to close