PHP Dubble For Loop - php
I need to make a loop in php that says 1*9 = 9 2*9 = 18 and 1*8 = 8 and 1*7 = 7 etc in loop so the result will be this:
1*7 = 7
2*7 = 14
3*7 = 21
1*8 = 8
2*8 = 16
3*8 = 24
1*9 = 9
2*9 = 18
3*9 = 27
And I need to use a nested loop for that i tried some things out but i cant get it to work here is what is did. But for the most part i don't really understand what nested loops do and what there used for. hope you can help me thanks!
for ($tafel7 = 0; $tafel7 <= 9; $tafel7++) {
for($tafel7 = 0; $tafel7 <= 9; $tafel7++){
for($tafel7 = 0; $tafel7 <= 9; $tafel7++){
$antwoord9 = $tafel7 * 9;
echo "$tafel7 x 8 = $antwoord9 <br>";
$antwoord8 = $tafel7 * 8;
echo "$tafel7 x 8 = $antwoord8 <br>";
$antwoord7 = $tafel7 * 7;
echo "$tafel7 x 7 = $antwoord7 <br>";
};
};
};
Your question is not as clear but if you just want the exact result, here's the code:
for($i = 7; $i <= 9; $i++){
for($j = 1; $j <= 3; $j++){
$result = $i * $j;
echo $j." * ".$i." = ".$result."<br>";
}
}
If you need to print complete tables, then try this:
for($i = 1; $i <= 9; $i++){
for($j = 1; $j <= 10; $j++){
$result = $i * $j;
echo $i." * ".$j." = ".$result."<br>";
}
}
As far as the explanation is concerned, then listen:
A normal loop works by executing a block of statement(s) again and again until a condition is met.
So, nested loops are basically loops in another loop. This means that the block of code will be executed 'n' number of times by the inner loop, and then the inner loop will again be executed by the outer loop, again 'n' number of times.
'n' means whatever the number of times the conditions are met for the respective for loops.
Hope you got my explanation!
You need to loop over your two variables, (1) the left operand and (2) the right operand
for ($right = 7; $right <= 9; $right++) {
for ($left = 1; $left <= 3; $left++) {
$product = $left * $right;
echo "{$left} x {$right} = {$product} <br>";
}
}
In this example, I have to loops one with the times table you want eg 7, 8 and 9 "tafel" and the other one with how many times you want it to run for each times table "$hoeveel". This can easily be altered to more times tables or how many times you want to run, you also only need to export the values once as it cycles through the loops anyways. Hope it helps.
for ($tafel = 7; $tafel <= 9; $tafel++) {
for ($hoeveel = 1; $hoeveel <= 3; $hoeveel++) {
$antwoord = $tafel * $hoeveel;
echo "$tafel x $hoeveel = $antwoord <br>";
}
}
Related
Exam Qn: Convert do while loop to for loop (PHP)
Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam: "Convert the following script using for loop without affecting the output:-" <?php //Convert into for loop $x = 0; $count = 10; do { echo ($count. "<BR>"); $count = $count - 2; $x = $x + $count; } while($count < 1) echo ($x); ?> Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change. Try: $count = 10; $x = 0; $firstRun = true; for(; $count > 1 || $firstRun;) { $firstRun = false; echo ($count . "<BR>"); $count -= 2; $x = $x + $count; } echo ($x); By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false. EDIT $firstRun to avoid infiniteLoop $count in loop EDIT Fixed code for new requirement Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1. The output of your teacher's code is: 10 8 I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output: 10 8 6 4 2 20 Then a good for() loop would have been : $x = 0; $count = 10; for($i = $count; $i > 1; $i -= 2) { $count -= 2; echo $i . "<br>"; $x += $count; } echo $x; Which will output the same values. If you can, ask your teacher for this, and comment the answer ^^ ahahah
PHP infinity loop [While]
I am having some problems with PHP. I used while to sum a number's digits always that it has more than two digits, some how, it gets into an infinity loop. e.g: 56 = 5 + 6 = 11 = 1+1= 2. Here is the code: $somaP = 0; $numPer = (string)$numPer; //$numPer = number calculated previously while (strlen($numPer) > 1){ for ($j = 0; $j < strlen($numPer); $j++){ $somaP = $somaP + (int)($numPer[$j]); } $numPer = (string) $somaP; } Can anyone help me? Guess it is a simple mistake, but I couldn't fix it.
You need to reset the value of $somaP in your while loop. Currently it continues to increase its value every time through the loop. Try this: $numPer = (string)$numPer; //$numPer = number calculated previously while (strlen($numPer) > 1){ $somaP = 0; for ($j = 0; $j < strlen($numPer); $j++){ $somaP = $somaP + (int)($numPer[$j]); } $numPer = (string) $somaP; }
Take a look at this line: $numPer = (string) $somaP; It seems that the length of $somaP is never lesser (or equal) than 1. So the length of $numPer is never lesser (or equal) than 1.
What are you trying to do? It's unclear to me. This for example would add every number in a string together? E.g "1234" = 1+2+3+4 = 10 $total = 0; for($i = 0; i < strlen($string); $i++){ $total += $string[$i]; } echo $total;
This looks cleaner I would say: $numPer = 56; while ($numPer > 9){ $numPer = array_sum(str_split($numPer)); } echo $numPer; PHP handles all string <> number conversions for you, so no need to do (string) on a number unless really needed.
Simple PHP program requires less time to execute
i had applied for a job recently and the requirement was to complete a test and then interview 2 questions were given for test which was very simple and i did it successfully but still i was told that i have failed the test because the script took more than 18 seconds to complete execution. here is the program i dont understand what else i could do to make it fast. although i have failed the test but still wants to know else i could do? Program language is PHP and i had to do it using command line input here is the question: K Difference Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9] Input Format: 1st line contains N & K (integers). 2nd line contains N numbers of the set. All the N numbers are assured to be distinct. Output Format: One integer saying the no of pairs of numbers that have a diff K. Sample Input #00: 5 2 1 5 3 4 2 Sample Output #00:3 Sample Input #01: 10 1 363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 Sample Output #01: 0 Note: Java/C# code should be in a class named "Solution" Read input from STDIN and write output to STDOUT. and this is the solution $fr = fopen("php://stdin", "r"); $fw = fopen("php://stdout", "w"); fscanf($fr, "%d", $total_nums); fscanf($fr, "%d", $diff); $ary_nums = array(); for ($i = 0; $i < $total_nums; $i++) { fscanf($fr, "%d", $ary_nums[$i]); } $count = 0; sort($ary_nums); for ($i = $total_nums - 1; $i > 0; $i--) { for ($j = $i - 1; $j >= 0; $j--) { if ($ary_nums[$i] - $ary_nums[$j] == $diff) { $count++; $j = 0; } } } fprintf($fw, "%d", $count);
Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only. Algorithm: Sort the array ary_nums. for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise. sort($ary_nums); for ($i = $total_nums - 1; $i > 0; $i--) { $hi = $i-1; $low = 0; while($hi>=$low){ $mid = ($hi+$low)/2; if($ary_nums[$mid]==$ary_nums[$i]-$diff){ $count++; break; } if($ary_nums[$mid]<$ary_nums[$i]-$diff){ $low = $mid+1; } else{ $hi = $mid-1; } } } }
I got the same question for my technical interview. I wonder if we are interviewing for the same company. :) Anyway, here is my answer I came up with (after the interview): // Insert code to get the input here $count = 0; sort ($arr); for ($i = 0, $max = $N - 1; $i < $max; $i++) { $lower_limit = $i + 1; $upper_limit = $max; while ($lower_limit <= $upper_limit) { $midpoint = ceil (($lower_limit + $upper_limit) / 2); $diff = $arr[$midpoint] - $arr[$i]; if ($diff == $K) { // Found it. Increment the count and break the inner loop. $count++; $lower_limit = $upper_limit + 1; } elseif ($diff < $K) { // Search to the right of midpoint $lower_limit = $midpoint + 1; } else { // Search to the left of midpoint $upper_limit = $midpoint - 1; } } } #Fallen: Your code failed for the following inputs: Enter the numbers N and K: 10 3 Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10 Result: 6 I think it has to do with your calculation of $mid (not accounting for odd number)
Complicated Star Pattern?
Okay, so I have a unique problem that I ran into when trying to code a 5x3 star pattern. I can do the for loops to get the 5x3, that's easy. However I need something different than a square. We can have a maximum of 15 stars. So printing out a full block would look like this: * * * * * * * * * * * * * * * But we can pass in a parameter for the number of stars that we want. So let's pass in 11 instead of 15. We should get: * * * * * * * * * * * However, with 11 as my parameter the output is like this: * * * * * * It prints out the correct number of rows with the incorrect number of stars. I know why this is, and it's because of the modulus in my code. I also tried a different approach, which printed out one less row than needed. I am stuck and not sure where to go from here. Here is my code: <?php $num = 11; $rows = ceil($num/3); $count - 0; for($j = 0; $j < $rows; $j++){ echo '<div class="row-fluid"><ul class="thumbnails">'; for($i = $num%3; $i < 3; $i++){ echo '*'; $count++; } $num-=$count; echo '</ul></div>'; } ?>
With some simple PHP-Fu: $stars = 11; $row_length = 3; $array = array_fill(0, $stars, '*'); $array = array_chunk($array, $row_length); $table = '<table border="0">'; foreach($array as $row){ $table .= '<tr><td>'. implode('</td><td>', $row) .'</td></tr>'; } $table .= '</table>'; echo $table; Online demo.
The idea should be as simple as: keep drawing until you reach the target number. So you could do this: $num = 11; for( $i=0; $i<$num; $i+=3) { echo "<div class=\"row-fluid\"><ul class=\"thumbnails\">"; for( $j=0; $j<3 && $i+$j<$num; $j++) { echo "*"; } for( ; $j<3; $j++) { // finish the current row (optional, remove if not needed) echo " "; } echo "</ul></div>"; }
Ooh a puzzle! I don't know if using for was a requirement for your assignment, I prefer while. $num_of_stars = 15; $stars_per_row = 3; while($num_of_stars > 0){ echo "*"; if($stars_per_row == 1){ $stars_per_row = 3; echo "<br />"; }else{ $stars_per_row --; } $num_of_stars --; }
I don't see why you would have to use two for-loops. I would do something like this: (I noticed you don't have any <li>'s in your code) Of course you would have to set the class="thumbnails" to include list-style-type:none; <?php $num = 11; $cols = 3; echo '<div class="row-fluid"><ul class="thumbnails">'; $count = 0; for($j = 0; $j < $num; $j++){ $count++; echo '<li style="float:left;">*</li>'; if ($count>=$cols) { $count = 0; echo '<li style="clear:both;"></li>'; } } echo '</ul></div>'; ?>
For this to work, this is what you need. $num = 11; $cols = 3; $rows = ceil($num/$cols); for($j=0;$j<$rows;$j++) echo "<div class='row'>"; for($i=0;$i<$cols;$i++){ echo "*"; } echo "</div>"; } To show where you went wrong in your code. First, your definition of $count should be = not -. Next, your inner for loop is odd. First loop through, $num is equal to 11. In your inner loop you set $i = $num%3 which is $i = 2. So the inner loop runs through once while $i++ < 3, echo's one star and increments count once. inner loop exits, you subtract $count from $num making $num=10 and row is completed, next outer loop iteration. Next time the inner loop runs, $num is 10 so $i = $num%3 becomes $i=1. Inner loop runs 2 times while $i++ < 3, echo'ing 2 more stars and incrementing $count both times making it now 3. after the inner loop you subtract 3 more from $num making it 7 and row ends, outer loop continues. Next inner loop, $num is 7 so $i = $num%3 becomes $i=1. Inner loop runs 2 times while $i++ < 3, echo'ing 2 more stars and incrementing $count both times making it now 5. after the inner loop you subtract 5 from $num making it now 2, row ends, outer loop continues. Last iteration of the outer loop (row limit hit), $num is 2 so $i = $num%3 becomes $i=1. Inner loop runs once, echo's one star and inrement count once making it now 8. Inner loop finishes, you subtract 8 from $num making it now -6, row ends, outer loop ends.
how to find the sum of all the multiples of 3 or 5 below 1000 in php, issue?
i have an small issue with the way this problem is resolved. some would say: println((0 /: ((0 until 1000).filter(x => x % 3 == 0 || x % 5 == 0))) (_+_)) is the solution witch adds to 233168 my way was to do: $maxnumber = 1000; for ($i = 3; $i < $maxnumber; $i += 3) { $t += $i; echo $i.','; } echo '<br>'; for ($j = 5; $j < $maxnumber; $j += 5) { $d += $j; echo $j.','; } echo '<br>'; echo $t; echo '<br>'; echo $d; echo '<br>'; echo $t+$d; this will give me : 3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,183,186,189,192,195,198,201,204,207,210,213,216,219,222,225,228,231,234,237,240,243,246,249,252,255,258,261,264,267,270,273,276,279,282,285,288,291,294,297,300,303,306,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,423,426,429,432,435,438,441,444,447,450,453,456,459,462,465,468,471,474,477,480,483,486,489,492,495,498,501,504,507,510,513,516,519,522,525,528,531,534,537,540,543,546,549,552,555,558,561,564,567,570,573,576,579,582,585,588,591,594,597,600,603,606,609,612,615,618,621,624,627,630,633,636,639,642,645,648,651,654,657,660,663,666,669,672,675,678,681,684,687,690,693,696,699,702,705,708,711,714,717,720,723,726,729,732,735,738,741,744,747,750,753,756,759,762,765,768,771,774,777,780,783,786,789,792,795,798,801,804,807,810,813,816,819,822,825,828,831,834,837,840,843,846,849,852,855,858,861,864,867,870,873,876,879,882,885,888,891,894,897,900,903,906,909,912,915,918,921,924,927,930,933,936,939,942,945,948,951,954,957,960,963,966,969,972,975,978,981,984,987,990,993,996,999 5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,155,160,165,170,175,180,185,190,195,200,205,210,215,220,225,230,235,240,245,250,255,260,265,270,275,280,285,290,295,300,305,310,315,320,325,330,335,340,345,350,355,360,365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,650,655,660,665,670,675,680,685,690,695,700,705,710,715,720,725,730,735,740,745,750,755,760,765,770,775,780,785,790,795,800,805,810,815,820,825,830,835,840,845,850,855,860,865,870,875,880,885,890,895,900,905,910,915,920,925,930,935,940,945,950,955,960,965,970,975,980,985,990,995 $t - 166833 $d - 99500 and total: 266333 why am i wrong?
Some numbers are multiples of both 3 and 5. (Your algorithm adds these numbers to the total twice.)
Because 6 * 5 == 30 and 10 * 3 == 30, you're adding the some numbers up twice. $sum = 0; $i = 0; foreach(range(0, 999) as $i) { if($i % 3 == 0 || $i % 5 == 0) $sum += $i; }
Because you double-count numbers that are multiple of both 3 and 5, i.e. multiples of 15. You can account for this naively by subtracting all multiples of 15. for ($j = 15; $j < $maxnumber; $j += 15) { $e += $j; echo $j.','; } $total = $total - $d;
In your case, if it is 15, you will add the number twice. Try this: $t = 0; $d = 0; for ($i = 0; $i <= $maxnumber; $i++){ if ($i % 3 == 0) $t+= $i; else if ($i % 5 == 0) $d += $i; } echo $t.'<br>'.$d;
I think that in your code, if a number is a multiple of 3 and 5, it is added twice. Take 15 for example. It's in your list of multiples of 3 and in the list of multiples of 5. Is this the behaviour you want?
One of the best approach to this solution (to achieve optimum time complexity), run an Arithmetic Progression series and find the number of terms in all series by using AP formula: T=a+(n-1)d, then find sum by : S=n/2[2*a+(n-1)d] where : a=first term ,n=no. of term , d=common deference, T=nth term The code solution below has been implemented to suit the question above - so the values 3 and 5 are hard-coded. However, the function can modified such that values are passed in as variable parameters. function solution($number){ $val1 = 3; $val2 = 5; $common_term = $val1 * $val2; $sum_of_terms1 = calculateSumofMulitples($val1,$number); $sum_of_terms2 = calculateSumofMulitples($val2,$number); $sum_of_cterms = calculateSumofMulitples($common_term,$number); $final_result = $sum_of_terms1 + $sum_of_terms2 - $sum_of_cterms; return $final_result; } function calculateSumofMulitples($val, $number) { //first, we begin by running an aithmetic prograssion for $val up to $number say N to get the no of terms [using T=a +(n-1)d] $no_of_terms = (int) ($number / $val); if($number % $val == 0) $no_of_terms = (int) ( ($number-1)/$val ); //since we are computing for a no of terms below N and not up to/exactly/up to N. if N divides val with no remainder, use no of terms = (N-1)/val //second, we compute the sum of terms [using Sn = n/2[2a + (n-1)d] $sum_of_terms = ($no_of_terms * 0.5) * ( (2*$val) + ($no_of_terms - 1) * $val ); // sum of multiples return $sum_of_terms; }
You can run a single loop checking whether the number is multiple of 3 OR 5: for ($i = 0; $i < $maxnumber; $i++) { if($i%3 || $i%5){ $t += $i; echo $i.',';} }
I think the original code is not including numbers which are multiples of both 3 and 5 in the total: if the test for multiple of 3 matches, it takes that and goes on. If you total the multiples of 15 up to 1000, you get 33165, which is exactly the difference between your total, 266333, and the original total, 233168.
Here's my solution to the question: <?php $sum = 0; $arr = []; for($i = 1; $i < 1000; $i++){ if((int)$i % 3 === 0 || (int)$i % 5 === 0) { $sum += $i; array_push($arr,$i); } } echo $sum; echo '<br>'; print_r($arr);//Displays the values meeting the criteria as an array of values