Home > Blockchain >  Iterate over a part of an array
Iterate over a part of an array

Time:04-07

Whats the best way to iterate over a part of an array? I want to iterate over the first 4 elements of an array and then separately I want to iterate over the last 4 elements of the array. Is the following code the best way to do it? Please help.

    void function() {
        int arr[8] = {a1, a2, a3, a4, b1, b2, b3, b4};
        int arr_num = 8;

        for (int i = 0; i < arr_num/2; i  ) {
           if (arr[i] == a1) {
               // publish something
           } else if (arr[i] == a3) {
               // publish something
           }
        }

        for (int i = 5; i < arr_num; i  ) {
           if (arr[i] == b1) {
               // publish something
           } else if (arr[i] == b3) {
               // publish something
           }
        }
     }

CodePudding user response:

You could do:

int i = 0; 
for ( ; i < arr_num / 2;   i ) { // leave the initialization section empty, "i" is already 0
    //... 
} 
for ( ; i < arr_num;   i ) { // "i" already has the correct value from above loop
    // ...
}

This way i retains its value between loops, and, is more generic for different sizes of arrays.

  • Related