+ 1

#include <iostream> using namespace std; int main() { int a[4]={1,2,3,4}; a[1]=*(a+2); *(a+2)=a[3]++; cout<<a[1]+a[2]; } could someone explain (comment each line) why the output is 7 ?

13th Jul 2016, 9:22 AM
Jetset Willy
Jetset Willy - avatar
4 Answers
+ 8
int a[4]={1,2,3,4}; //Defines a 4 elements array a[1]=*(a+2); //Assigns the value stored in the third element to the second element of the array. Now a[]={1,3,3,4}. *(a+2)=a[3]++; //Now assing the value stored in the last element to the third element of the array and after that add one to the last element. Now a[]={1,3,4,5} cout<<a[1]+a[2]; //Prints the sum of he second and third elements in the array, that is 3+4 which is equal to 7. Hope it helps...
13th Jul 2016, 9:42 AM
Nelson Urbina
Nelson Urbina - avatar
+ 2
*(a+2) is simply the element in index 2 of your array ie 3. therefore a[1]=3. now a[3] is 4 and its a post increment hence you are putting that into *(a+2) ie index 3 in the array now your array looks like {1,3,4,5}. hence a[1]+a[2]=3+4=7
13th Jul 2016, 9:46 AM
chaitanya guruprasad
chaitanya guruprasad - avatar
+ 1
thank you all for clear explanations
13th Jul 2016, 3:44 PM
Jetset Willy
Jetset Willy - avatar
0
both explanations are correct
13th Jul 2016, 12:41 PM
Atharva Vaidya
Atharva Vaidya - avatar