Reputation: 12163
I am trying to display whenever I need to do a certain action in my for
loop every 300th iteration (makes sense?)
Here is in code what I want to do, but not the way I want to do it:
for I := 0 to 2000 do
Begin
if I = 300 then
DoAnAction;
if I = 600 then
DoAnAction
if I = 900 then
DoAnAction
if I = 1200 ......... Same action all over, but I don't want to check all those conditions!
End;
So I have been told to use the mod
operator, and this is how I do it:
for I := 0 to 2000 do
Begin
if I mod 300 = 299 then
DoAnAction;
End;
However, the results using the above snippet would do the action at 299, 599, 899 ....
How can I make it do it at 300, 600, 900 ...... using the Mod operator? (And doing if I mod 300 = 300
did not work)
Thanks!
Upvotes: 3
Views: 17975
Reputation: 7397
for I := 0 to 2000 do
Begin
if (I mod 300 = 0) and (I > 0) then
DoAnAction;
End;
Though your previous version does makes sense too, I=299 is the 300th pass ;)
EDIT: I mod 300 = 300
would not work because mod
operator returns the remainder of devision, which is by definition will be in range 0..299
Upvotes: 10
Reputation: 125688
Use this:
if i mod 300 = 0
The modulus operator returns the remainder of a division.
Here's an example to help you out. Drop a TMemo on a blank new form, and put this in the FormCreate
evemt:
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
const
Output = 'i mod %d = %d';
begin
Memo1.Clear;
for i := 0 to 10 do
Memo1.Lines.Add(Format(Output, [i, i mod 5]));
end;
Run it, and look at the output in the memo.
Upvotes: 4
Reputation: 61437
The mod
operator returns the rest of the division. So if you want to do it every 300th iteration, use i mod 300 = 0
.
I mod 300 = 300
doesn't make sense, as there can't be a division by 300 leaving a rest of 300.
Upvotes: 4