Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get every 100th value in a loop

Is there a way to make this cleaner and not use the tempvalue like i have done here?


UPDATE the code had a logic bug and didn't show what I'm doing. This is what I'm doing:

var loopTempValue = noOfPackets / 100;
for(i=0; i < noOfPackets; i++)
{   
    \\DoStuff

    if (i == loopTempValue)
    {
         loopTempValue = loopTempValue + (noOfPackets / 100);
         UploadBackGroundWorker.ReportProgress(pross);
    }
}

UPDATE Final

This is how its fixed after the feedback, thx guys.

if (i % (noOfPackets / 100) == 0 && i != 0)
{
     UploadBackGroundWorker.ReportProgress(pross);
}
like image 970
Darkmage Avatar asked Jan 25 '11 11:01

Darkmage


3 Answers

if (i % 100 == 0 && i != 0) { //YOUR CODE }

Modulus is fantastic for checks like this.

More on Modulus - http://www.vias.org/cppcourse/chap04_01.html

UPDATE: I added && i != 0 for the 0 case being true.

If you want to use the tempvalue instead of hard coding 100, then this would be a solution:

if (i % tempvalue == 0 && i != 0) { //YOUR CODE }
like image 54
Jón Trausti Arason Avatar answered Nov 20 '22 15:11

Jón Trausti Arason


You mean that you want the condition to be triggered 100 times during the loop, i.e. every 36th iteration? (In your original code you double the tempvalue each time, so it would only trigger seven times during the loop.)

You can use the modulo operator to check for that. This will trigger the condition at the last of each set of 36 iterations:

for(i=0; i < 3600; i++) {
   \\DoStuff

   if(i % 36 == 35) {
      \\DoStuff
   }
}
like image 37
Guffa Avatar answered Nov 20 '22 15:11

Guffa


if( (i+1 % (tempvalue+1) == 0)
{
      //DoStuff

      //tempvaule = tempvalue + tempvalue;
}
like image 1
Henk Holterman Avatar answered Nov 20 '22 16:11

Henk Holterman