3
$\begingroup$

I am supposed to get 2 in the output, but it is still -3 instead.

ClearAll[t, n];
n = -10;
While[True, If[n^2 + n - 6 == 0, Break[]]; n++];
t = n;
While[True, If[t^2 + t - 6 == 0, Break[]]; t++];
t

Is it possible to abort the 1st root(-3) and get 2nd root (2) with While loop code here?

$\endgroup$
  • $\begingroup$ it works OK as expected. because t=-3 before second loop and so second loops exists right away and so t do not change? why do you think t should be 2 ? $\endgroup$ – Nasser Mar 26 at 3:36
  • $\begingroup$ @Nasser how can I make second loop work? $\endgroup$ – kile Mar 26 at 3:38
  • 2
    $\begingroup$ If you mean by make second loop work is to get -3 again for t, then you need to reset n back to -10 again before you assign it to t since n has changed after the first loop has finished. But may be you can clarify why you expected second loop to return 2 in the question itself, that would be best. $\endgroup$ – Nasser Mar 26 at 3:40
  • $\begingroup$ @Nasser. If it works in the way you have said, then n=-10 should not be considered in 1st loop. And the output should be -10. $\endgroup$ – kile Mar 26 at 3:43
  • $\begingroup$ n++ works by incrementing n. try this n = 0; n++; n and now is 1 and no longer zero. But it is possible I do not understand what the issue you are having in all of this and what exactly is the problem here. $\endgroup$ – Nasser Mar 26 at 3:49
2
$\begingroup$

I wanna get the second root that meet the criteria I set n^2 + n - 6 == 0

In this case you could do

ClearAll[t, n];
n = -10;
While[True, If[n^2 + n - 6 == 0, Break[]]; n++];
t = n + 1;
While[True, If[t^2 + t - 6 == 0, Break[]]; t++];
t

Which gives 2.

Or you could also just do

ClearAll[n];
Solve[n^2 + n - 6 == 0, n]

But I am sure you knew about the Solve command and was trying to do it another way.

| improve this answer | |
$\endgroup$
  • $\begingroup$ I know Solve command can do it much easier. But I wanna test how While is working here. Anyway, Thanks. $\endgroup$ – kile Mar 26 at 4:06
1
$\begingroup$

Another slightly different way to do it is this

ClearAll[t, n];
n = -11;
While[True, n++; If[n^2 + n - 6 == 0, Break[]];];
t = n;
While[True, t++; If[t^2 + t - 6 == 0, Break[]];];
t    
| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.