Home > Software engineering >  Is there a way to extract the value of a variable used in a for loop at a certain point (C)?
Is there a way to extract the value of a variable used in a for loop at a certain point (C)?

Time:11-21

I would like to know if there's a way for me to get the current value of "j" outside of the foor loop whenever the conditions is true. The variable "totalvalid" will tell me how many times the condition was met but I would also like to know the exact value of j when the condition is true so that I can use it at a later point. So I would want to extract the value of "j" whenever the "totalvalid = totalvalid 1" happens. Sorry if it looks messy. I'm new to coding and still have no idea how to make it cleaner. Thank you.

    for(int j = 0; j < stringnumber; j  ){
        
        int valid = 0;
        
        if(str[j][10] == '\0'){
            
            for(int k = 0; k < 10; k  ){
                
                if(str[j][k] >= 'A' && str[j][k] <= 'Z'){
                
                valid  ;
                } 
          
            }
            if (valid == 10){
                totalvalid = totalvalid   1;
            }
      }  
    }

CodePudding user response:

It seems that you want an array of numbers from that pass the condition.
My suggestion would be to make an array of ints, where you will keep these numbers.
Before loop:

int *array_of_valid_ints = (int *) calloc(stringnumber, sizeof(int)); // allocate the array
int number_of_valid_ints = 0;

Inside the if statement:

array_of_valid_ints[number_of_valid_ints] = j;
number_of_valid_ints  ;

After the loop ends, you can check the good values with:

printf("This are the good ints: ")
for (int i = 0; i < number_of_valid_ints; i  ) {
    printf("%d ", array_of_valid_ints[i]);
}
printf("\n");

CodePudding user response:

maybe you can define a variable before the loop as int j=0; then use a while loop instead of for.also remember to write j in the while loop.this way you can use the value of j outside of the loop too!

  •  Tags:  
  • c
  • Related