Home > database >  How to stop variable from changing value after the first time in a loop
How to stop variable from changing value after the first time in a loop

Time:12-22

I'm trying to get a variable to change only in the first iteration of a loop unless another condition makes it so it needs a different value. For example:

for (int i = 0; i < numOfIterations; i  ){
   if (this happens){
   value = i;  //trying to save that particular position
   }

//Now the problem is: the value will change in the next iteration. 

¿How do I stop it without stopping the loop?

CodePudding user response:

#include <stdbool.h>

bool setValue = true;  

for (int i = 0; i < numOfIterations; i  ){
   if (this happens && setValue){
       value = i;  //trying to save that particular position
       setValue = false; // Now that setValue is false
                         // variable "value" will not be set again,
                         // even if "this happens" is true
   } // End of if
} // End of For-loop

CodePudding user response:

Easiest way to do this would be

for (int i = 0; i < numOfIterations; i  ){
   if (this happens && i == 0){
   value = i;
   }
}

CodePudding user response:

for (int i = 0; i < numOfIterations; i  ){
   if (this happens && i == 0) {  //that means if i is equal to 0 and your condition is true, code will be executed
       value = i;  //trying to save that particular position
   }
}
  • Related