Calculate a specific number PHP - php

I have a for loop, where $i is 0, and it will run until $i reaches 4. I am trying to make a code that would output numbers in an order like this: 01, 11, 02, 12, 03, 13... etc... Now, the thing is next: when $i is 1, the script should make an order of those number in the boundaries of 1 and 20. When $i is 2, it would be 21 to 40, etc.
I've tried many things (mostly deleted), could not come up with anything that would work the right way.

The inner loop:
for ($j = 0; $j != 10; ++$j)
{
echo $j + 1 + 10 * ($i - 1);
echo $j + 1 + 10 * $i;
}

Try this piece of code;
<?php
$num = 4;
for($i=1;$i<($num + 1);$i++){
$string = "0" . $i . ", 1" . $i;
if($i<$num){
$string .= ", ";
}
echo $string;
}
?>

printf will format your numbers with a leading zero, as specified:
<?php
$format = "%02d ";
for ($i = 1; $i <= 4; $i++) {
$k = 2 * $i - 1;
for ($j = 1; $j <= 10; $j++) {
printf($format, ($k - 1) * 10 + $j);
printf($format, $k * 10 + $j);
}
echo "<br />";
}
?>

You can try:
<?php
$ten = 10;
for ($i = 0; $i<=4; ++$i)
{
echo "0".$i." , ";
echo $ten + $i."<br/>";
}
?>
Only change the range of $i
Thanks

Related

PHP loop and removing a character from the loop

Im doing a factorial loop test for college but I cannot figure this bit out. I want to do the factorial calculation and echo it but also to remove a bit of the calculation. So i want it to show:
Factorial of 5 is 120
5 x 4 x 3 x 2 x 1 = 120
But what i get is:
Factorial of 5 is 120
5 x 4 x 3 x 2 x 1 x = 120
This is the code I have so far Within php brackets
$i = $num;
do
{
echo strrev(" x $i ");
$i--;
} while($i > 0);
echo (" = $factorial");
You could increase your while() condition by one and add another echo after the loop (Demo), but I don't recommend it.
do-while() looping is not appropriate for your scenario if it is possible that $i = 1. You should use a pre-test loop. I am also using the combined "multiplication-assignment" operator to increase the end product.
Code: (Demo)
for ($i = 5, $product = 1; $i > 1; --$i) {
echo $i . ' x ';
$product *= $i;
}
echo $i . ' = ' . ($product * $i);
In a professional application, I'd probably use functional programming, but you are probably only doing this as an academic exercise. Regardless, here is one way that that style can look:
Code: (Demo)
$i = 5;
$range = range($i, 1);
printf(
'%s = %d',
implode(' x ', $range),
array_product($range)
);
This would do the trick:
$i = $num;
$factorial = 1;
$sep = "";
do {
echo "$sep $i";
$factorial = $factorial * $i;
$i--;
$sep = " x";
} while($i > 0);
echo (" = $factorial");
You can try this :
$i = $num;
$factorial = 1;
while($i > 0);
{
echo $i . ' x ';
//if($i>1) echo strrev(" x $i "); strrev would produce undesired output when $num is 10 or greater as pointed out by #wire
else echo $i;
$factorial = $factorial * $i;
$i--;
}
echo (" = $factorial");
Or use Ternary operator like :
$i = $num;
$factorial = 1;
while($i > 0){
echo( $i>1 ? $i . ' x ' : $i);
$factorial = $factorial * $i;
$i--;
}
echo (" = $factorial");
Conidering the input from #mickmackusa, I have modified my answer to fir the purpose.

Print pattern of increasing asterisks and zeros

