Recitation R11
- Java Arrays
Spring 2015
CS160: Foundations in Programming
The purpose of this lab is to:
- Introduce you to arrays.
- Practice the basics of arrays.
- Practice reading instructions carefully.
Introduction to Arrays
Your TA will introduce arrays and discuss:
- How to create arrays.
- How to find the length of an array.
- How to access elements in an array.
- How to modify elements in an array.
- How to print all the elements in an array using a loop.
- How to print all the elements in an array Arrays.toString().
- This recitation will be done in teams of two assigned by the TA.
- Each team will work on one computer, and you will switch who is typing midway.
- To submit, each person in the team will submit the same file.
Array Practice, Practice, and more Practice!
Do the following steps in order (and ask questions!):
- Create a new R11 project in Eclipse and an associated class.
- Put everything that follows into the main method except the methods arrayAverage and swapArray.
- Create a four element array of doubles called grades that contains the following numbers in this order: 81.2, 92.5, 48.9, 78.8
- Create a 6 element array of ints called numbers that contains the following numbers in this order: 12, 42, 33, 67, 92, 58
- Create a 9 element array of Strings called arguments without using an array initializer.
- Print the length of grades using length.
- Print the length of numbers using length.
- Print the length of arguments using length.
- Print the 4th element of grades.
- Print the 2nd element of grades.
- Print the 3rd element of numbers.
- Set the 1st element of numbers to be 99.
- Set the last element of grades to be 90.5
- Set the 7th element of arguments to be "HelloThere"
- Use a loop to print each element of grades on the same line, separated by commas (with a trailing comma)
- Use a loop to print each element of numbers on the same line, separated by spaces (with a trailing space)
- Use a loop to print each element of arguments on the same line, separated by an underscore (with a trailing underscore)
- Print the contents of grades using Arrays.toString(grades);
- Print the contents of numbers using Arrays.toString(numbers);
- Print the contents of arguments using Arrays.toString(arguments);
- FINAL STEP: Write a static method called arrayAverage that takes an array of doubles as a parameter
and returns the average as a double. Print the result of calling arrayAverage with the array grades
with exactly 3 digits after the decimal point.
Optional bonus:
- Write a static method called reverseArray that takes an array of doubles as a parameter and returns an array of doubles with the elements swapped. Print the result of calling reverseArray with the array grades. For example: {8.8, 1.1, 4.4, 2.2} would turn into {2.2, 4.4, 1.1, 8.8}
Submit your R11.java program to each partner's Checkin.
© 2015 CS160 Colorado State University. All Rights Reserved.