i have:
# = 1
# = 0,5
% = 0
max = 10
for example if i have: 3 then should show me:
###$$$$$$$
if i have 3,5 :
####$$$$$$
etc
if i have 3,99 then = 3,5
if i have 3,49 then = 3,0
etc
how can i use this with foreach or for?
for whole number i can make:
$number = 8;
$one = 10 - $number;
$three = 0 + $number;
and
for($i=1;$i <= $one){
echo "#";
}
for($i=1;$i <= $three){
echo "$";
}
but how is the best solution if $number = 3,57
If I've understood what you're after, this should do what you want:
<?php
function printItOut($number) {
$s = '';
for ($i = 0; $i < 10; $i++) {
if ($i < $number%10) {
$s .= '#';
} else if ($i < ($number+0.5)%10) {
$s .= '#';
} else {
$s .= '$';
}
}
return $s;
}
echo printItOut(3.49), "\n";
echo printItOut(3.5), "\n";
echo printItOut(3.99), "\n";
echo printItOut(4), "\n";
Outputs:
###$$$$$$$
####$$$$$$
####$$$$$$
####$$$$$$
Inside the for loop, I using the modulus operator to find the integer remainder of dividing $number by 10. So 3%10 gives a result of 3, 3.49%10 also results in 3.
In the first 'else if' block, I'm checking whether the number is 0.5 or more, since (3.49+0.5) is 3.99, and 3.99%10 is 3; but 3.5+0.5 is 4, and 4%10 is 4.
Related
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.
I want to give n as a input and get a pattern like this.
pattern If n = 4
1
222
33333
4444444
33333
222
1
What is the perfect way to achieve this?
I have tried. But my code is not good! Is there any way to do this with less and clear code!?
echo '<pre>';
$n=4;
for ($i=1; $i <= $n*2-1; $i++) {
if($n<$i){ //bottom part
$scount=$i-$n;
$iterator = 0;
while($iterator != $scount){
$iterator++;
echo ' ';
}
$num = ($n*2)-$i;
$loop = $num*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $num;
}
}elseif ($n==$i){ // middle part
$loop = $i*2-1;
$iterator = 0;
while ($iterator != $loop) {
$iterator++;
echo $i;
}
}else{ //top part
$scount = $n-$i;
$iterator=0;
while ($iterator != $scount) {
$iterator++;
echo ' ';
}
$loop = $i*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $i;
}
}
echo "<br>";
}
?>````
On a similar line to the other answers, but this builds a string with the output. This allows it to build each of the repeating lines in the loop and add it to the start and end of the result string. This means the loop is only run $n-1 times (plus the first line which sets the middle line)...
$n=4;
$output = str_repeat("$n", (2*$n)-1).PHP_EOL;
for ( $i = $n-1; $i>0; $i-- ) {
$line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1);
$output = $line.PHP_EOL.$output.$line.PHP_EOL;
}
echo $output;
Two for loops which repeats the number of spaces needed and characters.
$n = 4;
for($i=1;$i<=$n;$i++){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
for($i=$n-1;$i>0;$i--){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
https://3v4l.org/1hK3s
You can solve this by noticing the longest line is the one with the max value of n, and that has 2*n-1 n's in it. All other lines need spacing to make them line up with that one which will be half the difference between the number of n's on that line and the number on the longest line. str_repeat is a good way of generating those repeated strings:
echo "<pre>\n";
$n=4;
$max_length = $n * 2 - 1;
for ($i = 1; $i <= $n * 2 - 1; $i++) {
$this_n = ($i <= $n) ? $i : $n * 2 - $i;
$num_ns = $this_n * 2 - 1;
echo str_repeat(' ', ($max_length - $num_ns) / 2);
echo str_repeat("$this_n", $num_ns);
echo "\n";
}
echo '</pre>';
Output:
<pre>
1
222
33333
4444444
33333
222
1
</pre>
Demo on 3v4l.org
So i have a simple for loop to get this result from any given number (get).
1 + 2 + 3 + 4 = 10
$num = intval($_GET["number"]);
$total = 0;
for ($i = 1; $i <= $num; $i++) {
echo $i;
if ($i != $num) {
echo " + ";
}
$total += $i;
}
echo " = " . $total;
Now I want to show the calculation of every step
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
And it should be done with an Array, but I can't seem to figure out the Algorithm.
I think I'm overlooking something simple here.
Try something like this:
<?php
$num = intval($_GET["number"]);
//add all numbers to an array
$numbers = array();
for ($i = 1; $i <= $num; $i++)
{
$numbers[] = $i;
//show each array element with ' + ' in between the elements
echo implode(' + ', $numbers);
//show total sum
echo " = " . array_sum($numbers) . "\n";
}
?>
Note that this does not work, if $_GET['number'] is zero or even below zero.
Here's the simplest way I can think...
$num = intval($_GET['number']);
$intArray = range(1,$num);
echo implode(" + ",$intArray)." = ".array_sum($intArray);
You don't actually need a loop to do an arithmetic progression. An arithmetic progression like this can be calculated in constant time with the formula n * (n[-1] + n[1]) / 2.
For example the progression of 4, where n1 = 1, n2 = 2, n3 = 3, and n4 = 4 is simply 4 * (4 + 1) / 2 == 10.
function progression($n) {
return $n * ($n + 1) / 2;
}
echo progression(4); // 10
However, to show the result of the progression at any given step you simply limit the upper-bound of that progression (i.e. $n).
$n = 4;
for ($i = 1; $i <= $n; $i++) {
$operands = implode('+', range(1, $i));
echo $operands . " = " . progression($i), "\n";
}
output
1 = 1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10
Generalization
This works for any linear arithmetic progression, regardless of the upper/lower bound. So for example the progression of 5 through 8 is still 4 * (5 + 8) / 2 which gives you 26.
So you can modify this function to a more general solution for any linear arithmetic progression as such.
function progression($size, $start = 1) {
return $size * ($start + ($size + $start - 1)) / 2;
}
$n = 4;
$start = 5;
for ($i = $start; $i <= $n + $start - 1; $i++) {
$operands = implode('+', range($start, $i));
echo $operands . " = " . progression($i - $start + 1, $start), "\n";
}
output
5 = 5
5+6 = 11
5+6+7 = 18
5+6+7+8 = 26
So assuming you are doing a range from the $_GET['number'] number then you can do something like (see comments in code for further explanation):
//This will create an array from 1 to number inclusive
$nums = range(1, $_GET['number']);
//The nums that have been used
$used = array();
//Now loop over that array
foreach($nums as $num){
$used[] = $num; //Add this number to used
if(count($used) > 1){//Dont care about first loop
echo implode(' + ', $used); // put all elements together by + sign
echo ' = ' . array_sum($used) . "<br>"; //Show total plus a break
}
}
<?php
$num = intval($_GET["number"]);
$terms = [1];
for ($i = 2; $i <= $num; $i++) {
$terms[] = $i;
$sum = array_sum($terms);
echo implode(' + ', $terms) . ' = ' . $sum . PHP_EOL;
}
Going for maximum use of PHP array related functions:
$num = intval($_GET["number"]);
$array = range(1, $num);
for ($i = 2; $i <= $num; $i ++)
{
$slice = array_slice($array, 0, $i);
$total = array_sum($slice);
echo implode(" + ", $slice) . " = " . $total . PHP_EOL;
}
Alternative with array_push
$num = intval($_GET["number"]);
$array = array(1);
for ($value = 2; $value <= $num; $value ++)
{
array_push($array, $value);
echo implode(" + ", $array) . " = " . array_sum($array) . PHP_EOL;
}
Output
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
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