Arrays Review Questions and Exercises

From CompSciWiki
Revision as of 10:16, 4 December 2007 by Alex (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Arrays


Introduction

This section has some review questions and exercise to help you review this section. Answers to these questions can be found here

   

{{{Body}}}

Review Questions

Question 1

What is it called when you access an element outside of the bounds of an array.

Example

    int i[] = new int[3];
    i[4] = 3;


Question 2

What is it called when a for-loop loops one iteration too many such that it passes the array's bounds.

Example:

    int j;
    int array[] = new int[3];
    for (j = 0; j <= 3; j++) {
        array[j] = 0;
    }


Question 3

Does the second statement of following code copy an array?


int array1[]={2,4}
int array2[]=array1;


Question 4

Does the following piece of code compare two arrays?

int array1[]={1,3,4}
int array2[]={1,3,4}

if(array1=array2)
  System.out.println("SAME ARRAY");
else
  System.out.println("NOT THE SAME");


Question 5

Does the following piece of code change the value of i to "Hey"?

    String i = "Hello";
    String array[] = new String [20];
    array[10] = i;
    array[10] = "Hey";


Question 6

What does the following piece of code print to the screen?

    String s = "Gello";
    String h[] = new String [20];

    h[10] = s;
    s = "Jello";
    System.out.println(h[10]);


Exercises

Exercise 1

Write a program that calculates the product of all the values in an array.


Exercise 2

Write a program that finds the position of the smallest value in an array.


Exercise 3

Write an program to create and populate an array.


Exercise 4

Write a program to copy the contents of one array into another.


Exercise 5

Create a function to sort an array of integers.


Exercise 6

Write a program to print all of the values in an array.

Exercise 7

Write a program that generates 100 random numbers from 1 to 12 and store it in an array named "randomNumbers". Create another array that can store 12 numbers. Call this second array "months". Iterate through the "randomNumbers" array and for every random number 1-12 that you find, increment the contents in the "months" array by 1. For example when you find a 1 in "randomNumbers" increment the value at position 0 in the array called "months". when you find a 6 in "randomNumbers" increment the value at position 5 in the array called "months". when you find a 12 in "randomNumbers" increment the value at position 11 in the array called "months".


Hints: The size of your first array should be 100. The size of the seciond array should be 12.