CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Array problem

  1. #1
    Join Date
    May 2009
    Posts
    3

    Array problem

    Hi,
    I am learning to program in C++ and have been learning arrays. In the following piece of code I am wanting to fill an array with the values 100-109. myarray[1] = 100, myarray[2] = 101 and so on. However, when this code is executed, b is actually taking on the values 100 - 109. What have I done wrong here.

    thanks


    #include <iostream>

    using namespace std;

    int main()
    {
    int b, c = 100;
    int myarray [10];
    for (b =0 ; b<=9; b++) {
    myarray [b] = c; // want b to have value 0-9 and be filled with value 100-109.
    c++;
    cout << "myarray [" << myarray [b] << "] = " << c << "\n";
    }


    system("pause");
    return 0;

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    Re: Array problem

    You print out the wrong content. Variable b is your index and use myarray[b] to retrieve the value of each element in the array.

    Code:
    cout << "myarray [" << b << "] = " << myarray[b] << "\n";
    quoted from C++ Coding Standards:

    KISS (Keep It Simple Software):
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.

    Avoid magic number:
    Programming isn't magic, so don't incant it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured