0

the answer shows 6, can anyone explain me that " sum+=*(a+i); " part???

int i,sum=0; int a[]= {1,2,3,4}; for(i=1; i<4; i+=2){ sum+=*(a+i); }

3rd Oct 2021, 5:48 AM
RAJESH
3 ответов
+ 4
An array name is a pointer to its first element and when you add i to a you are going forward in the array so *(a+i) equals a[i]
3rd Oct 2021, 6:16 AM
GHOST mHBr
GHOST mHBr - avatar
+ 8
Rajesh Dutta, *(a) is a pointer to the first element of the array a[]. Likewise, *(a + 1) points to the second element, *(a + 2) to the third and so on. The for loop iterates from i = 1 to i = 3. *(a + 1) = 2 and *(a + 3) = 4. sum += *(a + 1) ==> sum += 2 (which makes sum = 2) and sum += *(a + 3) ==> sum += 4 (which makes sum = 6)
3rd Oct 2021, 6:13 AM
David Akhihiero
David Akhihiero - avatar
3rd Oct 2021, 6:18 AM
RAJESH