C++ Help

This is a discussion on C++ Help within the C++ Programming forums, part of the General Programming Boards category; I have written the code and is trying to fix it to display the values entered into an inventory array. ...

  1. #1
    nazma
    Guest

    C++ Help

    I have written the code and is trying to fix it to display the values entered into an inventory array. I am really stuck, can someone please see if you can help me out:


    #include <iostream>
    using std::cout;
    using std::endl;

    int main()
    {
    int j;
    int n[10] = {12, 45, 23, 89, 56, 23, 12, 44, 77, 54};
    for (j = 1; j <= 10; j++)
    cout << “Inventory Item # “ << j << “ has “ << n[j] << “ items remaining.” << endl;

    return 0;
    }

    Thanks

    Nazma

  2. #2
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Null terminate:
    Code:
    int n[11] = {12, 45, 23, 89, 56, 23, 12, 44, 77, 54};
    n[11] = NULL

    Please use code tags ( # button )
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  3. #3
    Registered User happycoder's Avatar
    Join Date
    Jun 2003
    Posts
    6
    just start the for loop at 0, like this:

    Code:
    for (j = 0; j < 10; j++)
       cout << “Inventory Item # “ << j << “ has “ << n[j] << “ items remaining.” << endl;

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    249
    In an array of 10 integers, the first number is stored in element 0, and thus the last is stored in 9. So that's why your loop needs to look like:

    Code:
    for (j = 0; j < 10; j++) {...}

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