Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

M3-Lesson 4 - One-Dimensional Array

Dimension Lesson

Uploaded by

cababatvicente
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

M3-Lesson 4 - One-Dimensional Array

Dimension Lesson

Uploaded by

cababatvicente
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ITE 2 – Computer Programming 1 (Module 3)

Learning Plan

Lesson No: 4

Lesson Title: One-dimensional array

Let’s Hit These:


At the end of this lesson, students should be able to:
 describe why arrays are necessary in programming.
 declare array reference variables and create arrays.
 obtain array size using arrayRefVar.length and know default values in an array.
 access array elements using indexes .
 declare, create, and initialize an array using an array initializer.
 program common array operations (displaying arrays, summing all elements,
finding the minimum and maximum elements, random shuffling, and shifting
elements).
 simplify programming using the for each loops.

Let’s Get Started:

Problem: Suppose you want to compute the average temperature for the seven days in a
week. You might use the following code:
Scanner keyboard = new Scanner(System.in);
System.out.println(“Enter 7 temperature:”);
double sum = 0;
for (int count = 0; count < 7; count++)
{
double next = keyboard.nextDouble();
sum = sum + next;
}
double average = sum / 7;

This works fine if all you want to know is the average. But let’s say you also want to know
which temperatures are above and which are below the average. Now you have a problem in order
to compute the average, you must read the seven temperatures, and you must compute the average
before comparing each temperature to it. Thus, to be able to compare each temperature to the
average, you must remember the seven temperatures. How can you do this? The obvious answer
is to use seven variables of the type of double. This is a bit awkward, because seven is a lot of
variables to declare, and in other situations, the problem can be even worse. Imagine doing the
same thing for each day of the year instead of just each day of the week. Writing 365 variable
declarations would be absurd. Arrays provide us with an elegant way to declare a collection of
related variables. An array is a collection of items of the same type. It is something like a list of
variables, but it handles the naming of the variables in a nice, compact way.

Filename: ArrayOfTemperatures.java
ITE 2 – Computer Programming 1 (Module 3)

Let’s Find Out:


ITE 2 – Computer Programming 1 (Module 3)
ITE 2 – Computer Programming 1 (Module 3)
ITE 2 – Computer Programming 1 (Module 3)

Let’s Read:
{Place here text or readings as an input)

Array Basics
Once an array is created, its size is fixed. An array reference variable is used to access the elements
in an array using an index.

An array is used to store a collection of data, but often we find it more useful to think of an array
as a collection of variables of the same type. Instead of declaring individual variables, such as
number0, number1, . . . , and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], . . . , and numbers[99] to represent individual variables. This section
introduces how to declare array variables, create arrays, and process arrays using indexes.

Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array and specify
the array’s element type. Here is the syntax for declaring an array variable:

elementType[] arrayRefVar;

The elementType can be any data type, and all elements in the array will have the same data type.
For example, the following code declares a variable myList that references an array of double
elements.

double[] myList;

Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array. It creates only a storage location for the reference
to an array. If a variable does not contain a reference to an array, the value of the variable is null.
You cannot assign elements to an array unless it has already been created. After
array variable is declared, you can create an array by using the new operator and assign its
reference to the variable with the following syntax:

arrayRefVar = new elementType[arraySize];

This statement does two things:


(1) it creates an array using new elementType[arraySize];
(2) it assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement as:

elementType[] arrayRefVar = new elementType[arraySize];

or

elementType arrayRefVar[] = new elementType[arraySize];


ITE 2 – Computer Programming 1 (Module 3)

Here is an example of such a statement:

double[] myList = new double[10];

This statement declares an array variable, myList, creates an array of ten elements of double type,
and assigns its reference to myList. To assign values to the elements, use the syntax:

arrayRefVar[index] = value;
ITE 2 – Computer Programming 1 (Module 3)

Array Size and Default Values


When space for an array is allocated, the array size must be given, specifying the number of
elements that can be stored in it. The size of an array cannot be changed after the array is created.
Size can be obtained using arrayRefVar.length. For example, myList.length is 10. When an array
is created, its elements are assigned the default value of 0 for the numeric primitive data types,
\u0000 for char types, and false for boolean types.

Accessing Array Elements


The array elements are accessed through the index. Array indices are 0 based; that is, they range
from 0 to arrayRefVar.length-1. In the example in Figure 7.1, myList holds ten double values,
and the indices are from 0 to 9.
Each element in the array is represented using the following syntax, known as an indexed
variable:

arrayRefVar[index];

For example, myList[9] represents the last element in the array myList.

An indexed variable can be used in the same way as a regular variable. For example, the
following code adds the values in myList[0] and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
The following loop assigns 0 to myList[0], 1 to myList[1], . . . , and 9 to myList[9]:
for (int i = 0; i < myList.length; i++) {
myList[i] = i;
}

Array Initializers
Java has a shorthand notation, known as the array initializer, which combines the declaration,
creation, and initialization of an array in one statement using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example, the statement

double[] myList = {1.9, 2.9, 3.4, 3.5};

declares, creates, and initializes the array myList with four elements, which is equivalent to
the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Processing Arrays
When processing array elements, you will often use a for loop—for two reasons:
■ All of the elements in an array are of the same type. They are evenly processed in the
same fashion repeatedly using a loop.
■ Since the size of the array is known, it is natural to use a for loop.
ITE 2 – Computer Programming 1 (Module 3)

