Code About Us Tutorial


  Arrays
    What is an Array?
    Array Elements
    Filling an Array
    Initializing An Array
    Multidimensional Arrays


   
 

Home > Arrays > Initializing An Array

November 27, 2009 9:59 am

   

Initializing An Array

Let us now consider how to initialize an array. An array can be initialized with a single initializer list, for example:

 

 
#include <iostream.h>

int main() { double a[5] = {40.50, 30.3, 30.6, 11.3, 0.5}; // ß initializer list

cout<<"Here is the array:" << endl; for(int i = 0; i < 5; i++) { cout <<"a[" << i << "]" << a[i] << "n"; } return 0; }

In this program, an initializer list, which consists of 5 numbers; this automatically fills the array with the numbers typed in the initializer list. A for loop is used to access and print the numbers entered in the array. Braces and commas must always be used to separate the different numbers.

In this next example 2 arrays are created, one which used the array-size in the [] and used the initalizer list as above, and in the 2nd array the array-size is excluded and just the initalizer list used, as will be seen, they both produce the exact same output.

 

 
#include <iostream.h>

int main() { int i; int a[5] = {23, 40, 27, 36, 90};

cout<<"Here is the array, when i included the arraysize[5]:" << endl; for(i = 0; i < 5; i++) { cout <<"a[" << i << "]" << a[i] << "n"; }

int b[] = {23, 40, 27, 36, 90}; //left out the array-size cout <<"Here is the array, when i excluded the arraysize[]: " << endl; for(i = 0; i < 5; i++) { cout <<"b[" << i << "]" << b[i] << "n"; } return 0; }

In a case the array-size is set to 6, and only 3 elements are typed in the initializer list, then the other three that are not assigned any value will automatically be set to 0. One thing to be avoided is creating an array with no initializer list, and then writing a program that accesses the array and prints the values. It will generate odd numbers and may even crash the program. Please Rate this Code:


    Comments for: Initializing An Array
Annonymouse User says:
Hi,

Thanks for the good advice. However, how do you initialize a multi-dimensional array?

I.e.

Is it like this? array[2][2] = { {2,5}, {3,3} }

Thanks, Neil

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Yes, Thats exactly how!!




Add Comment:
Name:
Email:


 «372» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.