In: Computer Science
Java programming language:
1. Create a new Netbeans project called ArrayLoop.
2. Declare a fixed length array of integers which can store 8 elements. Do not assign any values.
int[] myAddresses = new int[8];
3. Create a statement which raises 2 to the power of your loop counter, then subtracts 1, and assigns that value to the corresponding element. For example, when i = 3, 2 to the third power is 8, minus 1 = 7. When i = 4, 2 to the fourth power is 16, minus 1 = 15. Etc etc for all values of i.
Fill up the entire array with these values.
4. Use Array.toString to print out the entire Array to the console.
5. Create another FOR loop which counts from 8 down to 1.
6. Use the counter values as indexes to print out your Array values in REVERSE order, from largest to smallest.
7. Create a String object which stores your last name. Mine would be myName = "Hughes";
8. Use the .length field to find the number of char's in your name. Use that value in a new FOR loop. This loop will print out the letters of your name one at a time. For example, my output should be:
H
u
g
h
e
s
TIP: Watch out for the 'Off by one' error.
9. SCREENSHOT AND PRINT all source code in Notepad++.
a. MARK AND LABEL the line which defines a FOR loop
b. MARK AND LABEL the line which declares your integer Array.
c. MARK AND LABEL the line which stores your computed values in the Array.
d. MARK AND LABEL the line which prints out an entire Array at once.
e. MARK AND LABEL a line which uses a loop counter as an Array index.
f. MARK AND LABEL a line which finds the length of your name.
SCREENSHOT AND PRINT all outputs.
/*
* Java test program that demonstrates the given java
statements in the below java class program.
* */
//ArrayLoop.java
import java.util.Arrays;
public class ArrayLoop
{
public static void main(String[] args)
{
/*Create an array of
integer type of size,8*/
int[] myAddresses = new
int[8];
/*Loop over the array
,myAddresses that
* stores the valuse of 2 to
raise to power of i
* at the index, i value of
myAddresses*/
for (int i = 0; i <
myAddresses.length; i++)
{
myAddresses[i]=(int) Math.pow(2.0, i);
}
System.out.println("Arrays.toString() to print the myAddresses
array");
//print the myAddresses
using Arrays.toString method
System.out.println(Arrays.toString(myAddresses));
System.out.println("printing the
myAddresses in REVERSE order");
//print the myAddresses to
the console in reverse order
for (int i =
myAddresses.length-1;i>=0; i--)
{
System.out.print(myAddresses[i]+" ");
}
String myName = "Hughes";
//print the size of the
myName string object
System.out.println("Length of the
myName is "+myName.length());
System.out.println("Printing the
values in myName string ");
System.out.println("each character
one on a line");
//print the myName letters
each letter one at time
for (int i = 0; i <
myName.length(); i++)
{
System.out.println(myName.charAt(i));
}
}
}
Sample Output: