Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Similar documents
Arrays. Here is the generic syntax for an array declaration:

Controls Structure for Repetition

Passing Array to Methods

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

H212 Introduction to Software Systems Honors

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

First Java Program - Output to the Screen

Functions. Arash Rafiey. September 26, 2017

Last Class. More on loops break continue A bit on arrays

Example: Computing prime numbers

Arrays. Eng. Mohammed Abdualal

Some Sample AP Computer Science A Questions - Solutions

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

CompSci 125 Lecture 11

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

CSE 1223: Exam II Autumn 2016

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Oct Decision Structures cont d

CS 101 Spring 2007 Midterm 2 Name: ID:

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

BM214E Object Oriented Programming Lecture 4

STUDENT LESSON A12 Iterations

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Data dependent execution order data dependent control flow

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

I. True/False: (2 points each)

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Fundamentals of Programming Data Types & Methods

ECE 122. Engineering Problem Solving with Java

Example Program. public class ComputeArea {

Building Java Programs

More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COP 3330 Final Exam Review

Building Java Programs

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

CS111: PROGRAMMING LANGUAGE II

CS 211: Methods, Memory, Equality

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Array. Array Declaration:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Example: Monte Carlo Simulation 1

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Loops. CSE 114, Computer Science 1 Stony Brook University

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Computer Science is...

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Final Exam. COMP Summer I June 26, points

Programming with Java

CS111: PROGRAMMING LANGUAGE II

Midterm Examination (MTA)

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Object Oriented Programming. Java-Lecture 6 - Arrays

COMP 202. Java in one week

Last Class. While loops Infinite loops Loop counters Iterations

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

PROGRAMMING FUNDAMENTALS

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Esc101 Mid Semester Exam - II

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CS 112 Introduction to Programming

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

Building Java Programs

CS Week 5. Jim Williams, PhD

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

H212 Introduction to Software Systems Honors

I. True/False: (2 points each)

Arrays. Fundamentals of Computer Science

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 9 Introduction to Arrays. Fundamentals of Java

Use of the ArrayList class

CS 102/107 - Introduction to Programming Midterm Exam #2 - Prof. Reed Spring 2011

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Full file at

COMP 202 Java in one week

Methods and Functions

CS 101 Exam 2 Spring Id Name

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

Building Java Programs

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Chapter 3. Selections

Question: Total Points: Score:

1 Short Answer (10 Points Each)

Chapter 7 User-Defined Methods. Chapter Objectives

Chapter 4: Control Structures I

Arrays. Loops + arrays: challenge problem. Arrays (II) An array is a set of variables of the same type accessed by their index.

CS 302: Introduction to Programming in Java. Lecture 9

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Transcription:

Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the same type. (In essence declaring an array allows you to use many variables of the same type without explicitly declaring all of them.) You can picture an array like below: 0 1 2 3 4 5 6 7 8 9 Each cell of the array can hold one data item. Furthermore, each cell has its own index, to distinguish it from the rest of the cells. In Java, these cells are always numbered from 0 to the size of the array minus one. The array above is indexed from 0-9 and has size 10, since it can hold 10 elements. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; The above line of code will declare an array called numbers, which will hold integer values. Its size is still undefined at this point. Since an array isn't a primitive, technically, numbers is just a reference. At the current time, no SPACE in the computer's memory has been allocated to store a set of integers. The next step is to allocate this space. In order to do this, we need to know how much space we want to allocate. If we wanted to allocate space for 10 variables, we would do the following: numbers = new int[10]; Once we've done this, the picture looks like the following: ---numbers v 0 1 2 3 4 5 6 7 8 9

To refer to a variable in a single cell or element of an array, you use the name of the array, followed by a bracket, the index you want to access, and then another bracket. Thus, numbers[0] = 3; would set the int variable in the 0 index of the numbers array to 3. ---numbers v 0 1 2 3 4 5 6 7 8 9 3 A sample program The following program will read in five test scores and then print these out in reverse order: public static void main(string[] args) { Scanner stdin = new Scanner(System.in); int index; int[] test_scores = new int[5]; // Read in scores into the array. System.out.println("Please enter 5 test scores."); for (index=0; index < 5; index++) test_scores[index] = stdin.nextint(); // Print them out by going through the array in backwards. printf("here are the scores in reverse order: "); for (index=4; index >= 0; index--) System.out.print(test_scores[index]+" "); System.out.println();

Common mistakes made with arrays 1. Out of Bounds error: This is when you index into an array with an invalid index. For example, if you declare a test_scores of size 5 and tried to access test_scores[5] or test_scores[-1], you would be trying to access a variable that does not exist, since the valid indices of test_scores range from 0 through 4. Often times, these errors are masked by the fact that the index to an array in an algorithm can be a complex expression. It is difficult to tell whether a particular expression will equal an invalid index at some point during the execution of the algorithm. 2. Not initializing all values of an array. 3. Trying to assign an entire array a value such as: test_scores = 7; This will not assign 7 to each element of the array test-scores. In fact, it is not syntactically correct. This is because the left-hand side is not an integer variable, while the right hand side is an integer expression. 4. Not differentiating between an array index and the value stored in an array at a particular index. (We will talk about this more as we see sample algorithms.)

What s relatively simple about arrays? Once you understand the difference between an array, array element, and an index to an array, it is fairly simple to follow array code and to write syntactically correct code dealing with arrays. What is difficult about arrays? The actual manipulation of array elements and indeces can get quite tricky. Let s look at an example, similar to the one we just did. Let s say you are given an array named numbers, indexed from 0 to 99. You are to reverse the contents of the array. It looks like this solution might work: int index, temp; int[] numbers = new int[100]; //...Fill in values for numbers for (index=0; index<100; index++) { temp = numbers[index]; numbers[index] = numbers[99 index]; numbers[99 index] = temp; But, it does not. What happens here? You end up reversing the list twice, so by the end of the loop, you ve got the array in the exact order that you started.

Finally, we realize that we need to go through half of the list instead of the whole list, while we are swapping numbers. So, here an algorithm that correctly reverses the values in the array: for (index=0; index<99/2; index++) { temp = numbers[index]; numbers[index] = numbers[99 index]; numbers[99 index] = temp;

Technically, an array is a reference. int[] numbers; Passing an array as a paramenter numbers is a reference to the spot in memory where the beginning of the array is stored. Since this is the case, whenever we pass an array into a function it works like a reference variable. Here is a method prototype with an array as a formal parameter: public static void print(int[] board); What this means is that the function print CAN change the values in the array (the actual parameter) that is passed to it. Consider the following function: public static void initialize(int[] numbers, int value) { for (int i=0;i < numbers.length; i++) numbers[i] = value; What does this function do? One other thing to note is that given an array, in Java we can always access the length of it. The variable length is like a public instance variable for all arrays. Though this seems silly, it can be very helpful at times. Searching for a value in an array One of the most common subroutines performed on an array is a search for a particular value. Let s look at a straightforward method for doing this, using a function: public static boolean Find(int[] numbers, int val) { int index; for (index=0; index < numbers.length; index++) { if (numbers[index] == val) return true; return false; Upon completion, the function will return either a true or false value, depending on whether or not the target value was found.let's trace through an example, where we call this function from main as follows:

public static void main(string[] args) { int i; int[] num = new int[10]; Scanner stdin = new Scanner(System.in); for (i=0;i<10;i++) { System.out.println("Enter the next number."); num[i] = stdin.nextint(); if (Find(num, 3) == 1) System.out.println ("You entered the number 3."); else System.out.println ("You did not enter the number 3."); return 0;

Character Counting Example Consider the following task: Given an input of characters, count the frequencies of each alphabetic character, and print all of these out. First, I will write a program without methods that completes this task. Then, I will show an improved design of this program with static methods. Finally, I will show an objectoriented design of this program that uses a Frequency object. Here are some of the issues we'll have to discuss: 1) How to create 26 different counters using an array. 2) How update the proper counter once a letter is read in. 3) How to print out all the values of the counters in a reasonable manner. Here are quick answers to these questions: 1) Use an array of size 26, and initialize each element to 0. 2) First we can test to see if the character is a letter. If so, we must determine how to find its corresponding value from 0 to 25. (Hint: Use the idea given in the last lecture!) 3) We can loop through each index (0 to 25) into the array, and for each one, print out the corresponding letter and value stored in the array at that index. public static void main(string[] args) { int index; char c; int[] freq = new int[26]; Scanner stdin = new Scanner(System.in); for (index = 0; index<26; index++) freq[index] = 0; String inp = stdin.nextline(); for (index=0; index<inp.length(); index++) { c = inp[index]; if (c >= 'A' && c <= 'Z') freq[c-'a']++; else if (c >= 'a' && c <= 'z') freq[c-'a']++;

System.out.println("Letter\tFrequency\n"); for (index = 0; index<26; index++) System.out.println((char)('a'+index)+"\t"+freq[index]);

public static void main(string[] args) { int index; int[] freq = new int[26]; Scanner stdin = new Scanner(System.in); init(freq, 0); String inp = stdin.nextline(); count(freq, inp); printchart(freq); public static void init(int[] arr, int val) { for (int i=0; i<arr.length; i++) arr[i] = val; public static void count(int[] arr, String inp) { for (index=0; index<inp.length(); index++) { char c = inp.charat(index); if (c >= 'A' && c <= 'Z') arr[c-'a']++; else if (c >= 'a' && c <= 'z') arr[c-'a']++; public static void printchart(int[] arr) { System.out.println("Letter\tFrequency\n"); for (int index = 0; index<26; index++) System.out.println((char)('a'+index)+"\t"+freq[index]);

public class Frequency { private int[] arr; public static void main(string[] args) { int index; char c; Frequency fobj = new Frequency(); Scanner stdin = new Scanner(System.in); fobj.init(0); String inp = stdin.nextline(); fobj.count(inp); fobj.printchart(); public Frequency() { arr = new int[26]; public void init(int val) { for (int i=0; i<arr.length; i++) arr[i] = val; public void count(string inp) { for (index=0; index<inp.length(); index++) { char c = inp.charat(index); if (c >= 'A' && c <= 'Z') arr[c-'a']++; else if (c >= 'a' && c <= 'z') arr[c-'a']++; public void printchart() { System.out.println("Letter\tFrequency\n"); for (int index = 0; index<26; index++) System.out.println((char)('a'+index)+"\t"+freq[index]);