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!
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.
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.
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:
There are just a few important things to remember about an array:
Review
Let’s just review those four points again:
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 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.
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.
Answer the following questions based on the array definitions provided.
numbers
integers
10
names
1200
String
double [ ] averages = new double [70];
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:
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”}
The following interactive will assess your understanding of how arrays are declared and initialized:
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:
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.
The source code above prompts the user to enter five doubles and reads each one into the subsequent array location.
The program above prompts the user to enter five strings and reads each one into the subsequent array location.
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.
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.
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.
d. The names Ahmid and Faye.
b. Sparrow
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]);
}
a. The values 4 and 2.
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]);
d. The values 9.0 and 4.5.
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:
The following flow chart outlines the design of the program above:
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.
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.
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]);
}
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:
Start by doing a top-down design and flow chart. Then you can start coding!
Make sure to include in your program:
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
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:
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.