An alien variable suddenly in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HolyDoom Witch
    New Member
    • Oct 2012
    • 34

    An alien variable suddenly in an array

    H! there

    I am learning C++. While the author of this website (called CPlusPlus.com) seems to be good enough, sometimes he does miss out on explaining a few things, that I keep wondering, till either I keep experimenting and thus understand, or refer the Internet.

    This time, it is the arrays chapter I have reached. In the code I am giving below, he never explained in the first place why an alien variable should be in the array's square brackets in the first place, let alone how all the figures of the array are adding up automatically, without having given any such instructions. The second one I guess, "assume" rather, that when you want to add up all the figures, this is what you have to do-- this is its formula.

    While searching something earlier, I happened to reach this site, and understand there are a few good experts here. Explain to me too how and why should an alien variable be placed inside the square brackets of an array.

    Code:
    int billy [] = {16, 2, 77, 40, 12071};
    int n, result=0;
    
    int main ()
    {
      for ( n=0 ; n<5 ; n++ )
      {
        result += billy[n];
      }
      cout << result;
    After running this code we get: "12206".

    Thanks
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    I don't know what an alien variable is, I haven't heard that term before. But if you're talking about the n, that's because it's being used to access each item in the array.

    The for loop will run 5 times, setting n = 0, 1, 2, 3, 4. The += operator is the same as taking the existing value and adding to it.

    Comment

    • johny10151981
      Top Contributor
      • Jan 2010
      • 1059

      #3
      The output is correct and the program is behaving as it was suppose to be.

      I will say you didn't read properly. Read more read brief.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You might also read this: http://bytes.com/topic/c/insights/77...rrays-revealed

        Comment

        • HolyDoom Witch
          New Member
          • Oct 2012
          • 34

          #5
          No no, I perfectly understand that the program is perfect, and I also understand that the behavior is perfect too. (As far as reading is concerned, I have to read a thousand times or I won't understand; now, due to whatever problem may that be.) What I want to know is that how come we use a variable in an array, that was never connected to it earlier in ANY way? So the answer to this is probably, that we can place a variable in an array from a particular formula, and that would give us a particular, pre-determined result in an array. For example, if we try to use the multiply operator here, then values don't multiply with each other, but they do add with each other. I assume this assumption would be the answer.

          I was expecting some more explanation about the arrays behaving in such a manner. May be things I haven't been told. (Like they tell about C++ itself, that "this is C++, and it is going to behave this way no matter what".) For example, if someone said the following, I would have understood much better: 'if we place such-and-such variable in the array brackets, then we get this result. So whenever we need this result, we give this variable, from this formula, to the array'. (Because you won't get same results everywhere, like by placing the same variable from the same formula to some other place.) Or if someone said: 'if we place 'that' variable in an array, then we get that result'. I think the array chapter needed a whole paragraph that would tell 1) what kind of results can be churned out of an array, and 2) how. Which is missing, I think.

          Here is one last example. You are experts, you may not find any problem with this code. But please try to see it from the point of view of a beginner, who was till now told: 'use this structure, and get this result'. Like he was also told: 'use square brackets, and get an array'. But when was he told that 'in C++, you can also add all the values of an array to each other by using a formula, and this is that formula'? What I suddenly was getting, that all the values of an array were adding up with each other as a result of an 'alien variable'.

          I am sure you now understand, what I mean.

          Never mind, I now take this behavior for granted, for this particular formula, and would assume so, as and when I encounter more such behavior.

          Thanks

          Comment

          • zmbd
            Recognized Expert Moderator Expert
            • Mar 2012
            • 5501

            #6
            WOW,
            HolyDoom_Witch. ... such a fantastic bit of writing that demonstrates a considerable amount of thought... and yet, you are simply quite over thinking the entire thing and lost sight of what that poor little "n" is doing... it's not a bandersnatch I assure you... I have one. ;-)

            Take a step back, and please calm yourself (or at least from what you have written you come across as quite frustrated, exasperated, confused, and slightly (ever-so slightly) twitterpated. Running in thought as thou a Bandersnatch was chasing you thru the forest (they are nasty creatures I assure you, but quite gentile once they get to know you... provided they don't eat you first... .... ... hmmm - speaking which, time to feed mine... they do get hungry, wonder where it's gotten to - oh, behind you :) Here BS, leave the nice HDW alone... )

            ANYWAY (or maybe this-way or that-way - perhaps the other-way)

            Let's head towards the light... Bandersnatches don't like the light and it'll leave us alone for a few moments before the sun sets.

            Using your example: poor little "n" is a stand-in for the hard coded index referring to the element in the array - a symbolic representation of the index if you will allow it to be so...

            However, let's look at your poor "n" from a mathematical means of reason - a different light and horse of another colour:

            The "n" is much like 1+Z=1000 where-in the "Z" is a stand-in for the number 999. We quite simply could have used "a" or "b" or "n" or as you'll see in my daughter's 4th grade text they substitute a triangle, square, or other such symbol - would be simply cool to use a "Ж" in code to represent a variable... well in Russian it works... why not English... just not fair ( mumbles to self )

            OR

            If you like space and time references, let's put that poor little "n" into space (Wonder if the Bandersnatch needs to breath air, never tried walking with it there before, maybe that'll be where we walk tonight) ... make it a point in space. Take the Cartesian reference for that point (that point of course being "n") in three dimensional space (x,y,z) (or there is the polar reference method too but let's not go there as it's quite cold this time of year however it would be (r,theta)).

            Why use the letters X,Y,Z or the array (x,y,z)... they have nothing in common with the point in space that they define (that being the poor little "n" wonder if some tea and honey would help it)... for that fact why use the equation aX^2+bX+c to describe an parabolic lying within the x,y plane - these are merely symbolic representations and have very little to do with the points (lines, curves, etc) themselves.

            SO (with-needle-and-thread), back to your code and the last:
            But when was he told that 'in C++, you can also add all the values of an array to each other by using a formula, and this is that formula'? What I suddenly was getting, that all the values of an array were adding up with each other as a result of an 'alien variable'. Get it?
            to achieve the same thing that your code is doing without using the "n" you would need to do the following:
            (note that I'm coding by hand here... I don't have any flavor of C-compiler or IDE with which to work so there might be a syntax error; however, you should be able to understand the idea):
            Code:
            int billy [] = {16, 2, 77, 40, 12071}; 
            int result=0; 
              
            int main () 
            { 
              result += billy[0];
              result += billy[1];
              result += billy[2];
              result += billy[3];
              result += billy[4];
              cout << result; 
            }
            My word... could you imagine trying to code this for an array of 1000 or more elements... or say a cross-product of two different two dimensional arrays..... I'd feed the madman that wanted that hardcoded to my Bandersnatch (there's never any evedence once the Bandersnatch eats you! ( manical laughter )

            As for defining "n" as an array and trying to push that into the index pointer of a different array... that more than likely might fail... and I've never tried it as such is a redundent formulation of a tertiary or higher order array or a poor attempt at an array function.

            NEVER just accept something if you don't have to... St. Albert the Great took on Aristotle and the other Great Philosophers of his age... However, in doing so... do not over think the question so that you start looking for an answer that has nothing to do with the question in the first place. In all of all of that I was taught in my undergrad studies as a Chemist came to me from my Analytical Chemistry Professor: "Young Man... Good Chemistry is Easy Chemistry. You will not find the answer by pounding your head thru the wall, and if you are doing so, then you have missed something simple."

            Comment

            • zmbd
              Recognized Expert Moderator Expert
              • Mar 2012
              • 5501

              #7
              My apologies for the length of the prior post... it was quite simply the shortest path I could find out of the forest without a light, gps, or my Bandersnatch... they don't like the light.

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                What you put between the square brackets of an array is: a)if you are creatng the array it is the number of elements, or b) if the array exists then it is the element number. It doesn't matter that the elemenent number is a variable. However, if it is a variable then it is up to you to be sure you have the correct element number in the variable.

                Please stop using the term "alien variable". I have never heard this term before and I expect it is a bogus term.

                Also, the arrays in C and C++ are identical in behavior.

                Comment

                • Rabbit
                  Recognized Expert MVP
                  • Jan 2007
                  • 12517

                  #9
                  @johny, the poster was not saying the code wasn't working. They were saying that they didn't understand why it works.

                  This is one way you create and populate an array:
                  Code:
                  int someArray[] = {5,8,2};
                  This is how you access an item in an array:
                  Code:
                  someArray[0];
                  Where the number between the brackets is the number of the item you want to retrieve. 0 is the first item in the array, 1 is the second, and so on. So someArray[0] will return 5.

                  Given that, if x = 1, what is the value of someArray[x]?

                  Comment

                  • HolyDoom Witch
                    New Member
                    • Oct 2012
                    • 34

                    #10
                    Please excuse me. I suddenly have a brainwave (while preparing a long reply... whew!).

                    Here is what I missed:

                    1. billy [0 or 1 or 2 or 3 etc] COUTs values of each of the elements starting from the first element, which is tagged "0".

                    2. An int named "n", somewhere (that's why 'alien'), is initiated to 0.

                    3. Placing "n" in the array as billy [n], converts billy [n] into billy [0], and which is the first value from the array.

                    4. After n++, n becomes 1, and now billy [n] becomes billy [1], the second value from the array.

                    That's all I missed. I would make such a mistake once per decade. But I might have crossed my limits by making TWICE, a similar mistake, since I started learning C++ alone (Aug 21, 2012), which is: NOT waiting for some more time before deciding that I should take advice before reading further. Generally I read on if I absolutely don't understand anything after repeated attempts, referring back till I am actually done with it. May be enough sleep (really) would keep my brain from slipping away mutually related things that connect with each other and make things understand when we remember them together. Here my mind slipped the fact how one single number in the square brackets becomes the serial number of an element, and now starts holding the value of that element. So if it's a variable there, or an identifier rather, and we keep assigning this identifier different numbers... (So what the hell did I forget, that variables can take numbers?!)

                    The author has done a lot of explaining in many a thing too lucid. Somehow, if he wrote a line about this too since this was not exactly "lucid", but slightly obscure; after all it's a 3 layer thing: variable> element serial-number> value, that also a variable with changing values... never mind. May be it's not his fault even then.

                    Though I am unable to discredit your explanations because, just as it was difficult for me to catch exactly what it was I was missing, it can always be impossible for a third party to know what someone is missing.

                    I also had this feeling of losing myself in a forest or something-- like in Underlands; now I don't know exactly if I had this feeling before starting this thread, or after. After, I think...

                    Before that, these were the references in your replies I was digging into:

                    1. @ zmbd
                    "n" is a stand-in for the hard coded index referring to the element in the array - a symbolic representation of the index if you will allow it to be so...
                    2. @ weaknessforcats
                    What you put between the square brackets of an array is: a)if you are creating the array it is the number of elements, or b) if the array exists then it is the element number. It doesn't matter that the elemenent number is a variable. However, if it is a variable then it is up to you to be sure you have the correct element number in the variable.
                    At that time I thought that this was the best reply.

                    3. @ Rabbit
                    - full reply -
                    This reply was the closest to the thing I missed, going right past the explanation I have given above in this reply, missing it by a whisker. Yet I did not get it. Even after including this in my reply. I may have complicated things a bit more though (by posting that reply). At first I thought what a kiddish thing to say! :D

                    Other than that I was planning to read what weaknessforcats posted as a link. I'll go there if there is something I need in the arrays again, since I still have a section left in the array chapter called "Arrays as parameters".

                    If everybody votes, then I can delete this thread, too.

                    Please excuse me for rolling the reply machinery into action full steam. I'll take special care to "wait" before I seek help here again.

                    Thanks to everybody.

                    Comment

                    • Rabbit
                      Recognized Expert MVP
                      • Jan 2007
                      • 12517

                      #11
                      I wouldn't delete this thread. It can prove useful for someone else facing the same difficulty. And if you have trouble understanding something, don't feel like you shouldn't ask, that's what we're here for.

                      Comment

                      • HolyDoom Witch
                        New Member
                        • Oct 2012
                        • 34

                        #12
                        Great! I'll feel less sick now! :)

                        Comment

                        • HolyDoom Witch
                          New Member
                          • Oct 2012
                          • 34

                          #13
                          Unless I have a feeling, that doesn't go, in which I feel that there are some hidden definitions that I need to be TOLD which someone did not (as opposed to something I have to "understand "), I would not go to a forum. In this, somehow I got convinced that there is something hidden I haven't been told about. If I waited, I would know.
                          ***

                          Comment

                          • weaknessforcats
                            Recognized Expert Expert
                            • Mar 2007
                            • 9214

                            #14
                            There's nothing hidden. Did you read the article I referred to in Post #4?

                            As you say. you are a beginner and I remember when I was in the same position and I found arrays to be terribly confusing until I studied them closely, wrote code to exercise array concepts and made myself a PowerPoint presentation about arrays. I reasoned that if I couldn't explain it, then I didn't understand it.

                            Comment

                            • HolyDoom Witch
                              New Member
                              • Oct 2012
                              • 34

                              #15
                              H! weaknessforcats

                              Of course there was nothing hidden; only I got convinced there was. That's what I said above as you can see clearly.

                              Besides, also arrays absolutely did not confuse me; they seemed easy enough (at least to me). Only thing was, that it was going to take a day or two for me, as it got proved later, to realize that the ever changing values of some variable "n" now placed inside the array were nothing but jumping element serial numbers of that array. Instead I jumped the guns. Due to the nature of the code suddenly ending up with a total of all the element values, I thought there were some more pre-defined instruction sets in C++, that can be used in conjunction with arrays EXCLUSIVELY, about which I haven't been told in the tutorials, which I thought was the case here.

                              I need to realize that when someone starts talking about an absolutely new material as if it were something extremely common knowledge, then there are only two possibilites: Either we are ACTUALLY, completely unaware of it, OR, we are missing out on something, like ignoring a fact. I thought the former was the case here. But it happened to be the later. (Like zmbd even pointed out too (which I absolutely did not like at that time ;p, may be because he did not tell what it was I was overlooking) in the beginning of his long post. But probably each one of you knew a little bit of what it was I was missing.)

                              I too tend to make a somewhat lengthy and sophisticated program before starting the next chapter. I had planned it for the arrays too. But what I thought was that since I cannot understand this particular thing, which means there could be some mistake on part of the author of omitting some more definitions he ought to reveal, so I took to the forum, posted, and kept waiting for a reply instead of continuing to think about the problem, or read further and keep referring back. But that was the mistake I made.

                              Thx

                              Comment

                              Working...