Home > Backend Development > C++ > body text

In C language, array post-increment and front-increment

PHPz
Release: 2023-08-30 16:57:06
forward
1518 people have browsed it

In C language, array post-increment and front-increment

Question

Use a C program to explain the concepts of post-increment and pre-increment of an array.

Solution

Increment operator ( ) -

  • is used to increase the value of a variable by 1

  • There are two types of increment operators - pre-increment and post-increment.

  • In prepended increment, the increment operator is placed before the operand, the value is incremented first, and then the operation is performed.

eg: z = ++a; a= a+1
z=a
Copy after login
  • The auto-increment operator is placed after the operand in the post-increment operation, and the value will be increased after the operation is completed.

eg: z = a++; z=a
a= a+1
Copy after login

Let us consider an example of accessing a specific element in a memory location by using pre-increment and post-increment.

Declare an array of size 5 and perform compile-time initialization. Afterwards try assigning the pre-increment value to variable 'a'.

a=++arr[1] // arr[1]=arr[1]+1
a=arr[1]
b=arr[1]++// b=arr[1]
arr[1]+1
Copy after login

Example 1

Demonstration

#include<stdio.h>
int main(){
   int a, b, c;
   int arr[5] = {1, 2, 3, 25, 7};
   a = ++arr[1];
   b = arr[1]++;
   c = arr[a++];
   printf("%d--%d--%d", a, b, c);
   return 0;
}
Copy after login

Output

4--3--25
Copy after login

Explanation

is translated as:

Explanation

here, a = ++arr[1]; i.e a = 3 //arr[2];
b = arr[1]++; i.e b = 3 //arr[2];
c = arr[a++]; i.e c = 25 //arr[4];
printf("%d--%d--%d",a, b, c);
printf("%d--%d--%d",4, 3, 25);
Thus 4--3--25 is outputted
Copy after login

Example 2

Consider another example to learn more about pre-increment and post-increment of an array.

Real-time demonstration

#include<stdio.h>
int main(){
   int a, b, c;
   int arr[5] = {1, 2, 3, 25, 7};
   a = ++arr[3];
   b = arr[3]++;
   c = arr[a++];
   printf("%d--%d--%d", a, b, c);
   return 0;
}
Copy after login

Output

27--26&mdash;0
Copy after login

The above is the detailed content of In C language, array post-increment and front-increment. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!