Examples of Arrays and Increment Operators

For Complete YouTube Video: Click Here

In this class, we will understand Examples of Arrays and Increment Operators.

We have already discussed the concepts of arrays.

Examples of Arrays and Increment Operators

Example

The image below is an example of arrays and increment operators.

Examples of Arrays and Increment Operators 1
Examples of Arrays and Increment Operators 1

The above example looks simple, but when we solve this example in exams, we can put the wrong answer.

In the above example, we have created three integer variables, x, y, z, and an array ‘a’ of 5 integer elements.

Before understanding the example, the important point to understand is the pre-increment operator has the highest precedence over the post-increment operator.

The pre-increment operator is in the first row of the precedence table, and the post-increment is in the second row.

x = ++a[1];
y = a[1]++;
z = a[x++];

The three lines of code are the important part of the program to understand.

The first line of code is x = ++a[1];

Here the value stored in a[1], 2, will be incremented and stored in x.

The value of x and a[1] is 3.

The second line of code is y = a[1]++;

Here we have to be cautious in understanding. This line of code is the tricky part of the program.

The value stored in a[1] is 3, but it is a post-increment, so the value of a[1] will get assigned to y first, then the increment happens and will get stored in a[1].

Now, a[1] is 4, and y is 3.

The third line of code is z = a[x++];

Here x is a post-increment, so the value of x is used first, and the x will get incremented later.

So, a[3] will be stored in z.

The value of z is 25, and x is 4.

If we print the x, y, and z, the output will be 4, 3, and 25.