I just want to ask what's the meaning of p[x] below in this C++ syntax. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I just want to ask what's the meaning of p[x] below in this C++ syntax.

int main() { int p[ ]={5,4,3,21,1}; int s = 0; for (int x = 0; x < 5; x++){s+=p[x];} cout << s; return 0; }

6th Oct 2022, 10:15 PM
Soham
Soham - avatar
3 Answers
+ 4
You probably understand that p[ ] is an array that holds five numbers. To access one of the numbers in p, you use an index value, like p[0] to get 5 p[1] to get 4 p[2] to get 3 The code above replaces the index value with a variable, x. Whatever value is stored in x becomes the index. If x=0, p[x] means p[0], 5 If x=1, p[x] means p[1], 4 If x=2, p[x] means p[2], 3 If x=3, p[x] means p[3], 21 If x=4, p[x] means p[4], 1 The for() loop starts with x=0, and tests whether x<5. If true, then it executes the statement inside the braces. Afterward it increments x by 1 and tests whether x<5. If x is still less than 5, it repeats the statement. This continues as x goes through values 0, 1, 2, 3, and 4, executing the statement s+=p[x]; each time. Now after the loop exits, s holds the sum of all the values in p[ ].
6th Oct 2022, 11:00 PM
Brian
Brian - avatar
+ 3
It's inside a for loop, so you are iterating the items of the array p and accumulating it on s. s+=p[0] // s=5 s+=p[1] // s=5+4=9 s+=p[2] // s =9+3=12 s+=p[3] // s=12+21=33 s+=p[4] // s=33+1=34
6th Oct 2022, 11:04 PM
Bob_Li
Bob_Li - avatar
0
Very thanks for helping me out with it.
7th Oct 2022, 7:32 AM
Soham
Soham - avatar