d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Basic C++ Question
Add Reply New Topic New Poll
Member
Posts: 30,905
Joined: Feb 18 2007
Gold: 0.00
Nov 5 2015 07:41pm
I am using this with an array of 1,2,3,4,5
I want it to add the indices, so index 0 + index 1 etc:
Code
for(int x = 0; x < 5; x++){
int sum = Array[x] + Array[x+1];
cout<<sum<<endl;

}


It gives me all correct answers except for some reason the last number output is 32769


Any idea why?
Member
Posts: 23,862
Joined: Aug 16 2006
Gold: 20.00
Nov 5 2015 07:43pm
Quote (jro1221 @ Nov 5 2015 08:41pm)
I am using this with an array of 1,2,3,4,5
I want it to add the indices, so index 0 + index 1 etc:
Code
for(int x = 0; x < 5; x++){
int sum = Array[x] + Array[x+1];
cout<<sum<<endl;

}


It gives me all correct answers except for some reason the last number output is 32769


Any idea why?


it is a short loop, so unroll it

array[0] + array[1]
array[1] + array[2]
array[2] + array[3]
array[3] + array[4]
array[4] + array[5]

notice the bold?

if you know about how arrays/pointers work in C/C++ you'll quickly see the problem

This post was edited by Eep on Nov 5 2015 07:46pm
Member
Posts: 30,905
Joined: Feb 18 2007
Gold: 0.00
Nov 5 2015 07:49pm
Quote (Eep @ Nov 5 2015 06:43pm)
it is a short loop, so unroll it

array[0] + array[1]
array[1] + array[2]
array[2] + array[3]
array[3] + array[4]
array[4] + array[5]

notice the bold?

if you know about how arrays/pointers work in C/C++ you'll quickly see the problem


Yup, figured it out
Working great. Thanks
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll