Breaking

Program to print digits in Ascending order

In the previous example, we saw a program to print digits in descending order. Now we will look into the following pattern where we will digits in ascending order.

Let's see the working example of the code and then we will look into line by line in-depth and how this code outputs in iteration.

$input = 5;

for ($i = 0; $i < $input; $i++) {
    for ($j = 1; $j <= ($i + 1); $j++) {
        echo $j . ' ';
    }
    echo PHP_EOL;
}

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


In the above example, as we always do, we will loop row-wise first and then column-wise.

So, let's understand the code line by line-

First, we will assign $i = 0 in the first for loop and will add a condition that this $i should always be less than the provided input $input to make sure that this will print 5 rows(depending upon $input value).
In the inner loop, we will assign $j = 1 because we want to print numbers starting from 1 and onwards. So in the next condition, $j should always be less than OR equal to ($i + 1) so that $j will always be compared to next value of the $i.
Here, we can make a little change in the main code to avoid confusion (if any).

$input = 5;

for ($i = 1; $i <= $input; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo $j . ' ';
    }
    echo PHP_EOL;
}

In this way, we have assigned $i = 1 because we do not want to give extra calculation in the inner loop. Basically, we avoided extra code inside inner loop. So in the inner loop we changed condition to $j <=$i.

Let's continue with this code and see what happens in the iteration.

First Iteration:
$input = 5;

for ($i = 1; $i <= $input; $i++) { //$i=1
    for ($j = 1; $j <= $i; $j++) { // 1<=1

        echo $j . ' ';
    }
    echo PHP_EOL;
}
//output
1

Second Iteration:
$input = 5;

for ($i = 1; $i <= $input; $i++) { //$i=2
    for ($j = 1; $j <= $i; $j++) { // 1<=2, 2<=2
        echo $j . ' ';
    }
    echo PHP_EOL;
}
//output
1  2

Third Iteration:
$input = 5;

for ($i = 1; $i <= $input; $i++) { //$i=3
    for ($j = 1; $j <= $i; $j++) { // 1<=3, 2<=3, 3<=3
        echo $j . ' ';
    }
    echo PHP_EOL;
}
//output
1  2  3

Fourth Iteration:
$input = 5;

for ($i = 1; $i <= $input; $i++) { //$i=4
    for ($j = 1; $j <= $i; $j++) { // 1<=4, 2<=4, 3<=4, 4<=4
        echo $j . ' ';
    }
    echo PHP_EOL;
}
//output
1  2  3  4

Fifth Iteration:
$input = 5;

for ($i = 1; $i <= $input; $i++) { //$i=5
    for ($j = 1; $j <= $i; $j++) { // 1<=5, 2<=5, 3<=5, 4<=5, 5<=5
        echo $j . ' ';
    }
    echo PHP_EOL;
}
//output
1  2  3  4  5 

No comments:

Post a Comment