Arrays' simple problem

Aug 28, 2013 at 3:19pm
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
Aug 28, 2013 at 4:06pm
Because according for loop :

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

I hope it helps!
Last edited on Aug 28, 2013 at 4:11pm
Aug 28, 2013 at 4:18pm
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 Aug 28, 2013 at 4:19pm
Aug 28, 2013 at 5:22pm
@Ladyney

why the output was 12206? please englighten me


Due to the rules of arithmetic.
Aug 30, 2013 at 12:18pm
oh i see!
it seem i have a hard time grasping c++ concept ^_^''
Topic archived. No new replies allowed.