954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Array Algorithm

I'm really not understanding what's going on with the array in this. Here's the question.

The following code totals the values in each of the two arrays. Will the code print the correct total for both arrays?

int total = 0;
int count;

for (count = 0; count <= 25; count++)
	total += array1[count];
cout << "The total is " << total << endl;

for (count = 0; count <= 25; count++)
	total += array2[count];
cout << "The total is " << total << endl;


I'm not understanding this at all. Both arrays hold 25 integer elements but they aren't equal to anything, so im just lost here... or maybe it's really simple and I'm thinking too hard about it...

Foe89
Newbie Poster
22 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

If both array1 and array2 contain 25 elements then you should write your for loops

for (count = 0; count < 25; count++)


as arrays of n elements are indexed from 0 to n-1.

Moreover, the second cout will print the sum of all the elements of the second arrayplus the sum of all the elements of the first array, as long as you don't reset your total variable between the for loops.

EDIT: What do you mean with "they aren't equal to anything" ? Please clarify this.

mrboolf
Junior Poster
183 posts since Jun 2008
Reputation Points: 134
Solved Threads: 18
 

Leave out the equal sign in <= !
Else you are counting from 0 to 25 inclusive, which is 26, not 25.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

Don't know what I was thinking there. I changed it to just greater than and then inbetween the two for loop I made total = 0 again. Both arrays outputted -20 so that seems to be working properly. So by not initializing total to = 0 again after the first array is finished will cause total to equal whatever it was in the first output which would be -40 which I checked and so the counter in the for loop must be written as < and not <= because the element starts at 0? I'm going to look in my book about the indexing

Foe89
Newbie Poster
22 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

Don't worry, there are many people on this globe(including me) that have made this mistake. Join the club!

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You