Working with arrays (we will use an array of double as example)

Slides:



Advertisements
Similar presentations
Write a program step by step. Step 1: Problem definition. Given the coordinate of two points in 2-D space, compute and print their straight distance.
Advertisements

Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
How to Create a Java program CS115 Fall George Koutsogiannakis.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Writing Methods. Create the method Methods, like functions, do something They contain the code that performs the job Methods have two parts.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
Introduction to Methods
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Shorthand operators.
Laboratory Study October, The very first example, traditional "Hello World!" program: public class first { public static void main (String[ ]
The character data type char
Copyright 2009 by Pearson Education Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos: Ch.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
© 2012 Pearson Education, Inc. All rights reserved. 1-1 Why Java? Needed program portability – Program written in a language that would run on various.
Parameter passing mechanism: pass-by-value. Introduction In the last webpage, we discussed how to pass information to a method I have kept it (deliberately)
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
Mixing integer and floating point numbers in an arithmetic operation.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
© 2012 Pearson Education, Inc. All rights reserved types of Java programs Application – Stand-alone program (run without a web browser) – Relaxed.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Generics. Writing typed checked generic code There are many instances where the type of the object is irrelevant : –The construction of data structures.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
The need for Programming Languages
Writing Methods.
Building Java Programs Chapter 7
An Introduction to Java – Part I, language basics
The Boolean (logical) data type boolean
Arrays .
Suggested self-checks:
The for-statement.
Presentation transcript:

Working with arrays (we will use an array of double as example)

Accessing the elements in an array Suppose we have created an array of 5 double variables:

Accessing the elements in an array (cont.) The elements of the array are identified by the following variable names:

Accessing the elements in an array (cont.) Explanation: The first array element is accessed through the variable name a[0] The second array element is accessed through the variable name a[1] And so on.

Accessing the elements in an array (cont.) Note: The numbers 0, 1, 2,... used to access array elements is called an (array) index The indices of the array elements (in Java) start with 0 Consequently, if an array has n elements, the index of the last element is n − 1

Array index and array length The array index: Array index = an integer value that is used to access an array element You can use any integer expression as array index !

Array index and array length (cont.) Example: a[1] // Accesses a[1] int i; i = 1; a[i] // Accesses a[1]

Array index and array length (cont.) int i; i = 2; a[i] // Accesses a[2] int i; i = 2; a[2*i] // Accesses a[4]

Array index and array length (cont.) The array length: Each array variable in Java stores the length of the array To access the length (information) of the array a, use the expression: a.length

Array index and array length (cont.) Example: public class Length { public static void main(String[] args) { double[] a = new double[5]; // Define an array of 5 elements double[] b = new double[10]; // Define an array of 10 elements System.out.println( a.length ); // Prints 5 System.out.println( b.length ); // Prints 10 }

Array index and array length (cont.) Example Program: (Demo above code) –Prog file: rogs/Length.java How to run the program: Right click on link and save in a scratch directory To compile: javac Length.java To run: java Length

Example: printing all elements in an array Consider the following for-loop: public class Print1 { public static void main(String[] args) { int i; int n = 5; for ( i = 0; i < n; i++ ) { System.out.println( i ); }

Example: printing all elements in an array (cont.) Output:

Example: printing all elements in an array (cont.) Within the body of the for-loop, the variable i takes on all indices of an array of length n !!! We can use this for-loop to print all elements in an array

Example: printing all elements in an array (cont.) Consider the following program: public class Print2 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements int i; System.out.println( "# elements in array: " + a.length ); System.out.println( ); System.out.println( "The array elements are:" ); for ( i = 0; i < a.length; i++ ) { System.out.println( a[i] ); }

Example: printing all elements in an array (cont.) Output of this program: # elements in array: 7 The array elements are:

Example: printing all elements in an array (cont.) Example Program: (Demo above code) –Prog file: rogs/Print2.java How to run the program: Right click on link and save in a scratch directory To compile: javac Print2.java To run: java Print2

A basic problem solving technique in Computer Science: brute force search Unlike humans who are intelligent but slow, in contrast, computers are dumb and fast... Consequently, humans and computer will solve a problem differently Humans will often discover patterns and and device shortcuts Computers on the other hand, often will try every possible answer to find the correct answer

A basic problem solving technique in Computer Science: brute force search (cont.) A commonly used technique to solve problems (perform tasks) with a computer is: The Brute Force Search technique: Brute force search Check every instance of all possible solutions For each instance, perform the desired task (e.g., determine if it is the best solution) on that instance.

A basic problem solving technique in Computer Science: brute force search (cont.) Warning: This is but one half of the technique, The other half is maintaining the correct information.

A basic problem solving technique in Computer Science: brute force search (cont.) Information, information, information: In order to perform the desired task (e.g., determine if it is the best solution), we need information Fact: A computer program (algorithm) will update some information while it examines every possible candidate solution

A basic problem solving technique in Computer Science: brute force search (cont.) The information that the computer program must maintain is problem specific. Through experience in writing computer programs, you will develop the skills to design the necessary information

The brute force search in an array The following for-loop can be used to examine every element in an array: The variable i is used as array index. (a is some array (any type) ) int i; for ( i = 0; i < a.length; i++ ) { // statements in the for-loop body will be // executed ONCE for each array element a[i] }

Special syntax in Java to define indexing variables in for-statements The for-statement is used so often, that Java has extended its syntax to allow you to define the array index variable inside the for-statement as follows: The reason for this special allowance to avoid Murphy's law (i.e.: what can go wrong, will) (a is some array (any type) ) for ( int i = 0; i < a.length; i++ ) { // statements in the for-loop body will be // executed ONCE for each array element a[i] }

Special syntax in Java to define indexing variables in for-statements (cont.) The life time and scope of a variable that is defined inside a for-statement is the for-statement itself: The index variable i can only be used inside the for- statement. The for-statement is "self-contained".

Special syntax in Java to define indexing variables in for-statements (cont.) Example: public class Print3 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements System.out.println( "# elements in array: " + a.length ); System.out.println( ); System.out.println( "The array elements are:" ); // System.out.println( i ); // Will cause an error: i undefined for ( int i = 0; i < a.length; i++ ) { System.out.println( a[i] ); } // System.out.println( i ); // Will cause an error: i undefined }

Special syntax in Java to define indexing variables in for-statements (cont.) Example Program: (Demo above code) –Prog file: rogs/Print3.java How to run the program: Right click on link and save in a scratch directory To compile: javac Print3.java To run: java Print3

Special syntax in Java to define indexing variables in for-statements (cont.) Note: If you uncomment the statement before or after the for-statement that uses the variable i, and re-compile, you will get an error message This error message shows you that the variable i only exists within the for-statement

A specialized for-statement for accessing all elements in an array Making array processing easier to program in Java goes even further (The designers of Java keep adding to the Java language)... A later version of the Java programming language introduced a specialized for-statement for array processing.

A specialized for-statement for accessing all elements in an array (cont.) Syntax of the specialize for-statement for array processing: for ( elementType varName : arrayRefVar ) { // statements in the for-loop body will be // executed ONCE for each array element "arratRefVar[i]" // which is represented by the variable name "varName" }

A specialized for-statement for accessing all elements in an array (cont.) Example: public class Print4 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 }; // 7 elements System.out.println( "# elements in array: " + a.length ); System.out.println( ); System.out.println( "The array elements are:" ); for ( double x : a ) { System.out.println( x ); // print all a[i] in array a }

A specialized for-statement for accessing all elements in an array (cont.) Example Program: (Demo above code) –Prog file: rogs/Print4.java How to run the program: Right click on link and save in a scratch directory To compile: javac Print4.java To run: java Print4

A specialized for-statement for accessing all elements in an array (cont.) Output: (same as Print2.java) # elements in array: 7 The array elements are: