More specifically, as soon as you call return
, the whole function which contains this loop will stop and return whatever you passed in the return statement. Think of return
as a hard stop to any function execution.
In this case, as soon as return(i)
runs the first time, the loop will stop, which is why you are getting back 1000
, which is the value you started with.
If you want to return the last value i
you need to do something like this:
function remainder() public pure returns(uint) {
uint r;
for(uint i = 1000; i >= 1; i-=4) {
r = i;
}
return r;
}
But this is super inefficient and will waste a bunch of gas (if called within another function). You should be using the modulus operator for this kind of math. In solidity, the modulus operator is represented by %
.
Here is an example of a function which does what I think you want:
function remainderBetter(uint i) public pure returns(uint){
uint r = i % 4;
if (r == 0) {
return 4;
}
return r;
}
%
) This is the same as remainder. Thus 1000 % 4 = 0 because 4 divides 1000 perfectly. If you want results between 1-4, you can have a check for 0 and turn it into 4. – Shawn Tabrizi Aug 27 '18 at 22:4610 % 4
which is equal to 2. You can try yourself in google search. – Shawn Tabrizi Aug 27 '18 at 23:55