This is a question from a past exam paper. The code was given in the question and i need to gain the values and how many times the breakpoint is it. I have tried running the code in eclipse but to no avail. (I could find the values in debug mode if code executed)
Also the question states that: the method fact is called on an instance of the class in which n has the value 6. Not sure what I am doing wrong as the code is exactly the same as given in the question.
public class FactLoop {
private int n;// assumed to be greater than or equal to 0
/**
* Calculate factorial of n
*
* @return n!
*/
public int fact() {
int i = 0;
int f = 1;
/**
* loop invariant 0<=i<=n and f=i!
*/
while (i < n) {// loop test (breakpoint on this line)
i = i++;
f = f * i;
}
return f;
}
// this main method is not a part of the given question
public static void main(String[] args) {
FactLoop fl = new FactLoop();
fl.n = 6;
System.out.println(fl.fact());
}
}
Your error is in
i=i++;.i++increments i, and retuns i’s old value. By sayingi=i++, you increment it, then set it to its old value.Just use
i++;to increment it.