TK1114 - 5(a) array 1D.pdf - 5(a Array 1D TK1114 COMPUTER...

This preview shows page 1 - 10 out of 28 pages.

5 (a) - Array 1D TK1114 COMPUTER PROGRAMMING
Introduction An array is used to store a collection of data , but it is often more useful to think of an array as a collection of variables of the same type . Instead of declaring individual variables , such as int number1, number2, number3, number4, number5; number1 number2 number3 number4 number5
Introduction int[] numbers; [0] [1] [2] [3] [4] numbers we can declare one array variable such as
Declaring Array variables To use an array, we must declare a variable to reference the array and specify the type of array the variable can reference. The syntax for declaring an array variable: datatype[] arrayVar; Example: double[] numbers;
Creating Arrays After an array variable is declared, we can create an array by using the new operator with the following syntax: arrayVar = new dataType[arraySize]; The above statement does two things: (1) it creates an array using new dataType[arraySize] (2) it assigns the reference of the newly created array to the variable arrayVar . ;
Declare&Creating Arrays However, declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement: dataType[] arrayVar; arrayVar = new dataType[arraySize]; or dataType[] arrayVar = new dataType[arraySize]; Example: double[] numbers = new double[10]; This statement declares an array variable, numbers , creates an array of ten elements of double type, and assigns its reference to numbers .
.
Array Size and Default Values When declare an array, we must specify the size of the array. The size of an array cannot be changed after the array is created. Size can be obtained using arrayVar.length . When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.
Assigning values To assign values to the elements, use the syntax: arrayVar[index] = value; Example: numbers[0] 5.6 numbers[1] 4.3 numbers[2] 2.2 numbers[3] 3.1 numbers[4] 2.2 numbers[5] 8.1

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture