Navigation



6.2 — Arrays (Part II)

Initializing Arrays

Because array variables are treated just like normal variables, they are not initialized when created. C++ provides a convenient way to initialize entire arrays via use of an initializer list.

int anArray[5] = { 3, 2, 7, 5, 8 };
cout << anArray[0] << endl;
cout << anArray[1] << endl;
cout << anArray[2] << endl;
cout << anArray[3] << endl;
cout << anArray[4] << endl;

Which prints:

3
2
7
5
8

What happens if you don’t initialize all of the elements in an array? The remaining elements are initialized to 0:

int anArray[5] = { 3, 2, 7 };
cout << anArray[0] << endl;
cout << anArray[1] << endl;
cout << anArray[2] << endl;
cout << anArray[3] << endl;
cout << anArray[4] << endl;

Which prints:

3
2
7
0
0

Consequently, to initialize all the elements of an array to 0, you can do this:

// Initialize all elements to 0
int anArray[5] = { 0 };

Omitted Size

If you are initializing an array of elements using an initializer list, the compiler can figure out the size of the array for you, and you can omit explicitly declaring the size of the array:

int anArray[] = { 0, 1, 2, 3, 4 }; // declare array of 5 elements

Sizeof

The sizeof operator can be used with arrays. It returns the total size allocated for the entire array:

int anArray[] = { 0, 1, 2, 3, 4 }; // declare array of 5 elements
cout << sizeof(anArray); // prints 20 (5 elements * 4 bytes each)

In C++, there is no direct way to ask an array how many elements it contains. However, using the sizeof operator, we can figure it out:

int nElements = sizeof(anArray) / sizeof(anArray[0]);

Because all of the elements of the array have the same size, dividing the total size of the array by the size of any one of the elements yields the number of elements in the array! We use element 0 because it is the only element guaranteed to exist, as arrays must have at least one element.

Arrays and Enums

One of the big documentation problems with arrays is that that integer indices do not provide any information to the programmer about the meaning of the variable. Consider a class of 5 students:

const int nNumberOfStudents = 5;
int anTestScores[nNumberOfStudents];
anTestScores[2] = 76;

Who is represented by array element 2? It’s not clear. Consequently, when known in advance, it is common to use enumerated values to index the array:

enum StudentNames
{
    KENNY, // 0
    KYLE, // 1
    STAN, // 2
    BUTTERS, // 3
    CARTMAN, // 4
    MAX_STUDENTS // 5
};

int anTestScores[MAX_STUDENTS]; // allocate 5 integers
anTestScores[STAN] = 76;

In this way, it’s much clearer what each of the array elements represents. Note that an extra enumerator named MAX_STUDENTS has been added. This enumerator is used during the array declaration to allocate one slot for each enum. This is useful for documentation purposes, and because the array will automatically be resized if another enumerator is added:

enum StudentNames
{
    KENNY, // 0
    KYLE, // 1
    STAN, // 2
    BUTTERS, // 3
    CARTMAN, // 4
    WENDY, // 5
    MAX_STUDENTS // 6
};

int anTestScores[MAX_STUDENTS]; // allocate 6 integers
anTestScores[STAN] = 76;

Note that this “trick” only works if you do not change the enumerator values manually!

Quiz

1) Declare an array to hold the high temperature (to the nearest tenth of a degree) for each day of a year. Assign a value of 0 to each day.

2) Set up an enum with the names of the following animals: chicken, dog, cat, elephant, duck, and snake. Allocate an array with an element for each of these animals, and use an initializer list to initialize each element to hold the number of legs that animal has.

Quiz answers

1) Show Solution

2) Show Solution

6.3 — Arrays and loops
Index
6.1 — Arrays (Part I)

