Arrays' simple problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// arrays example
#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;
}


why the output was 12206? please englighten me
Because according for loop :

result = billy[0] + billy[1] + billy[2] + billy[3] + billy[4]

I hope it helps!
Last edited on
Here is your program written in a more "beginner programmer-friendly" way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

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

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

    cout << result;

    return 0;
}

Trace it by hand and convince yourself.
Last edited on
@Ladyney

why the output was 12206? please englighten me


Due to the rules of arithmetic.
oh i see!
it seem i have a hard time grasping c++ concept ^_^''
Topic archived. No new replies allowed.