Nested for loop exercise [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I solve this using php?
Write nested for loops to produce the following output:
Enter a number:5
----1
---22
--333
-4444
55555

Here you go:
for ($i = 1; $i <= 1; $i++) {
for ($j = 1; $j <= 1; $j++) {
echo 'Enter a number:5 ----1 ---22 --333 -4444 55555';
}
}
Edit: Here is the real answer:
$number = 5;
for ($i = 1; $i <= $number; $i++) {
for ($j = $number; $j >= 1; $j--) {
if ($i < $j) {
echo '-';
} else {
echo $i;
}
}
echo PHP_EOL;
}
This code uses two for loops. The outer loop creates the rows (iterates from 1 to $number), the inner loop creates the characters (iterates from $number to 1). There is a comparison inside the inner loop. If $i is less than $j, then it prints -, otherwise it prints $i.

Related

Nested Loops headache PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would you go about answering a question like this? I know I would have to use a loop, but my current answer won't allow me to go over an input of about 5 which is incredibly inefficient. I'm finding nested loops a little daunting.
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
...
Calculate the row sums of this triangle from the row index (starting at index 1)
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
Disclaimer - this is not a test questions. Just one of the practice ones I'm struggling to get my head around.
Since posting this I have found a working answer (three hours later...)
Working code:
function rowSumOddNum($n) {
$start = ($n *($n - 1)) + 1;
$sum = 0;
$step = $start +($n*2);
for($a=$start;$a<$step;$a++){
if($a % 2 !== 0){
$sum = $sum + $a;
}
} echo $sum;
}
This was the original code I was working with that kept crashing out saying it didn't have enough memory. Very inefficient I believe.
function rowSumOddNumbers($n) {
$len = $n + ($n*1);
$array = [];
for ($i = 1; $i <= $len; $i+2) {
if ($i % 2 == 1) {
$array[] = $i;
}
}
$count = 0;
$answer = 0;
for ($row = 1; $row < $n; $row++) {
$count = $count + $row;
}
$length = $count + $n;
for ($a = $count; $a <$length; $a++) {
$answer = $answer + $array[$a];
}
echo $answer;
}
I liked the challenge, so here it is.
This should do the job no matter how big the triangle is.
<?php
$triangle = array(1,5,11,9,7,3);
$u = 1;
$results = array();
$sumrow =0;
for($i=0; $i<=count($triangle); $i++){
if($i == count($triangle)){
$sumrow += $triangle[0]; // for the last row add the first number of array
}else{
$sumrow += $triangle[$i];
}
if(is_int($u/3)){ // for every third number store results and use the same number again
$i--;
$u = 1;
array_push($results, $sumrow);
$sumrow = 0;
}else{
$u++;
}
}
echo json_encode($results);
?>

PHP: How to remove comma in a for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
for ($i = 10; $i < 101; $i = $i + 10) {
echo $i;
}
?>
I'm starting to learn PHP and this is the code I'm working on. What I'm trying to do is remove the comma on the last item that will display (e.g. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,) I've searched the forum and all I see are methods for "foreach"...Any suggestions, replies are appreciated.
You could do something like this,
$result = array();
for ( $i = 10; $i < 101; $i = $i + 10 ){
$result[] = $i;
}
echo implode(", ", $result);
This should work!
There is no comma in your code or it's output but your question is still understandable and you just missed posting the code line which outputs those commas. You simply have to check if this is the last iteration of the loop and if so don't print comma
echo $i;
if($i<100) //currently you don't have this check so you get an extra comma
echo ",";
Output
10,20,30,40,50,60,70,80,90,100
Try this:
$result = array();
for ($i = 10; $i < 101; $i += 10) {
$result[] = $i;
}
echo implode(", ", $result);
If it's an array, write implode(',', $array). If it's not, save output from each iteration to a variable(say $output), then, write substr($output,0,-1).
$output = "";
for ($i = 10; $i < 101; $i = $i + 10) {
$output .= $i.",";
}
echo substr($output,0,-1);
Your code doesn't relate to your question/description, though!

PHP: for VS. foreach? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Kindly someone explain to me about this?
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]] .= "a";
is faster than
foreach($aHash as $key=>$val) $aHash[$key] .= "a";
According to The PHP Benchmark. However I have a a code in my script:
My CODE:
foreach($_SESSION['undo'] as $key2=>$value2)
{
if{
}
else
{
}
.
.
.
.
}
How can I convert a code like that as shown above to my code?
Kindly explain why? Thank you.
do not count in for condition
you can try this
$size = count($_SESSION['undo']);
for($i = 0; $i< $size; $i++){
$value = $_SESSION['undo'][$i];
}
In a foreach loop the first part is your array and the second part after the as is the current value when iterating.
When using a for loop you are working with indexes and have to manually access them. Just do the same as in your example. I'm assuming you are working with an associative array as you are using array keys.
$myArray = $_SESSION['undo'];
$keys = array_keys($myArray);
$size = sizeOf($keys);
for ($i = 0; $i < $size; $i ++) {
/* do something with $myArray[$keys[$i]] */
echo $myArray[$keys[$i]];
}
try this:
for($i = 0; $i< count($_SESSION['undo']); $i++){
$value = $_SESSION['undo'][$i];
}
Seems you made a mistake, from the http://www.phpbench.com/,
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]] .= "a";
This way cost 92 us, just foreach cost 16 us, with 'as' cost 21 us.
Guys, wake up....

How to increment a for loop by more than 1? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How do I print a series like this?
6,15,24,33,42.....1000
I have tried using a for loop like this, but can't work out how to get it to increment by 9 on each iteration.
for($i = 6; $i <= 1000; $i = 9)
{
echo $i . ', ';
}
Quite simple really:-
for($i = 6; $i <= 1000; $i += 9){
echo $i . ', ';
}
//If you have to finish the series with 1000, although it is not a part of the series:-
echo '1000';
See it working
just for fun:
echo implode(', ', range(6, 1000, 9));
echo ", 1000";
<?php
for($i=6; $i<1000; $i+=9)
echo $i."<br>";
?>
Seeing the question this can be an answer.

Implement two-dimensional array [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I need to implement two-dimensional array in PHP. Is it a correct way to do this?
$constr = array();
for ($i = 0; $i < $size; $i++)
{
for ($j=0; $j < $ncons; $j++) {
$constr[$i][$j] = $set->getInd($i)->getConstr($j);
}
}
The code as you have it is fine, but since you're using objects, it's best to cache them inside the outer loop:
$constr = array();
for ($i = 0; $i < $size; $i++) {
$ind = $set->getInd($i);
for ($j=0; $j < $ncons; $j++) {
$constr[$i][$j] = $ind->getConstr($j);
}
}
In this way, you're not repeating $set->getInd($i) for the inner loop.

Categories