35 comments to 6.2 — Arrays (Part II)

  • Skylark

    Hi!

    … Why is the enumerated type in the second answer called ‘Month’?

    It doesn’t matter, but it seems bizarre and is consequently FREAKING ME OUT!

    ……. =D Loving this tutorial by the way.

  • jerry

    [ Please repost your question in the forums along with some more information about what you're trying to do. Thanks. -Alex ]

  • [...] 2007 Prev/Next Posts « 5.8 — Break and continue | Home | 6.2 — Arrays (Part II) » Wednesday, June 27th, 2007 at 5:20 [...]

  • Ronnie

    Hate to be the devil’s advocate, but in the answer to example one you presumably mistyped it as ‘adTemperature’, rather than ‘anTemperature’.

    Okay, must… code.. more..

    • Nope, it’s written as intended. The “ad” prefix is Hungarian Notation for an array of doubles, which is what is being declared. “an” would be for an array of integers.

  • [...] 6.2 — Arrays (Part II)  Print This Post This entry is filed under C++ Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. 14 Responses to “6.3 — Arrays and loops” Comment by Jonas 2008-02-19 13:06:17 [...]

  • Frank

    Can you initialize an array and omit the size inside a class?
    (See OMITTED SIZE above)
    I think the answer is no but I don’t understand why?

    This is fine.

    int x[] = {1, 2, 3};
    

    This is NOT.

    class my_x {
       int x[] = {1, 2, 3};
    };
    

    Why is that not allowed?

  • hardik

    you have done a good job but it is said that man make mistakes so you have made some writting
    errors but i understood all the things very well tjrough the examples.thanks alex….

  • In your last two examples, the array’s name is inconsistent — it’s either “anTestScores” or “anTestScore” — mind the missing/superfluous “s” at the end.

    Apart from that — many thanks and a great compliment to this very useful tutorial.

    # int anTestScores[MAX_STUDENTS]; // allocate 5 integers
    # anTestScore[STAN] = 76;

    [ Fixed. Thanks for letting me know. -Alex ]

  • Chiamaka

    for question #2 would the answer still have been right if instead of using “MAX_ANIMALS” for the array you just used the number “6″?

  • Zak

    For Question 1, aren’t there 365 days of the year. So wouldn’t the correct code be:

    //Including 0, this would have 365 elements.
    double adHighTemperature[364] = { 0 };
    
    • Zak

      OK NVM THAT WAS VERY STUPID OF ME. I JUST REALIZED MY MISTAKE. I FORGOT THAT THE SUBSCRIPT OPERATOR TOLD HOW MANY ELEMENTS THERE WERE INSIDE THE ARRAY WHICH WOULD MAKE 365 THE CORRECT ONE.

      my bad :).

    • MrAlshahawy

      No , Don’t get confused between array declaration and accessing array element , if you want to have an array with 5 elements you write :

      int adHighTemperature[5];
      

      when you need to access one of the array elements you have to follow the “Zero based index rule”.

      adHighTemperature[0] = 5;// The first element.
      
      adHighTemperature[4] = 6;// The last element.
      

      I hope you got it now.

  • Zak

    And thanks so much. This tutorial is so well done.

  • Chris

    In the solution to the first quiz, why did you use a double? To waste space? A float uses less space on some peoples’ PCs and you specifically mention temperatures that only go to the tenths place. Unless we’re going to be having some serious scorchers (over 15 digits long), I highly doubt the double is necessary.

  • Joshua Sinkfield

    Why wouldn’t this work

    //solution to Quiz (2)
    // sAnimal is a already declared struct earlier in function
    //nLegs is part of sAnimal struct 
    
    sAnimal anAnimal[NUM_ANIMALS];
    anAnimal[NUM_ANIMALS].nLegs = {blah, blah, blah, blah} /* values for enumerators */
    

    I fixed the problem but just want to know what happens. Is it because the array becomes as member?

    • twilight

      I think it is because you declared an array of structs, namely as many as your NUM_ANIMALS – thing is.

      And then you are trying to assign multiple values to one integer in ONE of your structs.

      Think about it, say NUM_ANIMALS was 5.
      Then there are 5 arrays, 0 – 4. And now you try to access anAnimal[5] because NUM_ANIMALS is still 5, but there is no array 5, it is just 0 – 4.

      Aditionally nLegs is probably just an integer and declared as such. You are trying to make an array out of an Integer that is no array; inside a struct that does not exist.

  • twilight

    Hey everybody.

    Thanks for the great tutorial, but something bothers me, maybe it is just a problem of understanding english correctly, since I am not speaking english as mothertongue.

    Quiz 1: “to the nearest tenth of a degree” – I understand that I need to use float instead of an int or a double, so I did. But the solution is using a double, why is that?

    “tenth of a degree” I do understand that I would be able to have a degree say 10.5° or 5.2°. But using a double as the solution suggests, I would not be able to store 10.5°. Or is it because we use °Celsius and you °Fahrenheit? Does Fahrenheit not have 10.x or such a thing?!

    • twilight

      I just re-realized that a double is in fact a double-precision-float, not a long-int :-D woah, how could I mix them up?

      anyhow, my question remains, why is a float not sufficent or why do you need to use a double?

      maybe it is an understasnding problem of “nearest to a tenth of a degree”

  • Shawn

    Lol south-park :P

    anyways so far, i am loving your tutorials
    thanks you guys for the tutorials

  • Hello Alex,

    Can you help me in understanding the following program?
    The motive of the program is to ask the user as many numbers as he wishes, and then if he want to stop he can enter zero(0) value. Once that is done, the program will show how many elements he had entered to the array.
    But the following program prints out incorrect values and crashes. I can’t figure out what is going wrong and where.

    The Code:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int sampArray[] = { 0 };
        int x = -1;
        int count = 0;
        while (x != 0)
        {
            cout << "Enter a number: ";
            cin >> x;
            if (x != 0)
            {
                sampArray[count] = x;
                count++;
            }
        }
        cout << "Size of the array: \t\t " << sizeof(sampArray) << endl;
        cout << "Total elements in the array: \t\t " << sizeof(sampArray) / sizeof(sampArray[0]) << endl;
    
        return 0;
    }

    The Output:

    Enter a number: 1
    Enter a number: 2
    Enter a number: 3
    Enter a number: 4
    Enter a number: 5
    Enter a number: 6
    Enter a number: 7
    Enter a number: 8
    Enter a number: 9
    Enter a number: 0
    Size of the array: 4
    Total elements in the array: 1

    Regards,
    Mayur

    • caboosethepantless

      The compiler needs to know how big the array is at compile time, which means…

          int sampArray[] = { 0 }; 

      … is telling the compiler that when the program is run, to allocate space for one element, and store 0 in element 0.

      Since your array only has one element, trying to store values in the non-existent element 1, element 2, or so on will cause the program to be unstable.

      • Mayur

        Ahh!! of course. So isn’t there anyway we can declare an array of indefinite size and according to the input, let it calculate itself what the size should be ?

        • Tom

          Ahh!! of course. So isn’t there anyway we can declare an array of indefinite size and according to the input, let it calculate itself what the size should be ?

          Yes, there is a way to do that, but that is a more advanced topic that is covered later, in section 6.9 (Dynamic Memory Allocation).

  • replax

    This is the print app for exercise 2:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	enum eAnimal
    	{
    		CHICKEN,
    		DOG,
    		CAT,
    		ELEPHANT,
    		DUCK,
    		SNAKE,
    		TOTAL_ANIMALS
    	};
    
    	int anAnimalLegs[TOTAL_ANIMALS] = { 4, 4, 4, 4, 2, 0 };
    
    	for(int iii = 0; iii < TOTAL_ANIMALS; iii++)
    	{
    		cout << "Animal Legs: " << anAnimalLegs[iii] << endl;
    	}
    
    	char exit;
    	cin >> exit;
    	return 0;
    }
    

    thanks for the free tutorials btw, theyre great!!

  • prafull.badyal

    we can’t use arrays with if?? like

    if(array[2]=xyz)
    {
    do this;
    }
    else
    thiz;

  • rajen

    hello alex i have to write a program that calculate the average body mass of 5 people on the basis of their hight and weight using 2 dimensional array. where i need to use for loop, while loop, switch statement for display the menu and pointers i am totally confused with this can you plz help me for this?

    BMI= weight(kg)/height2(m)

  • anwar002

    I wrote the follwoing program: ( based on quiz 2 above)

    {
    //
    enum Animals {chicken, dog, cat, elephant, duck, snake, maxAnimal};
    int numberofLegs []={2,4,4,4,2,0};
    for (int iii = 0; iii <=snake ; iii ++)
    cout << iii << " " << numberofLegs[iii]<< endl;
    cout << "Chicken has " << numberofLegs[chicken] << " legs \n" ;

    }

    How can I make it print

    chicken has 2 legs
    dog has 4 legs
    cat has 4 legs
    etc.
    using the iii values?
    How do we access a member of an enum type?
    Thanks

  • KanedaSyndrome

    main


    #include <iostream>
    using namespace std;

    int main()
    {
    //1st part
    float dailyTemps[365] = {0};

    //2nd part
    enum animals
    {
    chicken,
    dog,
    cat,
    elephant,
    duck,
    snake,
    numberOfAnimals
    };

    char animalLegs[numberOfAnimals] = {2, 4, 4, 4, 2, 0};

    //just checking everything worked out alright
    for (int iii=0; iii<6; iii++)
    {
    cout << (int)animalLegs[iii] << endl;
    }

    return 0;
    }

    ~Kaneda

You must be logged in to post a comment.