תוכנה 1 תרגול מס ' 3 מערכים ומבני בקרה. 2 מערכים Array: A fixed-length data structure for storing multiple values of the same type Example: An array of.

Slides:



Advertisements
Similar presentations
§3 Dynamic Programming Use a table instead of recursion 1. Fibonacci Numbers: F(N) = F(N – 1) + F(N – 2) int Fib( int N ) { if ( N
Advertisements

CS324e - Elements of Graphics and Visualization A Little Java A Little Python.
1 More on Arrays and Loops Reading for this Lecture: –Section 5.4, , Break and Continue in Loops Arrays and For-each Loops Arrays and Loops.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Grouping Objects Arrays and for loops. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-Size Collections.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Java Syntax Primitive data types Operators Control statements.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
Java Unit 9: Arrays Declaring and Processing Arrays.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
1 Chapter 10 Various Topics User defined Types Enumerated Types Type Casting Syntactic Sugar Type Coercion.
Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 –HW3 is posted Questions?
Chapter 9: Advanced Array Concepts
The University of Texas – Pan American
Grouping Related Items
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Chapter 8: Arrays.
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.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
9. Types Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Data Types data type:a collection of.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
תוכנה 1 תרגול 2: מערכים, מבני בקרה ושגיאות הדס צור ואסף זריצקי.
Neal Stublen Computer Memory (Simplified)  Remember, all programming decisions came down to a true or false evaluation  Consider.
Types in Java 8 Primitive Types –byte, short, int, long –float, double –boolean –Char Also some Object types: e.g. “String” But only single items. What.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Java Part I By Wen Fei, HAO. Program Structure public class ClassName { public static void main(String[] args) { program statements } user defined methods.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
14 BirthMonth1February BirthMonth CE : Fundamental Programming Techniques.
תוכנה 1 תרגול 2: מערכים, לולאות והתמודדות עם שגיאות.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
Arrays, cont MONDAY – APRIL 6, Review from lab Deep vs Shallow copy array1array array2 = array1; What happens?
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 9.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Fixed-sized collections Introduction to arrays 6.0.
Chapter 9 Introduction to Arrays Fundamentals of Java.
13 Arrays CE : Fundamental Programming Techniques June 161.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
Jan 2016 Solar Lunar Data.
תרגול 2: מערכים, לולאות והתמודדות עם שגיאות
Java Arrays. Array Object An array :a container object holds a fixed number of values of a single type. The length of an array is established when the.
תרגול 2: מערכים, לולאות והתמודדות עם שגיאות
Unit 3 Test: Friday.
CS2011 Introduction to Programming I Arrays (I)
CS 180 Assignment 6 Arrays.
Single-Dimensional Arrays chapter6
QUIZ.
CSE 206 Course Review.
Introduction to java Part I By Shenglan Zhang.
Presentation transcript:

תוכנה 1 תרגול מס ' 3 מערכים ומבני בקרה

2 מערכים Array: A fixed-length data structure for storing multiple values of the same type Example: An array of odd numbers: odds.length == Indices (start from 0) The value of the element at index 4 is 9: odds[4] == 9 The type of all elements is int odds:

3 Array Declaration An array is denoted by the [] notation Examples: int[] odds; int odds[]; // legal but discouraged String[] names; int[][] matrix; // an array of arrays matrix: …

4 Array Creation and Initialization What is the output of the following code: int[] odds = new int[8]; for (int i = 0; i < odds.length; i++) { System.out.print(odds[i] + " "); odds[i] = 2 * i + 1; System.out.print(odds[i] + " "); } Output: Array creation: all elements get the default value for their type (0 for int)

5 Array Creation and Initialization Creating and initializing small arrays with a-priori known values: int[] odds = {1,3,5,7,9,11,13,15}; String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; … months: “Jan”

6 Loop through Arrays By promoting the array's index: for (int i = 0; i < months.length; i++) { System.out.println(months[i]); } foreach (since Java 5.0): for (String month: months) { System.out.println(month); } The variable month is assigned the next element in each iteration

Operations on arrays The class Arrays provide operations on array Copy Sort Search Fill... java.util.Arrays java.util.Arrays 7

8 Copying Arrays Assume: int[] array1 = {1,2,3}; int[] array2 = {8,7,6,5}; Naïve copy: array1 = array2; How would we copy an array? 1,2,38,7,6,5 array1array2

Copying Arrays Arrays.copyOf the original array the length of the copy Arrays.copyOfRange the original array initial index of the range to be copied, inclusive final index of the range to be copied, exclusive See also: System.arraycopy 9 int[] arr1 = {1, 2, 3}; int[] arr2 = Arrays.copyOf(arr1, arr1.length);

What is the output of the following code: int[] odds = {1, 3, 5, 7, 9, 11, 13, 15}; int[] newOdds = Arrays.copyOfRange(odds, 1, odds.length); for (int odd: newOdds) { System.out.print(odd + " "); } Output:

11 Other Manipulations on Arrays The java.util.Arrays class has methods for sorting and searching, assigning arrays e.g. java.util.Arrays public static void sort(int[] a) public static int binarySearch(int[] a, int key) public static void fill(long[] a, long val) More details in JDK 6.0 documentation

12 2D Arrays There are no 2D arrays in Java but … you can build array of arrays: char[][] board = new char[3][]; for (int i = 0; i < 3; i++) board[i] = new char[3]; board Or equivalently: char[][] board = new char[3][3];

13 2D Arrays Building a multiplication table: int[][] table = new int[10][10]; for (int i = 0 ;i < 10 ;i++) { for (int j = 0 ;j < 10; j++) { table[i][j] = (i+1) * (j+1); }

en.wikipedia.org/wiki/Fibonacci_number Fibonacci Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2)

סלט פיבונאצ'י

16 If-Else Statement public class Fibonacci { … /** Returns the n-th Fibonacci element */ public static int computeElement(int n) { if (n==0) return 1; else if (n==1) return 1; else return computeElement(n-1) + computeElement(n-2); } } Assumption: n≥0 Can be removed

17 Switch Statement public class Fibonacci { … /** Returns the n-th Fibonacci element */ public static int computeElement(int n) { switch(n) { case 0: return 1; case 1: return 1; default: return computeElement(n-1) + computeElement(n-2); } can be placed outside the switch Assumption: n≥0

18 Switch Statement public class Fibonacci { … /** Returns the n-th Fibonacci element */ public static int computeElement(int n) { switch(n) { case 0: return 1; case 1: return 1; break; default: return computeElement(n-1) + computeElement(n-2); } Compilation Error: Dead Code Assumption: n≥0

19 For Loop A loop instead of a recursion static int computeElement(int n) { if (n == 0 || n == 1) return 1; int prev = 1; int prevPrev = 1; int curr; for (int i = 2 ; i < n ; i++) { curr = prev + prevPrev; prevPrev = prev; prev = curr; } curr = prev + prevPrev; return curr; } Assumption: n≥0

20 נתונים במקום חישוב בתרגום רקורסיה ללולאה אנו משתמשים במשתני עזר לשמירת המצב curr, prev ו - prevPrev הלולאה "זוכרת" את הנקודה שבה אנו נמצאים בתהליך החישוב דיון: יעילות לעומת פשטות. עיקרון ה-KISS (keep it simple stupid) תרגיל: כתבו את השירות computeElement בעזרת prev ו - prevPrev בלבד (ללא curr)

21 For Loop Printing the first n elements: public class Fibonacci { public static int computeElement(int n) { … } public static void main(String[] args) { for(int i = 0 ; i < 10 ; i++) System.out.println(computeElement(i)); } It is better to use args[0]

22 מודולריות, שכפול קוד ויעילות יש כאן חוסר יעילות מסוים: לולאת ה - for חוזרת גם ב - main וגם ב- computeElement. לכאורה, במעבר אחד ניתן גם לחשב את האברים וגם להדפיס אותם כמו כן כדי לחשב איבר בסדרה איננו משתמשים בתוצאות שכבר חישבנו (של אברים קודמים) ומתחילים כל חישוב מתחילתו

23 מודולריות, שכפול קוד ויעילות מתודה (פונקציה) צריכה לעשות דבר אחד בדיוק! ערוב של חישוב והדפסה פוגע במודולריות (מדוע?) היזהרו משכפול קוד! קטע קוד דומה המופיע בשתי פונקציות שונות יגרום במוקדם או במאוחר לבאג בתוכנית (מדוע?) את בעיית היעילות (הוספת מנגנון memoization) אפשר לפתור בעזרת מערכים (תרגיל)

24 for vs. while The following two statements are almost equivalent: for(int i = 0 ; i < n ; i++) System.out.println(computeElement(i)); int i=0; while (i < n) { System.out.println(computeElement(i)); i++; } Variable i is not defined outside the for block

25 while vs. do while The following two statements are equivalent if and only if n>0 : int i=0; while (i < n) { System.out.println(computeElement(i)); i++; } int i=0; do { System.out.println(computeElement(i)); i++; } while (i>n(; works since n ≥ 1

26 שאלות ? הסוף... 26