Java:
1. Define an array object variable:
Example: double[] a;
2. Create the array:
Example: a = new double[10];
|
|
DataType varName [ constantSize ] ; |
double a[10]; // Define an array of 10 variables of type double int b[20]; // Define an array of 20 variables of type int |
|
Explanation:
|
int main( int argc, char* argv[] )
{
double a[10];
int i;
for ( i = 0; i < 10; i++ )
a[i] = i;
for ( i = 0; i < 10; i++ )
printf( "a[%d] = %lf\n", i, a[i] );
}
|
Output:
a[0] = 0.000000 a[1] = 1.000000 a[2] = 2.000000 a[3] = 3.000000 a[4] = 4.000000 a[5] = 5.000000 a[6] = 6.000000 a[7] = 7.000000 a[8] = 8.000000 a[9] = 9.000000 |
How to run the program:
|
|
|
|
int main( int argc, char* argv[] )
{
double a[10];
printf(" a = %u\n", a); // Print array name
printf(" &a[0] = %u\n", &a[0]); // Print address of first elem.
}
|
Output:
a = 4290768640
&a[0] = 4290768640 (EQUAL !)
|
How to run the program:
|
|
|
|
|
| Java | C |
|---|---|
|
|
|
|
public class array2
{
public static void main( String[] args )
{
double[] a = new double[10];
int i;
for ( i = 0; i < 10; i++ )
a[i] = i;
for ( i = 0; i < 30; i++ )
System.out.println( "a[" + i + "] = " + a[i] );
}
}
|
Result:
a[0] = 0.0 a[1] = 1.0 a[2] = 2.0 a[3] = 3.0 a[4] = 4.0 a[5] = 5.0 a[6] = 6.0 a[7] = 7.0 a[8] = 8.0 a[9] = 9.0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at array2.main(array2.java:14) |
How to run the program:
|
int main( int argc, char* argv[] )
{
double a[10];
int i;
for ( i = 0; i < 10; i++ )
a[i] = i;
for ( i = 0; i < 30; i++ )
printf( "a[%d] = %lf\n", i, a[i] );
}
|
Sample output:
a[0] = 0.000000 a[1] = 1.000000 a[2] = 2.000000 a[3] = 3.000000 a[4] = 4.000000 a[5] = 5.000000 a[6] = 6.000000 a[7] = 7.000000 a[8] = 8.000000 a[9] = 9.000000 a[10] = 0.000000 a[11] = 0.000000 a[12] = 0.000000 ... a[22] = -2243494719485605301116825811.... ... |
How to run the program:
|
|
These index out of bound checks takes up CPU cycles (uses the CPU)
|
We say that:
|