Archived

This topic is now archived and is closed to further replies.

tad pole

Can you help me understand this code (arrays)

Recommended Posts

I am having all sorts of trouble trying to understand this program. I think part of it is that it uses some increment structure that I am not used to seeing.
#include <iostream>
using namespace std;

int billy[] = {16, 2, 77, 40, 12071};
int n, result = 0;

int main()
{
     for (n=0, n<5, n++)
     {
        result += billy[n];
     }

cout << result;
return 0;
} 
Their answer is 12206 and I am not sure how they got it.
[edited by - tad pole on April 20, 2004 2:22:52 PM]

Share this post


Link to post
Share on other sites
12206 = 16 + 2 + 77 + 40 + 12071

the program simply add all the numbers in the billy array and put it in the result variable.


#include <iostream>
using namespace std;

// defines an array of integers containing 5 elements

int billy[] = {16, 2, 77, 40, 12071};
// defines 2 integers

int n, result = 0;

int main()
{
// let n = 0, loop while n<5, increment n each loop

for (n=0; n<5; n++)
{
// result = result + integer at position n in the array

result += billy[n];
}

// show the result

cout << result;

// return success

return 0;
}


hope that helps !
Matt

edit: replaced , by ; in the for loop, sorry, typo :/

[edited by - lemurion on April 20, 2004 2:33:27 PM]

Share this post


Link to post
Share on other sites
geez what is with the negativity?

thanks for the help I guess...


Edit - yes that does help, lemurion.

Thank You



[edited by - tad pole on April 20, 2004 2:30:21 PM]

[edited by - tad pole on April 20, 2004 2:31:46 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Nurgle
You''re using "," instead of ";" in your for statement.

[edited by - Nurgle on April 20, 2004 2:30:08 PM]


(I didn''t notice the error, so I assumed it was a stupid question. I *hate* stupid questions)

Share this post


Link to post
Share on other sites
no it was a a stupid question. That error was not in the original code. This is my first time trying to use arrays and I thought they were incrementing the number 0 becuase of the part that says n=0. I didnt think of that being the element of the array that was 16 wtc...

Share this post


Link to post
Share on other sites
well let''s go through it!
int billy[] = {16, 2, 77, 40, 12071};
so:

billy[0] = 16
billy[1] = 2
billy[2] = 77
billy[3] = 40
billy[4] = 12071


now this code obviously loop through the 5 elements of the array.

for (n=0, n<5, n++)
{
result += billy[n];
}

result += billy[n] is the same as result = result + billy[n]

so basically it''s:

result += billy[0];
//or result = result + billy[0]
//which is result = 0 + 16
//then
result += billy[1];
//or result = result + billy[1]
//which is result = 16 + 2
//and so on....


hopes this answer the question. or puts on the right path.

Share this post


Link to post
Share on other sites