How To

How to Initialize an Array

Contributor
By David Hamilton
eHow Contributing Writer
(2 Ratings)

Arrays are a central part of programming. You will use arrays of one type or another in nearly every program you create. One of the most common tasks you will have to perform when working with arrays is to internalize the array so that every element has a known starting point. While the exact details will vary slightly depending on your language of choice, the basic steps are always the same. The illustrations here are written in C# but could be applied to Java, Python or PHP with very little modification.

Difficulty: Easy
Instructions
  1. Step 1

    Define the array. Before you can do anything with it, you must first define an array. In a strongly typed language like C# or Java this means making decisions about both the size and the type of the array. In loosely typed languages such as PHP size is the only consideration. For this example, a simple array of Integers will work. int[] myBigArray=new int[5];Once compiled, this statement will create an array named myBigArray that can hold five integers.

  2. Step 2

    Determine the size of the array. Before you can initialize the array, you have to know how many elements you will be working with. In this example, determining the size of the array is easy. You can just glance at the source code. The size of the array was fixed at compile time. This is not always the case. Many times the size of an array will not be known until the user does something. How do you know how big the array is? Easy, you ask it. Int howBig=myBigArray.length;Running this code will cause the program to print “5.” It is a good idea to get in the habit of using the length property of an array even when you set the size originally. If you ever change the size of the array you will only need to make one change instead of many.

  3. Step 3

    Perform the array initialization. Now that you know the size of the array you can use a loop to access each element and give it a value. for (int x=0;x<myBigArray.Length;x++) { int value=x+1; //sets the value of int to 1 for the first loop myBigArray[x] = value; //use the array Console.WriteLine("Element {0} just got the vale {1}",x,value); //print }The output of this program is something along the lines of:Element 0 just got the Value 1Element 1 just got the Value 2Element 2 just got the Value 3Element 3 just got the Value 4Element 4 just got the Value 5

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Education
Kurt Schwengel,

Meet Kurt Schwengel eHow's Education Expert.

Get Free Education Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US

Demand Media
eHow_eHow Education