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);
?>
Related
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 3 years ago.
Improve this question
I want to make row of number jumps, example I have $a = 1 and $b = 2. then I want loop $a and $b and the result is $a = '1', '5', '9', '13', '17' and $b = '2', '6', '10', '14', '18' . How to make it?
You might want to add some context as to me it looks like a generic PHP question, but you also added the codeigniter tag which looks like there is more to it than you wrote.
If I understand you correctly, you start with two numbers and want to generate an list (array) for each of those numbers. Reusing $a and $b for the results might not be a good idea. So I suggest you save the result to a different variable:
// initialize A
$a=1;
$a_result=[];
// initialize B
$b=2;
$b_result=[];
// set the jump size
$jump_size=4;
// loop 5 jumps
for($i=0; $i<5; $i++) {
// add new elements to the result arrays
$a_result[] = $a + $jump_size * $i;
$b_result[] = $b + $jump_size * $i;
}
// print the results
print_r($a_result);
print_r($b_result);
If you have more than just two numbers to start from, you might want to put those in an array too (as well as the result arrays).
You can check odd or even number using modulo, and skip next number.
See below example.
See Running Example
$a = 1;
$b = 2;
for($i = $a; $i <= 20; $i++){
if($i > 1 && $i % 2){
$i = $i + 2;
}
if($i % 2 == 1) {
echo $i;
}
}
echo " b=> ";
for($i = $b; $i <= 20; $i++){
if($i > 1 && $i % 2){
$i = $i + 2;
}
if($i % 2 == 0) {
echo $i;
}
}
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
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!
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.
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 8 years ago.
Improve this question
Hello i would like the loop below to generate a random prime number below 1000. But only generate 1 with the variable $i and the variable $finish should allow the while loop to stop after the first prime number is found and if the number is not prime it should generate a new $i variable randomly and check if its a prime number again until the first prime number is found.
<html>
<body>
<?php
$finish="a";
while($finish = "a") {
$i = (mt_rand(0,999));
$counter = 0;
for($j = 1; $j <= $i; $j++) { //all divisible factors
if($i % $j == 0) {
$counter++;
}
//prime requires 2 rules ( divisible by 1 and divisible by itself)
if($counter == 2){
print $i." is Prime <br/>";
$finish = "b";
}
}
}
?>
</body>
</html>
how can i modify this so that it will stop the code after the first prime number below 1000 is found?
The problem is $finish="a" - you are assigning the string a (which is truthy) to $finish. So this loop will run forever (as the condition is always true).
You are setting flags as string and ints while boolean here should suffice. In addition to that, once a divisor >= 2 is found you can stop the for() loop. If you introduce a helper function it becomes even more readable.
function isPrime($number) {
$max = $number;
for ($i=2; $i < $max; $i++) {
if ($number % $i == 0)
return false;
}
return true;
}
do {
$i = mt_rand(100, 9999);
} while ( ! isPrime($i) );
var_dump($i);
See it work here. I'm not too sure but sqrt($number) should suffice as $max and make the loop shorter -> the script faster.
To break out of your 2 loops when the condition is matched, you can use break 2:
if($counter == 2){
print $i." is Prime <br/>";
$finish = "b";
break 2;
}