0% Complete
Minds on

MINDS ON

Imagine that you’ve been asked to write a program that needs to store 100 integers. How would you write that source code? Would you create 100 different variables each of type int? What if you then had to initialize all those variables to 0, and output their values to the screen?

If you declared and initialized 100 variables on the same line, and then output them to the console, you might get away with only needing 200 lines of code: 100 lines to declare and initialize the variables, and 100 lines to output the value of each variable to the screen. That would be a large program with a lot of repeated code!

This is an image of source code that implements 100 variables.

That would not be a fun program to write. Actually, you can see what the source code looks like here.

If you look at the program above, you’ll notice that quite a few lines of code are repeated. Most lines only differ from each other by one single number, which helps identify the variable.

Data Structures

Early on in the development of programming languages and computer science, developers realized that they needed to have a way that would allow programmers to organize information (like 100 variables) into structures that would make the data easy to store, process and output. That’s why data structures were developed!

A data structure in computer science is a specific way to organize information. Specific data structures include arrays, stacks, queues and linked lists. For this activity, you're going to look closely at the array data structure.

This is an image representing an array with six locations. The array is called values.
Action.

ACTION

The Array

Recall that a data structure allows a programmer to organize a large amount of data of the same type in a specific way, and to be able to store, process and output the data efficiently.

An array is one of the most popular data structures used in computer science, and it’s really just a column of data, like this:

This is an image of an array with six locations. The array is called values.

There are just a few important things to remember about an array:

arrays1

Long Description

 

Review

Let’s just review those four points again:

  • an array can only store data that is of the same type;
  • an array must have a name;
  • an array has a specific size; and
  • each cell in an array has an index starting from 0, that is a reference to the location of the item or element in the array.

Programming with Arrays

The following video will show you how to declare, initialize and manipulate arrays and their data. After watching the video, you will break down the components so that you can see how each one works on its own.  For now, it will be good to see the big picture.

 

Declaring Arrays

Declaring an array is done a little differently than when you are declaring a variable, but you still need to provide a name and the type of data you’re going to store.

This is an image of the source code that declares an array called values of size 6.

The above code creates an array called values that is ready to hold 6 integers. Notice that the array indexes go from 0 to 5.

This is an image of an array called values with six locations.

 

This is the question/answer icon. Questions

Answer the following questions based on the array definitions provided.

  1. int [ ] numbers = new int [10];

    Considering the array definition above, what is the name of the array?
    Answer

    numbers

 

  1. int [ ] numbers = new int [10];

    Considering the array definition above, what type of data will the array hold?
    Answer

    integers

 
  1. int [ ] numbers = new int [10];

    Considering the array definition above, how many values will the array be able to hold?
    Answer

    10

 

  1. String [ ] names = new String [1200];

    Considering the array definition above, what is the name of the array?
    Answer

    names

 

  1. String [ ] names = new String [1200];

    Considering the array definition above, how many Strings can the array hold?
    Answer

    1200

 

  1. String [ ] names = new String [1200];

    Considering the array definition above, what type of data will the array hold?
    Answer

    String

 

  1. What would the source code look like that would declare an array called averages that would hold 70 double values?
    Answer

    double [ ] averages = new double [70];

 

Initializing Arrays

After an array has been declared and space for it has been allocated, there are several ways to initialize its contents. One way is to use simple assignment statements:

This is an image of the source code required to declare and initialize an array.

Did You Know?

There is a quick trick that some programmers use to declare and initialize an array on one line.

In the example above, the array is called values; it is initialized to hold the following 6 integers: 3, 34, 88, 54, 276, 21.

A programmer could declare and initialize this array with the following line of code:

int [ ] values = {3, 34, 88, 54, 276, 21};

A programmer could also declare and initialize a string or a double array in one line of code as well:

double [ ] avg = {34.7, 54.3, 87.9, 12.8, 87.9, 23.2, 65.4, 32.3};

or

