Navigation



6.1 — Arrays (Part I)

In a previous lesson, you learned that you can use structs to aggregate many different data types into one variable. However, structs are not the only aggregate data type. An array is an aggregate data type that lets you access multiple variables through a single name by use of an index. In C++, all of these variables must have the same type.

Consider the case where you want to record the test scores for 30 students in a class. To do so, you would have to allocate 30 variables!

int nTestScoreStudent1;
int nTestScoreStudent2;
int nTestScoreStudent3;
// ...
int nTestScoreStudent30;

Arrays give us a much easier way to do this:

int anTestScores[30]; // allocate 30 integers

In the above example, we declare an array named anTestScores. When used in an array definition, the subscript operator ([]) is used to tell the compiler how many variables to allocate. In this case, we’re allocating 30 integers. Each of these variables in an array is called an element.

To access each of our 30 integer array elements, we use the subscript operator with an integer parameter called an index to tell the compiler which variable we want. The first element of our array is named anTestScores[0]. The second is anTestScores[1]. The tenth is anTestScores[9]. Note that in C++, arrays always count starting from zero! This means an array of size N has array elements 0 through N-1. This can be awkward for new programmers who are used to counting starting at 1.

Note that the subscript operator actually has two uses here: in the variable declaration, the subscript tells how many elements to allocate. When using the array, the subscript tells which array element to access.

int anArray[5]; // allocate 5 integers
anArray[0] = 7; // put the value 7 in element 0

Let’s take a look at a simple program that uses arrays:

int anArray[3]; // allocate 3 integers
anArray[0] = 2;
anArray[1] = 3;
anArray[2] = 4;

int nSum = anArray[0] + anArray[1] + anArray[2];
cout << "The sum is " << nSum << endl;

This program produces the result:

The sum is 9

Array elements may be accessed by a non-constant integer variable:

int anArray[5];
int nIndex = 3;
anArray[nIndex] = 7;

However, when doing array declarations, the size of the array must be a constant.

int anArray[5]; // Ok -- 5 is a literal constant

#define ARRAY_SIZE 5
int anArray[ARRAY_SIZE]; // Ok -- ARRAY_SIZE is a symbolic constant

const int nArraySize = 5;
int anArray[nArraySize]; // Ok -- nArraySize is a variable constant

enum ArrayElements
{
    MAX_ARRAY_SIZE = 5;
};
int anArray[MAX_ARRAY_SIZE]; // Ok -- MAX_ARRAY_SIZE is an enum constant

int nSize = 5;
int anArray[nSize]; // Not ok! -- nSize is not a constant!

To summarize, array elements can be indexed with constants or non-constants, but arrays must be declared using constants. This means that the array’s size must be known at compile time!

Arrays can hold any data type, including floating point values and even structs:

double adArray[5]; // declare an array of 5 doubles
adArray[2] = 7.0; // assign 7.0 to array element 2

struct sRectangle
{
    int nLength;
    int nWidth;
};
sRectangle asArray[5]; // declare an array of 5 sRectangle

To access a struct member of an array element, first pick which array element you want, and then use the member selection operator to select the member you want:

// sets the nLength member of array element 0
asArray[0].nLength = 24;

Elements of an array are treated just like normal variables, and as such have all of the same properties.

6.2 — Arrays (Part II)
Index
5.9 — Random number generation

