Calculating in the Main Loop

5.7.3 Calculating in the Main Loop

By this stage, we have declared and initialized our variables and taken care of the command line argument. Now comes the the real work in the program, the Newton iterations.

Remember from the theory that if x0 is our guess for the root, our next guess is given by:

x = x0 - f(x0)/f'(x0)
We will iterate this process until either we come close to a root (so f(x) is smaller than our tolerance, `tolerance`), or we decide that we have iterated too many times and we aren't going to find a root (so the number of iterations is larger than `max_count`).
```          for  ( int count=0;
(Math.abs(f(x)) > tolerance) && ( count < max_count);
count ++)  {
x= x - f(x)/fprime(x);
System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
}
```
Here is the overview: `for` takes three arguments - how to begin, how to end, and what to do in between steps. This is followed by the ever-present curly braces which contain code that the Java interpreter executes each time it goes through the loop.
``` int count=1;
```
which declares a new integer `count` and initializes it to 0. The Java interpreter executes this before the loop is entered.
```Math.abs(f(x)) > tolerance
```
Here we see the absolute value function `Math.abs`. The second criterion is:
```count < max_count
```
We need both of these to be `true` to allow another loop to occur, so we connect the two boolean statements with the and operator `&&`, which returns `true` only if both of its arguments are `true`. So all together, we get:
```(Math.abs(f(x)) > tolerance) && (count < max_count);
```
Notice that the two arguments to `&&` are surrounded by parenthess. This is a good idea since it makes your code easier to read, and you don't have to worry about order of operations (which comes first, > or &&?).
```count ++;
```
The `++` operator adds one to its argument, so this is the same as `count=count+1;` but is shorter and (when you get used to it) easier to read.
```            x= x - f(x)/fprime(x);
```
We also print out a message for the loop letting the user know what is going on. The simplest method to print a message is `System.out.println` which takes a String as its argument:
```	    System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
```
Here we see also a nice way to make Strings using `+`. For example, if `count` is equal to 5, the expression `"Step: "+count;` evaluates to `"Step: 5"`. The line above uses `+` several times to make the information message.
David Maxwell, who is still writing this, would like to hear your comments and suggestions.