String [ ] cities = {“London”, “Sudbury”, “Ottawa”, “Sarnia”, "Sault Ste. Marie”}

Review

The following interactive will assess your understanding of how arrays are declared and initialized:

arrays2

Long Description

 

Outputting Array Values

It’s quite easy and straightforward to output array values to the screen if you are using the output console. It’s just important that you are aware of which array element you would like to output.

Just remember: You can’t output an entire array using one output statement. You can only output one value at a time.

The following program declares the values array, initializes all of the values, then outputs the values to the screen:

This is an image of the source code required to declare and initialize an array and then output the contents.

Storing User Entered Values into an Array

This is an image of source code that declares an array of integers and then reads in the values from a keyboard.

The source code above prompts the user to enter five integers and reads each one into the subsequent array location.

Just be sure to use the correct array index so that the values are being stored in the correct spot in the array.

This is an image of source code that declares an array of doubles and then reads in the values from a keyboard.

The source code above prompts the user to enter five doubles and reads each one into the subsequent array location.

This is an image of source code that declares an array of strings and then reads in the values from a keyboard.

The program above prompts the user to enter five strings and reads each one into the subsequent array location.

Elements, Indexes and Bounds

As you work more and more with arrays, it’s important for you to understand and use proper terminology. It can be quite confusing discussing program design or writing comments on your code if you aren’t sure how to reference the different parts of the array.

Element: An array element is the actual piece of information stored in an array cell.

Index: An array index is the location or index value of where an element is located.

This is an image of an array with array index, array name and array element all labeled.

Bounds: The bounds of an array are it’s highest and lowest indexes. The lower bounds of an array is always 0, and the upper bounds is always one less than the size of the array.

This is important, so let’s say that again:

The upper bounds of an array is always one value less than the size of the array.

Therefore if an array is of size 5, then the bounds or indexes are from 0 to 4. If an array is of size 900, then the bounds or indexes are from 0 to 899.

Review

Complete the following review questions to assess your understanding of arrays.

Learning About Learning

Before beginning each question, it might be a good idea to get some paper and a pencil or pen.


You can draw out the arrays and the variables as boxes and fill them in as you proceed through each line of code. These types of activities that involve tracing through code will help you tremendously as you learn more complex concepts in the course. Also, being able to sit with a finished program and read through each component will provide you with the skills necessary to tackle larger projects.
 

This is the question/answer icon. Questions

  1. Consider the following code:

    String [ ] names = new String [4];

    int num1 = 9;
    num1 = num1 - 7;

    names [0] = "Kim";
    names [2] = "Faye";
    names [1] = "Ahmid";
    names [3] = "Tony";

    System.out.println (names[1]);
    System.out.println (names[num1]);


    What would be ouputted to the screen after the code has been executed?
     
    1. The names Tony and Ahmid.
    2. The names Kim and Faye.
    3. The names Faye and Ahmid.
    4. The names Ahmid and Faye.
    Answer

    d. The names Ahmid and Faye.

 
  1. Consider the following code:

    String [ ] birds = new String [4];

    int val = 2;

    birds [0] = "Hawk";
    birds [2] = "Eagle";
    birds [1] = "Sparrow";
    birds [3] = "Duck";

    if (val > 2)
        {System.out.println (birds[val]);}
    else
       {System.out.println (birds[val-1]);}


    What would be ouputted to the screen after the code has been executed?
    1. Hawk
    2. Sparrow
    3. Duck
    4. Eagle and Sparrow
    Answer

    b. Sparrow

 
  1. Consider the following code:

    int [ ] values = new int [4];

    int number = 2;

    values [1] = number;
    values [0] = number + number;
    values [3] = number * 3;
    values [2] = number - 1;

    if (values[1] < number)
    {
        System.out.println(values[2]);
        System.out.println(values[3]);
    }
    else
    {
        System.out.println(values[0]);
        System.out.println(values[1]);
    }

    What would be ouputted to the screen after the code has been executed?
    1. The values 4 and 2.
    2. The values 1 and 2.
    3. The values 3 and 4.
    4. The values 2 and 4.
    Answer

    a. The values 4 and 2.

 
  1. Consider the following code:

    double [ ] averages = new double [3];

    double num;

    averages [2] = 4.5;
    averages [1] = averages[2] + averages[2];
    averages [0] = averages[1] + averages[1];

    num = averages[0] - averages[1];

    System.out.println(num);
    System.out.println(averages[2]);

    What would be ouputted to the screen after the code has been executed?
    1. The values 9.0 and 5.5.
    2. The values 5.5 and 18.0.
    3. The values 18.0 and 9.0.
    4. The values 9.0 and 4.5.
    Answer

    d. The values 9.0 and 4.5.


The Power of For Loops and Arrays

For loops and arrays make a perfect pair, because often, when dealing with arrays, there are several lines of code that are very similar.

When you look at the following program, for example, the input and output of array elements could be made much more efficient by using for loops:

Without For Loops

This is an image of a source code that declares an array of five integers, initializes the array from the keyboard input, then outputs the values entered.

With For Loops

This is an image of source code that declares an array of five integers, initializes the array from the keyboard, then outputs the values to the screen. This time a for loop is used.

The following flow chart outlines the design of the program above:

This is an image of a flowchart that presents the for loop as a method to fill and output the values of an array.

 

One major advantage of using for loops with arrays is that there are fewer lines of code. This means that it takes less time to write the program, and there are fewer lines to debug.

There is another advantage as well: Imagine that you wanted to change that program above so that the program reads in 50 integers.

This is the dropbox icon. Remixing For Loop and Array Programs

Before you start creating programs entirely on your own with for loops and arrays, it might be a good idea to create some programs using pre-written code.

Your task is to copy and paste the following programs into a new Netbeans project. You will then alter the program as indicated, comment all lines of code in the program, and then submit each one. Some programs may also ask you to add lines of code that have not been written yet. Good luck!

1. The following program prompts the user to enter 10 values. The program stores the values in an array, then adds all of the values up and outputs the total:

        Scanner keyedInput = new Scanner (System.in);
        
        int [ ] numbers = new int [10];
        int total = 0;
        
        System.out.println("Enter ten integers and they will be added together:");
        for (int i = 0; i <= 9; i = i + 1)
        {
           numbers[i] = keyedInput.nextInt();
        }
        

        for (int i = 0; i <= 9; i = i + 1)
        {
             total = total + numbers[i];
        }
        
        System.out.println("The sum of those numbers is:");
        System.out.println(total);

Alter the program so that the user can enter 20 values, and then add those 20 values to provide the sum of those numbers. 

2. The following program prompts the user to enter the names of 10 friends. The program then outputs the fourth and seventh name to the screen.

        Scanner keyedInput = new Scanner (System.in);
        
        String [ ] friends = new String [10];
        
        System.out.println("Enter the names of ten friends:");
        for (int i = 0; i <= 9; i = i + 1)
        {
            friends[i] = keyedInput.nextLine();
        }
        
        System.out.println("The fourth and seventh names listed were:");
        System.out.println("Fourth: " + friends[3]);
        System.out.println("Seventh: " + friends[6]);  

Alter the program so that it asks the user to enter the names of five friends, and then outputs the names of the second, third and fourth friend entered. 

3. The following program declares an array with five values already initialized. The program then calculates the average of the values and outputs it to the screen.

        Scanner keyedInput = new Scanner (System.in);
        
        double [ ] marks = {34.7, 54.1, 34.8, 99.6, 43.6, 43.2};
        double total=0;
        double average;
        
        System.out.println("These are the marks:");
        for (int i = 0; i<=5; i= i + 1)
        {
           System.out.println(marks[i]);
        }
        
        for (int i = 0; i<=5; i= i + 1)
        {
            total = total + marks[i];
        }
        
        average = total/6;
        
        average = average * 10;
        average = Math.round(average);
        average = average/10;
        
        System.out.println("The average mark is:");
        System.out.println(average);

Alter the program so that the following marks are added to the list: 65.8, 44.8, 88.6.

The program should then output a new, corrected average. 

 

 

Consolidation

CONSOLIDATION

In the beginning of this activity we discussed how a program with 100 variables might be difficult to write without using arrays.

Now that you know about arrays, and now that you know about how for loops work so well with arrays, you can imagine how a programmer might write that program quickly, using only five lines of code.

        int [ ] nums = new int [100];
        
        for (int i = 0; i<= 99; i = i + 1)
        {
           nums[i] = 0;
        }
        
        for (int i = 0; i<= 99; i = i + 1)
        {
           System.out.println(nums[i]);
        }

 
 

This is the dropbox icon. Show What You Know

Your task is to create a program that uses arrays and loops together to do a task.

Rather than being told exactly what your program should do, you now have an opportunity to plan, develop and submit a program of your choosing.

Here is a list of possible programs you might choose to develop:

  • Ask the user to enter his or her last 5 assignment marks and tell them the average.
  • Ask the user to enter his or her favourite hockey/baseball/sports star statistics for the past 5 games and tell them the average.
  • Create a program that will create an array of 10 random values between 1 and 100, display it to the user and tell the user the max and min values.
  • Create a program that will create an array of 10 random math/science/etc. questions, AND a second array of the 10 random answers that correspond to each question. The program should then ask the user 10 random questions.

Start by doing a top-down design and flow chart. Then you can start coding!

Make sure to include in your program:

  • variables
  • at least one constant
  • loops
  • arrays

To complete your program, you might also have to incorporate the other concepts you have learned in this course, such as selection (if ... then ... else or switch statements) and nested if ... then ... else statements.

You must also ensure that

  • you complete and submit a flow chart for your program.
  • your source code includes commenting.
  • your program includes a user-friendly interface.

Being given so much freedom and choice is a great thing, but it also might be a bit of a challenge for you to come up with ideas.

The following list is meant as “creative fodder”. These are ideas, words and concepts that might help you think of what type of program you would like to create:

  • Sports statistics
  • Random number games
  • Interesting math equations
  • Populations of countries
  • Computer specifications
  • Statistics about animals
  • Dice games
  • Guess that animal games
  • Distance, speed, acceleration calculator
  • Multiple choice quizzes

Also, before you decide on your project idea, consider some of the assignments that you have already completed. You have created projects related to a wide variety of topics., so maybe you would like to expand on some of those ideas.

 
 

 

 
test text.