Breaking

Program to print digits in descending order

We will first take a look at the example then will understand about it line by line-

$input = 5;
for ($i = 0; $i < $input; $i++) {
    for ($j = $input; $j > 0; $j--) {
        if ($i != $j)
            echo $j . ' ';
        else
            break;
    }
    echo PHP_EOL;
}

// output
5  4  3  2  1
5  4  3  2
5  4  3
5  4
5

Where,
$input - is the number on which you are required to perform an operation.
Then we start with two for loop because we need to print horizontally(row-wise) and then vertically(column-wise).
Second loop OR inner loop works as follows-
we have set $j = $number because we have to print number starting from bigger number. Then we make sure that $j should be greater than 0 to make sure that maximum value set in $number which is now assigned to $j in the decreasing order will be routed and will be printed.
Now we are set to print number in decreasing order. Like below-

$input = 5;
for ($i = 0; $i < $input; $i++) {
    for ($j = $input; $j > 0; $j--) {
        //if ($i != $j)
            echo $j . ' ';
      //  else
         //   break;
    }
    echo PHP_EOL;
}

This code will print digits as follows-
5  4  3  2  1
5  4  3  2  1
5  4  3  2  1
5  4  3  2  1
5  4  3  2  1

Now, we need to make sure that, this code will print numbers in descending order with maximum numbers in first column and decreasing order likewise. So, to make sure that this should work then we need to add a condition which let this happen.

First Iteration:
$input = 5;
for ($i = 0; $i < $input; $i++) { // $i=0
    for ($j = $input; $j > 0; $j--) { // $j=5, $j=4, $j=3, $j=2, $j=1 
        if ($i != $j)
           echo $j . ' ';
        else
           break;
    }
    echo PHP_EOL;
}

// output
5  4  3  2  1


Second Iteration:
$input = 5;
for ($i = 0; $i < $input; $i++) { // $i=1
    for ($j = $input; $j > 0; $j--) { // $j=5, $j=4, $j=3, $j=2
        if ($i != $j)
           echo $j . ' ';
        else
           break;
    }
    echo PHP_EOL;
}

// output
5  4  3  2


Third Iteration:
$input = 5;
for ($i = 0; $i < $input; $i++) { // $i=2
    for ($j = $input; $j > 0; $j--) { // $j=5, $j=4, $j=3
        if ($i != $j)
           echo $j . ' ';
        else
           break;
    }
    echo PHP_EOL;
}

// output
5  4  3


Fourth Iteration:
$input = 5;
for ($i = 0; $i < $input; $i++) { // $i=3
    for ($j = $input; $j > 0; $j--) { // $j=5, $j=4
        if ($i != $j)
           echo $j . ' ';
        else
           break;
    }
    echo PHP_EOL;
}

// output
5  4


Second Iteration:
$input = 5;
for ($i = 0; $i < $input; $i++) { // $i=4
    for ($j = $input; $j > 0; $j--) { // $j=5
        if ($i != $j)
           echo $j . ' ';
        else
           break;
    }
    echo PHP_EOL;
}

// output

No comments:

Post a Comment