Simple algorithms on an array - compute sum and min.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Moving To Code 3 More on the Problem-Solving Process §The final step in the problem-solving process is to evaluate and modify (if necessary) the program.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
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)
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
Shorthand operators.
Chapter 1 Algorithm Analysis
CS1101: Programming Methodology Aaron Tan.
The character data type char
Data Structures and Algorithms Lecture 5 and 6 Instructor: Quratulain Date: 15 th and 18 th September, 2009 Faculty of Computer Science, IBA.
IT253: Computer Organization Lecture 4: Instruction Set Architecture Tonga Institute of Higher Education.
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.
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)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
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.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
What does a computer program look like: a general overview.
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.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSci 111 – computer Science I Fall 2014 Cynthia Zickos WRITING A SIMPLE PROGRAM IN JAVA.
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.
The life time of local variables (in a method). Local variables Local variable: A local variable is used to store information that is relevant for the.
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.
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 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.
Cumulative algorithms. 2 Adding many numbers How would you find the sum of all integers from ? // This may require a lot of typing int sum = 1 +
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.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
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.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Repetition-Counter control Loop
TK1114 Computer Programming
Building Java Programs
Writing Methods.
The Boolean (logical) data type boolean
Java Programming Arrays
Building Java Programs
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
Introduction to Java Brief history of Java Sample Java Program
Building Java Programs
Building Java Programs
The for-statement.
Building Java Programs
Presentation transcript:

Simple algorithms on an array - compute sum and min

Introduction In this webpage, we will apply the array "traversal" for- statement: (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] }

Introduction (cont.) to: compute the sum of the elements in an array. find the smallest (minimum) value among the elements in an array. find the index of the array element that contains the smallest (minimum) value among the elements in an array.

Introduction (cont.) Recall that: Make a note of this when we go through the examples ! A computer program (algorithm) must update some information while it examines every possible candidate solution, and The information that the computer program must maintain (update) is problem specific.

Note on the algorithms I will use the most basic for-statement in my examples. I will not take advantage of any specialized syntax to keep my example as general (applicable to other programming languages) as possible.

Computing the sum of the elements in an array Problem Description: We are given a series of numbers stored inside an array (say, array a):

Computing the sum of the elements in an array (cont.) We must compute the sum of all the values store in the array a I.e: compute:

Computing the sum of the elements in an array (cont.) Information that we must maintain: sum = the running sum of the array elements Before any array element has been added, the running sum = 0

Computing the sum of the elements in an array (cont.) When we process the array element a[i], we add the value a[i] to the running sum: (The black arrow represents the array index variable i)

Computing the sum of the elements in an array (cont.) Algorithm is Pseudo code: sum = 0.0; for all elements a[0], a[1], a[2],... of array a do { add a[i] to sum; } print sum

