Reteras Remus
Reteras Remus

Reputation: 933

algorithm, decrement and increment [-100, 100]

I'm trying to create a cycle and decrement, increment an int.

int val = 0;

while(true){
   if(val < -100) val += 1;
   else val -= 1;

   myFunction(val);
}

It's an infinite cycle, I know but I need to send a value to myFunction between (-100, 100);

Upvotes: 0

Views: 2008

Answers (1)

Romias
Romias

Reputation: 14133

This will do the trick I think...

int val = 0;
int increment = 1;

while(true){
   val += increment;

   if(val < -100){
     increment = 1;
   }
   else if(val > 100){
     increment = -1;
   }

   myFunction(val);
}

It starts in 0 and incrementing untill reaching 100... then starts decrementing untill reaching -100... when it starts incrementing again.

If you need to start from 0 and decrementing, just change initial value of increment variable to -1 instead of 1. The same for initial value... set it as you want between -100 and 100.

Upvotes: 0

Related Questions