4 – Arrays Answers

1) Print out the elements of the following array: int [] numbers = {1,2,3,4,5};

int [] numbers = {1,2,3,4,5};
for (int i = 0; i < numbers.length; i++)
{
    System.out.println(numbers[i]);
}
// OR for(int element : numbers) { System.out.println(element); }

2) Declare and initialize a String array containing the days of the week. Print out a random day.

String [] days = {  "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday",  "Sunday" };
int random = (int)(Math.random()*days.length);
System.out.println(days[random]);

3) Output the sum of the elements in this array int [] values = {3,5,4,7,2,3};

int [] values = {3,5,4,7,2,3};
int sum =0;
for(int i = 0; i < values.length; i++)
{
    sum+=values[i];
}
System.out.println(sum);
//OR if you have Java 8...
sum = IntStream.of(values).sum();
System.out.println(sum);

4) Output the average of the elements in this array int [] values = {3,4,5,6};

int [] values = {3,4,5,6};
int sum =0;
for(int i = 0; i < values.length; i++)
{
    sum+=values[i];
}
System.out.println((double)sum/(values.length));
//OR if you have Java 8...
double average = IntStream.of(values).average().getAsDouble();
System.out.println(average);

5) Declare an int array of length 5. Use a for loop to prompt for 5 numbers and enter them into the array. Print out the array.

int [] numbers = new int[5];
Scanner scan = new Scanner(System.in);
for (int i = 0; i<numbers.length;i++)
{
    System.out.println("Enter a number");
    int n = scan.nextInt();
    numbers [i] = n;
}
System.out.println("... and your numbers are... ");
for (int i =0; i<numbers.length; i++)
{
    System.out.println(numbers[i]);
}

6) Declare an int array of length 4. Use a for loop to prompt for 4 numbers and enter them into the array. Print out the average of the four numbers

int [] numbers = new int[4];
Scanner scan = new Scanner(System.in);
for (int i = 0; i<numbers.length;i++)
{
    System.out.println("Enter a number");
    int n = scan.nextInt();
    numbers [i] = n;
}
int sum =0;
for (int i =0; i<numbers.length; i++)
{
    sum += numbers[i];
}
System.out.println("Average: " + (double)sum/numbers.length);

7) The following code will convert a String s to an array of characters c. Print out the characters: String s = “This is a string”; char [] c = s.toCharArray();

String s = "This is a string";
char [] c = s.toCharArray();
for(char e: c)
{
    System.out.print(e+",");
}
System.out.println("");

8) Use what you learned in the last question to count the number of times the letter e occurs in the String “I never saw a purple cow”

String s = "I never saw a purple cow";
char [] c = s.toCharArray();
int count = 0;
for(char e: c)
{
    if (e == 'e') count++;
}
System.out.println("Number of e's: "+ count);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.