ID:181312
 
#include
#include
int sum(int arr[],int size)
{
for(int I=0,s=0;I<size;++I)
{
cout<<I<<" - "<<arr[I]<<endl;
s+=arr[I];
}
return s;
}
int main(){
clrscr();
int val[]={1,3,5,7,9,11,13,15,17,19};
int s1=0,s2=0;
s1=sum(val,10);
s2=sum(val+4,6); // note I gave val+4
cout<<s1<<" "<<s2;
getch();
return 0;
}

The output I get:
0 - 1
1 - 3
2 - 5
3 - 7
4 - 9
5 - 11
6 - 13
7 - 15
8 - 17
9 - 19 //ok till here
0 - 9 // why is every term added with 8 instead of 4
1 - 11
2 - 13
3 - 15
4 - 17
5 - 19
6 - 21
7 - 23
8 - 25
9 - 29
100 84

I gave as val+4 but instead I see it gets added up with 8
if I give as val+2 it gets added up with 4
val+x ----> each gets added up with 2x <--- o.O

why is that?
last point --> the above prgm was written in C++

</<s2></<arr></<endl></<s1&g t;</<i>
Because you're not adding to the items in the array. You're passing val + 4 as an array, which just so happens to be the same as val[4]. Which is 9.

Try making that call sum(val + 4, 10), and see what happens.
My answer is similar to what Jp said.

When you call "sum(val,10);", it uses "{1, 3, 5, 7, 9, 11, 13, 15, 17, 19};" numbers, but when you call "sum(val+4,6);", it uses "{9, 11, 13, 15, 17, 19};".
+4 increases address, so instead of val[0] it becomes val[4].

Edit:
Please next time use >dm< tags, better than nothing.
In response to Jp
Thanks Jp

I recollect that val just refers to the mem address of val[0]
and adding +4 to it will just result into val[0+4].

Wonderful, thanks again.
@Ripiz:
I thought that dm tag 'blue highlights' only dm keywords so I just thought of defaulting it out. ;)
In response to Quixotic
But dm tags will have proper formatting (spacing, equal width characters, etc).

If you need more help you could contact me on MSN: [email protected]