Sunday, February 22, 2015

CSE Arrays

On February 19, 2015 in Computer Science Engineering my teacher taught the class about Arrays. An Array is essentially a list of data which will contain a certain length of variables. Since the first element in an array is [0] if you want an Array that contains a length of 10 the array should read array[9]. Below is the notes my class took on Arrays.


// arrays!!!
// declare an integer array
// datatype[] name;
int[] array;

// create the array
// name = new datatype[size];
array = new int[10];

// or you can declare and create
int[] array2 = new int[10];

// assign random ints to array
// this loop starts at 0 and runs until we've reached array.length (100)
for(int i = 0; i < array.length; i++){
 // since random() returns a float, we can
 // cast it to an int
 array[i] = (int)random(101);
}

// assign random ints to array
// this loop starts at 0 and runs until we've reached array.length (100)
for(int i = 0; i < array2.length; i++){
 // since random() returns a float, we can
 // cast it to an int
 array2[i] = (int)random(101);
}

// let's check - print out the elements of array
println(array);

print(array);
print("\n"); // print new line
// "\t" <- tab
// "\"" <- "
// "\'" <- '
// "\\" <- \

// double each value stored in array and store it back into array
for(int i = 0; i < array.length; i++){
 array[i] *= 2; // array[i] = array[i] * 2;
}

// print out the elements of array
for(int i = 0; i < array.length; i++){
 println("[" + i + "] " + array[i]);
}

// count how many even numbers are in array2
int numEvens = 0;
for(int i = 0; i < array2.length; i++){
 if(array2[i] % 2 == 0){
   numEvens++;
 }
}

println(array2);
println(numEvens);

// copy everything from array into array2
for(int i = 0; i < min(array.length, array2.length); i++){
 array2[i] = array[i];
}

print(array + " " + array2 + "\n");

boolean isEqual = true;
// int numEqual = 0;
for(int i = 0; i < array.length; i++){
 if(array[i] == array2[i]){
   // numEqual++;
 }
 else{
   isEqual = false;
 }
}

println(array == array2);
// println(numEqual == array.length);
println(isEqual);