Array Initialization


Program Listing

ArrayInit.cpp

/************************************************************************
*                                                                       *
*   Program:    ArrayInit                                               *
*                                                                       *
************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Declare an uninitialized array of size 10

    int a[10];
    for (int i = 0; i < 10; i++)
        cout << "a[" << i << "] = " << a[i] << endl;
     
    cout << endl << "No. of bytes in a = " << sizeof(a) << endl;
    cout << "No. of bytes in an int = " << sizeof(a[0]) << endl;
    cout << "No. of ints in a = " << sizeof(a)/sizeof(a[0]) << endl << endl;

//  Declare and initialize array of size 10

    int b[10] = {2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
    for (int i = 0; i < 10; i++)
        cout << "b[" << i << "] = " << b[i] << endl;
     
    cout << endl << "No. of elements in b = " << sizeof(b)/sizeof(b[0]) << endl << endl;

//  Declare and initialize array of calculated size

    int c[] = {2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
    for (int i = 0; i < 10; i++)
        cout << "c[" << i << "] = " << c[i] << endl;
     
    cout << endl << "No. of elements in c = " << sizeof(c)/sizeof(c[0]) << endl << endl;

//  Declare and partially initialize an array of size 10

    int d[10] = {2, 4, 6};
    for (int i = 0; i < 10; i++)
        cout << "d[" << i << "] = " << d[i] << endl;
     
    cout << endl << "No. of elements in d = " << sizeof(d)/sizeof(d[0]) << endl;

    return 0;
}

Sample Run

a[0] = 63717832
a[1] = 0
a[2] = 63717872
a[3] = 478832
a[4] = 1
a[5] = 1
a[6] = 30754838
a[7] = 30233468
a[8] = 30233456
a[9] = 1761605440

No. of bytes in a = 40
No. of bytes in an int = 4
No. of ints in a = 10

b[0] = 2
b[1] = 4
b[2] = 6
b[3] = 8
b[4] = 10
b[5] = 9
b[6] = 7
b[7] = 5
b[8] = 3
b[9] = 1

No. of elements in b = 10

c[0] = 2
c[1] = 4
c[2] = 6
c[3] = 8
c[4] = 10
c[5] = 9
c[6] = 7
c[7] = 5
c[8] = 3
c[9] = 1

No. of elements in c = 10

d[0] = 2
d[1] = 4
d[2] = 6
d[3] = 0
d[4] = 0
d[5] = 0
d[6] = 0
d[7] = 0
d[8] = 0
d[9] = 0

No. of elements in d = 10



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:52 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/ArrayInit.html

Return to Coms 261 home page