i cant understand this!!

This is a discussion on i cant understand this!! within the C++ Programming forums, part of the General Programming Boards category; hi i started learnin c++ and i just cant understand this code: // arrays example #include <iostream.h> int billy [] ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2

    i cant understand this!!

    hi i started learnin c++ and i just cant understand this code:

    // arrays example
    #include <iostream.h>

    int billy [] = {1, 2, 3, 4, 5};
    int n, result=0;

    int main ()
    {
    loop1: cout << "input a number smaller than 5 \n ";
    cin >> n;
    if (n>=5)
    goto loop1;

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

    i even made the arrays very small to try to understand it but i just cant!! heres my understanding..
    i input a n say like 2
    then in the formula result += billy[n] means..? result += result + billy[3]??
    this is weird the outcome are as follows when i enter the numbers
    0=15
    1=14
    2=12
    3=9
    4=5

    please shed some light for this newbie

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    you really shouldn't be using goto.

    when you enter 0; it'll add all the values

    1 + 2 + 3 + 4 + 5 = 15

    what this does is billy[0] == 1;
    billy[1] == 2;

    etc. etc.

    arrays start at index 0.

    so if you enter 2; it will start at billy[2] and add up billy[2] + billy[3] + billy[4].

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2

    thx

    hey ths alot .. i didnt know how the answer was coming but that made sense.. hehe

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    Whatever book are tutorial you got that code from, do not study it anymore. That is not C++. Get an up to date book or tutorial.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by 7stud
    Hi,

    Whatever book are tutorial you got that code from, do not study it anymore. That is not C++. Get an up to date book or tutorial.
    Of course it's C++. What else would it be? Everything there is valid C++ code. It's damn ugly code, but it is C++.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21