Darkmage
Darkmage

Reputation: 1603

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);
}

Upvotes: 15

Views: 25143

Answers (3)

J&#243;n Trausti Arason
J&#243;n Trausti Arason

Reputation: 4698

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 }

Upvotes: 29

Guffa
Guffa

Reputation: 700562

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
   }
}

Upvotes: 5

Henk Holterman
Henk Holterman

Reputation: 273464

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

      //tempvaule = tempvalue + tempvalue;
}

Upvotes: 1

Related Questions