Assume the array is created as follows:


double[] myList = new double[10];

The following are some examples of processing arrays.

1. Initializing arrays with input values: The following loop initializes the array myList
with user input values.
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
2. Initializing arrays with random values: The following loop initializes the array myList
with random values between 0.0 and 100.0, but less than 100.0.
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
}
3. Displaying arrays: To print an array, you have to print each element in the array using a
loop like the following:
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}

Tip
For an array of the char[] type, it can be printed using one print statement. For example,
the following code displays Dallas:
char[] city = {'D', 'a', 'l', 'l', 'a', 's'};
System.out.println(city);
4. Summing all elements: Use a variable named total to store the sum. Initially total is 0. Add each
element in the array to total using a loop like this:

double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
5. Finding the largest element: Use a variable named max to store the largest element.
Initially max is myList[0]. To find the largest element in the array myList, compare each element
with max, and update max if the element is greater than max.
double max = myList[0];

for (int i = 1; i < myList.length; i++) {


if (myList[i] > max) max = myList[i];
}
6. Finding the smallest index of the largest element: Often you need to locate the largest element
in an array. If an array has multiple elements with the same largest value, find the smallest index
of such an element. Suppose the array myList is {1, 5, 3, 4, 5, 5}. The largest element is 5 and the
ITE 2 – Computer Programming 1 (Module 3)

smallest index for 5 is 1. Use a variable named max to store the largest element and a variable
named indexOfMax to denote the index of the largest element. Initially max is myList[0], and
indexOfMax is 0. Compare each element in myList with max, and update max and indexOfMax
if the element is greater than max.
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
}

For each Loops


Java supports a convenient for loop, known as a foreach loop, which enables you to traverse the
array sequentially without using an index variable. For example, the following code displays
all the elements in the array myList:
for (double e: myList) {
System.out.println(e);
ITE 2 – Computer Programming 1 (Module 3)

You can read the code as “for each element e in myList, do the following.” Note that the
variable, e, must be declared as the same type as the elements in myList.
In general, the syntax for a foreach loop is
for (elementType element: arrayRefVar) {
// Process the element
}
You still have to use an index variable if you wish to traverse the array in a different order or
change the elements in the array.

Let’s Remember:
{Place here summary of the lessons}
1. A variable is declared as an array type using the syntax elementType[] arrayRefVar or
elementType arrayRefVar[]. The style elementType[] arrayRefVar is preferred, although
elementType arrayRefVar[] is legal.
2. Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array. An array variable is not a primitive data type
variable. An array variable contains a reference to an array.
3. You cannot assign elements to an array unless it has already been created. You can create an
array by using the new operator with the following syntax: new elementType[arraySize].
4. Each element in the array is represented using the syntax arrayRefVar[index]. An index must
be an integer or an integer expression.
5. After an array is created, its size becomes permanent and can be obtained using
arrayRefVar.length. Since the index of an array always begins with 0, the last index is always
arrayRefVar.length - 1. An out-of-bounds error will occur if you attempt to reference elements
beyond the bounds of an array.
6. Programmers often mistakenly reference the first element in an array with index 1, but it should
be 0. This is called the index off-by-one error.
7. When an array is created, its elements are assigned the default value of 0 for the numeric
primitive data types, \u0000 for char types, and false for boolean types.
8. Java has a shorthand notation, known as the array initializer, which combines declaring an
array, creating an array, and initializing an array in one statement, using the syntax elementType[]
arrayRefVar = {value0, value1, ..., valuek}.

Let’s Do This:

Problem: Write a program using arrays to solve the problem: to read 100 numbers, get the
average of these numbers, and find the number of the items greater than the average. To be flexible
for handling any number of input, we will let the user enter the number of input, rather than fixing
it to 100.

Filename: AnalyzeNumbers.java
ITE 2 – Computer Programming 1 (Module 3)

Let’s Check: {Answer Key}

Suggested Readings:
{Place here title of books/articles/links for the readings of the students}

Book:
 Joyce Farell, Java Programming 9th Edition, © 2019, 2016, 2014, 2012 Cengage Learning,
Inc
ITE 2 – Computer Programming 1 (Module 3)

Module Post Test:


Problem 1.
Write a java program that uses one-dimensional array, the program will accept the
compilation exercises of students and compute & display the average of the exercises.

Filename: one-array.java

Problem 2.
For the Final Project. Write a java program language that will execute and compile all
programming exercises on this module. You can use case statement for the options (selection) or
you can use function or method (procedure) with nested if statement for the options (selection).
Below are the format or sample.
Final Project
in
ITE 2 – Computer Programming 1

COMPILATION OF PROGRAMMING ACTIVITIES

Programmer: <Write your complete name, yr/sec>


1sem 2020.ver_1
Filename: Lastname-Final.java
===============================================
My Computer Programming Activities
===============================================
Menu:
Activity 1: Welcome1.java
Activity 2: Sum.java
Activity 3: info1.java
Activity … :
Activity … :
Activity … :
Activity … :
Activity … :
Activity … :

Activity to last number:


Exit 50: (Exit menu)
===============================================
Select your Option from the Menu to Open [ 1 ]
===============================================
Option 1 is selected

Then, run the Welcome1.java

Note:
If Welcome1.java will close it system will go back to main menu and
choose option again, until you select exit to close the program.
(Write this activity in one program only)

Filename: Lastname-Final.java

You might also like