Arrays
click here for complete presentation on arrays Declaration of an Array type[] name;To declare an array of a specified type with a given name: type[] name;> int[] list; // declaration> list = new int[10]; // instantiation Data types are String, int, double, boolean, char, Student, Employee or any object etc.. Example making an array with initial values(data type)[] variable name = {data values}; int[] nums = {34,32,34,56} Example making an array with no values(data type)[] variable name = new (data type) [length of array]; int[] nums = new int[10]; Put data into Arraysvariable [index value] = some input; nums[0] = 50;
Going through each element of an array forwardPrints all the elements of the array for (int i=0; i < nums.length; i++) //output: 50, 0, 0, 0, 10….etc //array processing goes here
System.out.println(nums[i]);
}
Prints all the elements of the array backwardsfor (int i=0; i < nums.length; i++) //output: 0, 10, 0,0,0,10 etc.. System.out.println(nums[i]);
}
Adding 1 to each element in the arrayfor (int i=0; i < nums.length; i++) nums[i]++;
}
Use Scanner to put values into an arrayString[] sInputs = new String[10]; for (int i=0; i < sInputs.length; i++) System.out.println(“Enter in a String”);
}
sInputs[i] = scan.nextLine(); Printing all the even numbers in the arrayfor (int i=0; i < sInputs.length; i++) if (nums[i] % 2 ==0)
}
System.out.println(nums[i]); Summing up all the numbers in the arrayint sum=0; sum=sum + nums[i];
}
Setting one array element equal to another array element assuming num.length = num2.lengthint [] num2 = {3,4,5,6,400)   nums[i] = num2[i];
}
|
Scanner ClassCredit: A Slides are modified with permission from Barry Wittman at Elizabethtown College |
|||||||||||||||||||||||