Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over a part of an array

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading