3-12 arrays

3-12 arrays - A[i]=1 Before you start programs with...

This preview shows pages 1–2. Sign up to view the full content.

Computer Science 3/12/08: Arrays Name(int A) 0 1 2 3 4 How to make an array: int[ ] A=new int[100]; largest cell would be 99 (because 0 is a cell) indexes are always int, and always start with zero Put something in a cell: A[2]=3; Therefore, the value for cell 2 is 3. A[3+2]=54; Therefore, the value for cell 5 is 54. Removing something from a cell: int number=A[5]; An array of floats: float [ ]A=new int[100]; A[2]=(float)3.0; An array of doubles: double [ ] A= new int[100]; A[2]=3.0; A[3+2]=54.0; double number=A[5]; Making a table: Int [ ] [ ] A=new int [rows][columns]; A[1][1]=7; inserts a seven into the second row of the second column A[2][4]=7; Higher dimension arrays: Int [ ][ ][ ]=new int [ ][ ][ ]; (3-d) Int [ ][ ][ ][ ]=new int[ ][ ][ ][ ]; (4-d) You can go as high as you want Ex. Build an array with 100 elements that has a number 1 in every cell int [ ]A=new int [100]; for (int i=0; i<a.length; i++){

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: A[i]=1; } Before you start programs with arrays…always set the values in the array to 0 or whatever you need. Good idea: public static final DIM=100; int[ ]A=new int[DIM]; Ex. Build an array with 100 elements that has even numbers in every cell int [ ]A=new int [100]; for (int i=0; i<a.length;i++){ A[i]=i*2+2; } Ex. Build an array with 100 elements that has the square of the index in every other cell int [ ]A=new int [100]; for (int i=0; i<a.length; i=i+2){ A[i]=i*i; } If you have two arrays and want to copy one array to the other, the one you are copying to has to be the same size or bigger. Ex. Copy what is in array A and put it in array B int [ ]B=new int [DIM]; int [ ]A=new int [DIM]; for (int i=0; i<A.length; i++){ if (i%2==0) A[i]=i*i; } for (int i=0;i<A.length; i++){ B[i]=A[i]; }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

3-12 arrays - A[i]=1 Before you start programs with...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online