43 comments to 6.1 — Arrays (Part I)

  • [...] and restrictions in their use. By far the most commonly used container in programming is the array, which you have already seen many examples of. Although C++ has built-in array functionality, [...]

  • Allen01

    Alex, not sure what is meant in this example, where array elements may be accessed by a non-constant integer variable; is “nIndex” the assigned index value, or is it an element value? I understand the first line and the last line seems to indicate that the value of 7 is being put into element nIndex. If so, should nIndex on line 2 be in [ ]?

    int anArray[5];
    int nIndex = 3;
    anArray[nIndex] = 7;
    
    • nIndex is the assigned index value. We set the value of nIndex on line 2 of your example. The element value is what comes after the assignment on the third line.

      To be as clear as possible: array indices must be integers. You can use either a literal index:

      anArray[3] = 7;
      

      or a variable index:

      int nIndex = 3;
      anArray[nIndex] = 7;
      

      nIndex doesn’t have to be a constant integer.

      Both of the above examples do the exact same thing: assign the value of 7 to array element 3. When the statement anArray[nIndex] = 7 is evaluated, the array index part takes precedence and is evaluated first. nIndex is evaluated to produce the value 3, and then anArray[3] = 7 assigns the value 7 to array element 3.

      The index itself is just an integer — thus, no need for []. You only need the [] when you’re accessing the array itself.

  • programmer

    thanks Alex

    but I still get some confuse .. could you please give an example like a complete program about what we could do with array ..

    thanks

  • greensteepe

    thanks Alex!
    Would you tell me about array with unknown number elements?
    thank you so much!

    • I’m not sure I understand your question. What do you mean by an unknown number of elements?

      It sounds to me like you’re talking about arrays where the size isn’t known in advance — this is handled via dynamic allocation, and is covered in lesson 6.9.

  • [...] 2007 Prev/Next Posts « 5.7 — For statements | Home | 6.1 — Arrays (Part I) » Tuesday, June 26th, 2007 at 4:22 [...]

  • Sinni

    int anTestScores[30]; // allocate 30 integers || anArray[3]; // allocate 3 integers

    If it starts counting at 0, shouldn’t these instead read anTestScores[29] and anArray[2] ?

    • csvan

      No, because you will still get 30 memory slots within that array (0 – 29). Thus, when you write int myArray[30], you are telling the compiler you want an array holding 30 integers. They will (normally) be allocated, and the first one will be at location 0, and the last one at location 29 :)

      Keep coding, use it for good :)

  • Unz

    Hi, Thanks for all this, excellent site. My compiler lets me allocate an array using a user defined variable. (For example, the user can input the size of array, at runtime, it works fine). Am I mis-understanding this or is this a problem with my compiler? (I use Code::Blocks – MinGW)

    • Most compilers don’t conform precisely to the C++ spec. Many will let you “get away” with things that you technically shouldn’t be able to do. A good example is that most compilers will let you declare main() as returning void instead of int. Technically not part of the C++ spec, but compilers let you do it anyway. It may be that Code::Blocks is more permissive in how it lets you allocate arrays than is defined in the C++ spec.

      • Unz

        Of course you are correct (never much doubt was there!). But the unusual behaviour wasn’t with Code::Blocks itself. While still using Code::Blocks, I changed the default compiler from the GNU GCC that I usually use, to MS Visual 2005/2008. And then it refused to compile (for the same reasons you mention).

        Seems MinGW GCC compiler is a little more lenient, in this respect at least.
        (Which is just as well because I can’t think of another solution to my problem.
        Thanks again. This site is exactly what I need. Its **easily** the best around & I hope you’re doing OK out of it.)

        • Eugene Wee

          What you are looking at is the effect of a compiler extension. In the 1999 edition of the C Standard (not C++, but C), a feature known as “variable length arrays” was introduced. The GNU C compiler implemented this feature, and it was ported over to the GNU C++ compiler as a compiler extension. As such, the MinGW port of g++ has this compiler extension.

          To disable such compiler extensions when compiling with g++, use the -pedantic option.

          Note that Code::Blocks is not a compiler, but an IDE. The compiler is the MinGW port of g++.

        • csvan

          There is a way to work around this – its a bit of overkill at this part of the tutorial, but you can use dynamic arrays to get around this limitation in VS:

          int size;
          cin >> size;
          int *myArray = new int[size];
          

          you can now use the pointer myArray (see later on in this tutorial how pointers work!) ALMOST as an array. I say almost because I think I have heard somewhere that pointers and arrays are NOT functionally equivalent, although they seem to be at face value.

          Hope it helps! Mail me if you have any problems with what I wrote (csvanefalk@hushmail.me)

          Keep coding. Use it for good :)

          EDIT: Note that the above dynamic array is declared for ints! If you want an array of doubles, I think you have to do the same thing for doubles (although the variable size itself should still be able to be an int, as it only defines the size of the array, not its content).

  • is asscociative array can also be done in c++?

  • Ivan

    “Prev/Next Posts” at the top of the page points back to 5.8 instead of 5.9. (random number generation)

    [ Seems okay now. The caching plugin probably had the old version cached for a while. -Alex ]

  • [...] 2007 Prev/Next Posts « 6.1 — Arrays (Part I) | Home | A.1 — Static and dynamic libraries » Wednesday, June 27th, 2007 at 5:48 [...]

  • Naga
    Why Array index starts from zero 
  • chong

    halo..im having a problem to find where is the array now..my sample output should be

    ” Enter a number to find
    15

    a[7]=15
    The number is found at positoon 8″

    what is my problem below to get the a[THIS VALUE]? please help me

    #include
    using namespace std;

    int main()
    {
    int num;
    int result=0;
    const int size=10;
    int a[size] = { 1,10,2,5,7,8,12,15,9,2};

    cout<< " Enter a number to find "<>num;

    if (num == a[size])
    {
    num=a[size];
    }

    cout<<"a["<<num<<"] = "<<num;
    result = num+1;
    cout<<"\nThe number is found at position no "<< result<<endl;

    system("pause");
    }

  • ellankavi

    You can try this one… I am also just going through this website. Nice work Alex. Thanks a lot!

    #include<iostream>
    
    int main()
    {
        using namespace std;
        const int nIndex=10;
        int nArray[nIndex]={1,10,2,5,7,6,12,15,9,2};
        cout<<"Number: ";
        int nNum;
        cin>>nNum;
    
        for (int iii=0;iii<nIndex;iii++)
        {
            if(nArray[iii]==nNum)
            {
                cout<<"a["<<iii<<"] = "<<nArray[iii]<<endl;
                cout<<"Number position: "<<iii+1<<endl;
                break; //disable if you want to check for multiple occurances
            }
        }
        return 0;
    }
    
  • When compiling, I get these errors:

    C:\devel\kernel>gcc clearscreen.c
    In file included from clearscreen.c:1:
    kernel.h:5: warning: data definition has no type or storage class
    kernel.h:5: error: conflicting types for 'vidloc'
    kernel.h:4: note: previous declaration of 'vidloc' was here
    kernel.h:5: error: invalid initializer
    kernel.h:6: warning: data definition has no type or storage class
    kernel.h:6: error: conflicting types for 'vidloc'
    kernel.h:4: note: previous declaration of 'vidloc' was here
    kernel.h:6: error: invalid initializer

    Here is kernel.h:

    #ifndef KERNEL_H
    #define KERNEL_H
    char *vidram = (char *) 0xb8000;
    int vidloc[2];
    vidloc[0] = 1;
    vidloc[1] = 1;
    #endif
    • ellankavi

      Could you tell us what you tried compiling?

      • I tried to compile the following code:

        #include "kernel.h"
        void clear_screen() // declaration
        {
        	unsigned int i = 0;
        	while(i < 4000){
        		vidram[i]=' ';
        		i++;
        		vidram[i]=0x07;
        		i++;
        	};
        	vidloc[0]=1;
        	vidloc[1]=1;
        }
        int main(){
        	clear_screen;
        }

        Compiling works if I delete line 5 and 6 of “kernel.h” but I would like to leave it in the header.

  • Harsh

    #include
    void main()
    {
    char str[200];
    }

    In this particular program is there any kind of memory leakage if the program is compiled in :-
    1) C
    2) C++

  • #include
    #include
    void main()
    {
    clrscr();
    int a[8],i,large;
    cout<<"Enter the elements of an array";
    for(i=0;i>a[i];
    cout<<"Comparing";
    large=a[0];
    for(i=1;1<=7;i++)
    {
    if( large<a[i])
    large=a[i];
    }
    cout<<"largest element is"<<large;
    getch();
    }

  • I have written that program to find the largest element in an arry, but i found warning or an error, i couldn’t find it so please help me to execute it. Thanks

  • mariusrazvan

    First of all i love what you did here… its a great thing,

    second, i have a doubt… you said that “Arrays can hold any data type, including floating point values and even structs” … can it hold char type too? tried but it only holds chars till it finds empty space…
    i want something like
    cout << "enter your text here" <> rawtext;

    cout << "your text is:" << rawtext << endl;
    // and i want the output: enter your text here
    // but i only get the first word…
    // if i input enteryourtexthere i get all the text as output…

    so my problem is with the empty space between the words…

  • astronaut13

    Would an array be good if, say, I was making a game that had an inventory, and I wanted to use the array for all the have/don’t have variables? Or is there a better way?

  • Akash Biswas

    I want a 2-dimensional string array program in which I can count the number of palindromes. Could you please help, Alex.

  • moon1212

    Q.1 write a the c program using a function method to calculation the area and perimeter for the rectangle and the square by any given width and height . the program should ask the user to stop or retry the program with other values .

    Q.2 write a program in c language using a function method to calculate the following series and give the result;
    X= n^1*n^2*n^3*…………* n^k
    Where n&k are any number given by the user

    pls… help me

  • sufy

    Wait… if C++ won’t let you do:

    cin >> nVar;
    int aArray[nVar];

    Can’t you just do:

    int nVar;
    cin >> nVar; // This can be replaced with anything that gives nVar a value.
    const int nArray = nVar;
    int someArray[nVar];

    Thereby easily bypassing the inability to give an array a variable size! :D

    …I think :-/

  • tiger

    Somebody can help me on this code. the program get input from user to enter grade score up to 5 different grade. be able to stop the loop if user enter Q, then calculate the average of the grade scores; the max and min of the grade scores. I could not make it work!
    #include

    using namespace std;

    int main ()
    {
    int gradeScore[4];
    int i,sum=0, avg=0;
    int count;
    int max=0,min=100;
    do
    {
    cout << "Enter grade score of the student " <> gradeScore[i];
    cout << "grade is " << gradeScore[i] << endl;
    i++;
    count = i + 1;
    cout << "count is " << count << endl;

    }while (count <=4 || gradeScore[i] == 'Q');

    for(i=0;i<count;i++)

    {
    sum +=gradeScore[i];
    cout << "Sum is " << sum << endl;
    }

    for(i=0;imax)

    {

    max=gradeScore[i];

    }

    if(gradeScore[i]<min)

    {

    min=gradeScore[i];

    }

    }
    avg = sum / count;
    cout << "SUM is: "<< sum << endl;
    cout << "COUNT is "<< count << endl;
    cout << " Average is " << avg << endl;
    cout << "Average grade of the student : " << avg << endl;
    cout << "Maximum grade of the student of the class : " << max << endl;
    cout << "Minimum grade of the student of the class : " << min << endl;

    return(0);

    }

  • Hossein

    Thank you for the great documentation :)
    By the way on the latest compiler versions ( starting from gcc 4.3+ and possibly VC++ 10) arrays size can be dynamically specified at run-time meaning now the statement below:
    int nSize = 5;
    int anArray[nSize]; //Is Ok in the latest compiler versions such as gcc (4.3+) and VC++10+

    is pretty fine and will compile just fine.
    So it would be a good idea to update the documentation to address new changes .
    Regards

  • rogererens

    The enumerator

    MAX_ARRAY_SIZE = 5;

    contains a spurious semicolon.

    Also, the previous/next links at the top and bottom of the pages frequently skip chapters. (Currently the ‘previous’ link points to chapter 5.8 instead of 5.9. (The links in using the white arrows in green circles are alright, though).

    Thanks for your great tutorial.

  • SivaSankar

    Can anyone answer how to merge 2 arrays(both in Ascending order) and sort them in ascending order?

You must be logged in to post a comment.