3

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?

kile
  • 1,671
  • 5
  • 10
  • 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 ? – Nasser Mar 26 '20 at 03:36
  • @Nasser how can I make second loop work? – kile Mar 26 '20 at 03:38
  • 2
    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. – Nasser Mar 26 '20 at 03:40
  • @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. – kile Mar 26 '20 at 03:43
  • 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. – Nasser Mar 26 '20 at 03:49
  • @Nasser, I wanna get the second root that meet the criteria I set n^2 + n - 6 == 0 – kile Mar 26 '20 at 03:54

2 Answers2

2

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.

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • I know Solve command can do it much easier. But I wanna test how While is working here. Anyway, Thanks. – kile Mar 26 '20 at 04:06
1

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    
Somos
  • 4,897
  • 1
  • 9
  • 15