Programming Tips: Traversing Arrays

        The little trick I share with you today is about array traversal. Usually when we operate on arrays, we are often troubled by the subscript out of bounds problem of the array. Of course in C the compiler doesn't check the bounds of array subscripts, which means if you define an array with 5 elements, the positive operation is completely legal in C:

int a[5] = {0, 1, 2, 3, 4};
a[-3];
a[-2];
a[-1];
a[5];
a[6];
a[7];

        But in other programming languages, programmers usually check whether the subscript of the array is out of bounds. But that's not the key content we're going to share today. What we want to say is that even if the compiler does not check the validity of array subscripts in C, we don't want to get an out-of-bounds subscript when using it. What we usually do when iterating over an array is this:

for (int i = 0; i < 5; i++)
{
    a[i] = something;
}

        This is a standard array traversal method. If we need to loop over the array many times, such as 100 times, how should we program the program so that the subscript of the array does not exceed the bounds?

for (int i = 0, j = 0; i < 100; i++, j++)
{
    if (j >= 5)
    {
        j = 0;
    }
    a[j] = something;
}

        There is no problem with this approach logically, the variable i is used to control the number of loops, and the variable j is used to control the subscript of the array. Although this approach achieves our purpose, the code is verbose. Let's take a look at the following processing method:

for (int i = 0; i < 100; i++)
{
    a[i % 5] = something;
}

        Cleverly use the modulo operation % to take the remainder of the variable i, and let the result of i % 5 be used as the subscript of the array. The code looks simple and practical.

   

        Did you learn the tricks today?


Welcome to the public account: programming aliens

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691281&siteId=291194637