How to print this Pattern?
$number = 5;
for ($i=1; $i <= $number ; $i++) {
for ($j=$i; $j >= 1;$j--){
echo "0";
}
echo "\n";
}
Prints
0
00
000
0000
00000
I've tries like this, but i'm confused to print star and Zero char
for ($i=1; $i <= $number ; $i++) {
$sum = 0;
for ($j=$i; $j >= 1;$j--){
$sum +=$j;
}
echo $i ." => " .$sum ."\n";
}
Prints
1 => 1
2 => 3
3 => 6
4 => 10
5 => 15
You can use str_repeat to generate the strings of required length. Note that for triangular numbers (1, 3, 6, 10, 15, ...) you can generate the i'th number as i(i+1)/2:
$number = 5;
for ($i = 1; $i <= $number; $i++) {
echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org
For a more literal generation of the triangular part of the output (i.e. sum of the numbers from 1 to i), you could use this code which adds $i *'s and 1 0 to the output on each iteration:
$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
$line = str_repeat('*', $i) . $line . '0';
echo $line . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org
Here is another way, which uses a more literal reading of the replacement logic. Here, I form each subsequent line by taking the previous line, and adding the line number amount of * to the * section, and then just tag on a new trailing zero.
$line = "*0";
$max = 5;
$counter = 1;
do {
echo $line . "\n";
$line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);
This prints:
*0
***00
******000
**********0000
***************00000
The number of zeros are equal to $i in the for loop. So we just need to calculate the number of stars and then simply do a str_repeat
$count = 5;
for ($i=1; $i <= $count; $i++) {
$stars = 0;
for($j=1; $j <= $i; $j++) {
$stars = $stars + $j;
}
echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}
Output:
*0
***00
******000
**********0000
***************00000
$line = '';
for ($i = 1; $i <= 5; $i++) {
$line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length
echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.
}

For loop (php) that results in this: 12345678910987654321

My niece is trying to create one for-loop (php), that results in this:
* 12345678910987654321
example for loop she tried:
for ($i = 1; $i <= 10; $i++ , $i = 10; $i <= 1; $i--) {
echo $i . ' ';
}
She can only use if's and elseif's. I'm not a programmer and can't really help her. Any ideas how this could be achieved in php?
Any information would be greatly appreciated.
The key is to add a variable instead of a number, then reverse that number when $i hits 10.
for($i = 1, $j = 1; $i> 0; $i+=$j) // Start i at 1, and j at 1
{
echo $i;
if($i == 10)
$j = -1; // i has hit 10, so use -1 to start subtracting
}
Another possibility is to loop up to 20, printing $i for the ascending part and 20 - $i for the descending.
for ($i = 1; $i < 20; $i++) {
if ($i <= 10) {
echo $i;
} else {
echo 20 - $i;
}
}

Why is the answer of $sum 6?

<?php
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
I'm going through PHP on TeamTreehouse.com, whilst learning php this was one of the quiz question, the answer is 6. I don't know why the answer is 6, can someone explain?
The variable $i is initialized by 0 (zero).
Before the condition if ($i < $total) is tested $i is incremented by 1. So even the first time it equals 1.
In the third pass $i equals 3, and in the fourth pass it equals 4 which is NOT < $total.
Therefore only 3 of the 4 elements of $numbers are summed up: 1 + 2 + 3, which equals 6.
See the comments in the code below:
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); // Gives 4
$sum = 0;
$output = "";
$i = 0; // $i = 0
foreach($numbers as $number) {
$i = $i + 1; // $i = 1, even at the first time
// after 3 passes $i is equal to $total (=4)
if ($i < $total) { // So, only 3 of the 4 elements of $number are honored
$sum = $sum + $number;
}
}
echo $sum; // Thus $sum = 1 + 2 + 3 = 6
// The last element (=4) is never summed up
?>
This would sum up all 4 elements, giving 10 as the result:
foreach($numbers as $number) {
if ($i < $total) {
$sum = $sum + $number;
}
$i = $i + 1;
}
<?php
$numbers = array(1,2,3,4);
$total = count($numbers); #value of $total is 4 here
$sum = 0;
$output = ""; #intital empty
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
if ($i < $total) {
$sum = $sum + $number;
}
}
echo $sum;
?>
You increment the $i by 1 so it becomes 1 which is smaller than $total(which is 4). Your program will add till $i become 4. It just add first three number in your array.
1+2+3=6.
That's why you are getting 6.
I hope you get it. :)
The condition limits the iterations. When $i is 4 it is no longer less than $total and so the last number doesn't get added.

Make pattern of asterisks and zeros in increasing lengths

I'm trying to echo stars and zero like the pattern below
*
***0
******00
**********000
The length of the asterisks grows by an increasing factor (in a ballooning fashion) -- the previous number of asterisks plus the current iteration number.
iteration 1: 1 (0 + 1)
iteration 2: 3 (1 + 2)
iteration 3: 6 (3 + 3)
iteration 4: 10 (6 + 4)
iteration 5: 15 (10 + 5)
etc
The length of the zeros increases by a static factor.
iteration 1: 0
iteration 2: 1
iteration 3: 2
iteration 4: 3
iteration 5: 4
etc
My code currently looks like this:
for ($i=0; $i<=10; $i++)
{
echo "*";
for ($j=0; $j<$i; $j++)
{
echo "*";
}
for ($z=0; $z<$i; $z++)
{
echo "0";
}
echo "</br>";
}
However I'm getting this result:
*
**0
***00
****000
*****0000
******00000
The number of stars is indicated by triangle numbers, 1, 1+2, 1+2+3. You want to increment your inner loop max value by $i with every iteration:
$k = 0;
for ($i=1; $i<=10; $i++)
{
$k += $i;
for ($j=1; $j<=$k; $j++)
{
echo "*";
}
...
}
This is also a good case where your loops should be initialized with 1 rather than 0, because it is more intuitive. 0-based loops work best when you are working with arrays.
I think something like this is more efficient; you can cache the current sequence of stars and zeros.
$cache_star = "";
$cache_zero = "";
for ($i=1; $i<=10; $i++)
{
for ($j=1; $j<=$i; $j++)
{
$cache_star .= "*";
}
echo $cache_star.$cache_zero;
$cache_zero .= "0";
}
Here's what I got:
for($i = 1; $i != 5; $i++)
{
$triangle = (0.5 * $i) * ($i + 1);
echo str_repeat('*', $triangle) . str_repeat('0', $i) . PHP_EOL;
}
Uses the formula 0.5n(n + 1) - the triangle numbers formula.
Example output:
*0
***00
******000
**********0000
I quite like #jordandoyle's approach, but I correct the zeros pattern by subtracting 1 from $i in the second str_replace()..
Code: (Demo)
$number = 5;
for ($i = 1; $i <= $number; ++$i) {
echo str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
. PHP_EOL;
}
Output:
*
***0
******00
**********000
***************0000
If this answer lacks significant uniqueness versus an earlier answer, I'll include a recursive approach as well (instead of a classic loop).
Code: (Demo)
function printLines($i, $lines = [], $newline = PHP_EOL) {
if ($i > 0) {
array_unshift(
$lines,
str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
);
printLines(--$i, $lines);
} else {
echo implode($newline, $lines);
}
}
printLines(5);
You can even copy the previous line and insert it into the middle of the next line to form the desired pattern. This is the functional-style equivalent of #CoertMetz's nested loop technique.
Code: (Demo)
$number = 5;
$line = '';
for ($i = 1; $i <= $number; ++$i) {
echo (
$line = str_repeat('*', $i)
. $line
. ($i > 1 ? '0' : '')
)
. PHP_EOL;
}
All above techniques deliver the same result.
Smells like homework... But ok, what about this:
$star = "*";
echo $star."\n";
for ($i=0; $i<=10; $i++)
{
$star = $star."**";
echo $star;
echo str_repeat("0", $i+1);
echo "\n";
}
Outcome:
*
***0
*****00
*******000
*********0000
***********00000
*************000000
***************0000000
*****************00000000
*******************000000000
*********************0000000000
***********************00000000000
Demo:
http://sandbox.onlinephpfunctions.com/code/583644f782005adb9e018b965cbbdefaf63c7c79

Categories