Computing the sum of the elements in an array (cont.) Java program: public class SumArray1 { 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; // array index double sum; // Running sum for ( i = 0 ; i < a.length ; i++ ) { sum = sum + a[i]; // Add a[i] to the running sum // Common error: sum = a[i] // This will store a[i] into sum } System.out.println( sum ); }

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

Note on the example programs: I use initialized array I used an initialized array in my examples to simplify the demo In real life, you may need to read in the value from the user. It's easy to change the program by adding an input segment before the summation algorithm.

Note on the example programs: I use initialized array (cont.) Example: import java.util.Scanner; public class SumArray2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; double[] a; System.out.print("How many numbers in input: "); n = in.nextInt(); // n = # values a = new double[n]; // Create an array of n elements int i; /* Read in the values */

Note on the example programs: I use initialized array (cont.) Example: for ( i = 0; i < a.length; i++ ) { System.out.print("Enter a number: "); a[i] = in.nextDouble(); // Read in number } /* Compute the sum */ double sum; sum = 0.0; for ( i = 0; i < a.length; i++ ) { sum = sum + a[i]; // Add a[i] to the running sum // Common error: sum = a[i] // This will store a[i] into sum } System.out.println( sum ); }

Note on the example programs: I use initialized array (cont.) The program section in red takes care of reading in the input data into the array a

Note on the example programs: I use initialized array (cont.) Example Program: (Demo above code) –Prog file: rogs/SumArray2.java How to run the program: Right click on link and save in a scratch directory To compile: javac SumArray2.java To run: java SumArray2

Find the minimum value in the elements of an array Problem Description: We are given a series of numbers stored inside an array (say, array a): We must find the minimum value of all the values store in the array a I.e: find: 1.2

Find the minimum value in the elements of an array (cont.) Information that we must maintain: min = the current minimum value found among the processed array elements

Find the minimum value in the elements of an array (cont.) Initial attempt to construct the find minimum algorithm: Before any array element has been examined, set min = 0 When we process the array element a[i], we change the minimum to a[i] IF: a[i] < min

Find the minimum value in the elements of an array (cont.) Examples: Example 1: In this example, the algorithm finds the correct minimum value

Find the minimum value in the elements of an array (cont.) Example 2: Observation: If the initial minimum value (0) is smaller than all the values in the array, the algorithm will find an incorrect minimum value

Find the minimum value in the elements of an array (cont.) How to correct the problem: Solution: We need to use a correct initial value Use a[0] as the initial minimum value Start comparing the array elements from a[1]

Find the minimum value in the elements of an array (cont.) Example:

Find the minimum value in the elements of an array (cont.) Algorithm is Pseudo code: min = a[0]; // Assume a[0] is the minimum for all elements a[1], a[2],... of array a do { if ( a[i] < min ) { min = a[i]; // We found a smaller minimum } print min;

Find the minimum value in the elements of an array (cont.) Java program: public class MinArray1 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 1.2, 7.8, 8.9 }; // 7 elements int i; // array index double min; // Current min value for ( i = 1 ; i < a.length ; i++ ) { if ( a[i] < min ) { min = a[i]; // Found a smaller min. value } System.out.println( min ); }

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

Find the index of the array element that contains the minimum value Problem Description: We are given a series of numbers stored inside an array (say, array a):

Find the index of the array element that contains the minimum value (cont.) We must find the index of the array element containing the minimum value of all the values store in the array a I.e: find: 2

Find the index of the array element that contains the minimum value (cont.) Information that we must maintain: min_i = the current index of the array element that contains the minimum value found among the processed array elements

Find the index of the array element that contains the minimum value (cont.) We can modify the previous algorithm for finding the minimum value to solve this problem. Modified solution: Use a[0] as the initial minimum value by setting min_i = 0 Start comparing the array elements from a[1] Update min_i when you find a smaller value

Find the index of the array element that contains the minimum value (cont.) Example:

Find the index of the array element that contains the minimum value (cont.) Algorithm is Pseudo code: min_i = 0; // Assume elem 0 (a[0]) is the minimum for all element a[1], a[2],... of array a do { if ( a[i] < a[min_i] ) { min_i = i; // We found a smaller minimum, update mn_i } print min_i;

Find the index of the array element that contains the minimum value (cont.) Java program: public class MinArray2 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 1.2, 7.8, 8.9 }; // 7 elements int i; // array index int min_i; // Current index with min value min_i = 0; // Assume a[0] is the current min. value for ( i = 1 ; i < a.length ; i++ ) { if ( a[i] < a[min_i] ) { min_i = i; // Found a smaller min. value, update min_i } System.out.println( min_i ); }

Find the index of the array element that contains the minimum value (cont.) Note: The variable min_i is an integer (In the previous program, the variable min is a double !)

Find the index of the array element that contains the minimum value (cont.) Example Program: (Demo above code) –Prog file: rogs/MinArray2.java How to run the program: Right click on link and save in a scratch directory To compile: javac MinArray2.java To run: java MinArray2

Efficiency considerations Real world computer programming: When you write real world computer applications that process a large amount of data, you need to pay some attention to the efficiency of the computer program.

Efficiency considerations (cont.) Fact on computers in 2011: One of the bottle necks (= the constraining component) of computers in 2011 is accessing RAM memory The CPU can execute instructions much faster than the memory can fetch them You want to write computer programs that uses less access operations to the RAM memory

Efficiency considerations (cont.) One of the areas where you can reduce RAM memory access operations is in array operations Facts: To access (= read or update) a simple variable (such as min), the computer needs to access the RAM memory once To access (= read or update) an array element (such as a[i]), the computer needs to access the RAM memory twice: The computer first need to access (= read) the variable i from RAM memory (Only after the computer obtained the value of the uses the variable i, it can find out the location of the variable a[i]) Then the computer need to access (= read or write) the variable a[i]

Efficiency considerations (cont.) Consider the previous Java program: public class MinArray2 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 1.2, 7.8, 8.9 }; // 7 elements int i; // array index int min_i; // Current index with min value min_i = 0; // Assume a[0] is the current min. value for ( i = 1 ; i < a.length ; i++ ) { if ( a[i] < a[min_i] ) // ****** Inefficient ****** { min_i = i; // Found a smaller min. value, update min_i } System.out.println( min_i ); }

Efficiency considerations (cont.) We can improve the efficiency by use a simple variable (min) to store a[min_i] and use that variable in the comparison: public class MinArray3 { public static void main(String[] args) { double[] a = { 2.3, 3.4, 4.5, 5.6, 1.2, 7.8, 8.9 }; // 7 elements int i; // array index int min_i; // Current index with min value double min; // min = a[min_i] for efficiency min_i = 0; // Assume a[0] is the current min. value min = a[0]; // For efficiency

Efficiency considerations (cont.) for ( i = 1 ; i < a.length ; i++ ) { if ( a[i] < min ) { min_i = i; // Found a smaller min. value, update min_i min = a[i]; // For efficiency } System.out.println( min_i ); }

Efficiency considerations (cont.) Note: We must make certain that the variable min contains the value a[min_i] all the time. How to achieve this: Whenever the variable min_i is updated, we must also update the variable min_i !

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