Arrays, Type Casting and Constants Engineering 1D04, Teaching Session 5.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
Arrays & Strings part 2 More sophisticated algorithms, including sorting.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
Arrays Chapter 8 page /24/07CS150 Introduction to Computer Science 1 Arrays (8.1)  One variable that can store a group of values of the same.
Arrays.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Arrays Code: Arrays Controls: Control Arrays, PictureBox, Timer.
Records Engineering 1D04, Teaching Session 11. © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng1 Records  So far we've seen a number of different.
Java Data Types Assignment and Simple Arithmetic.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
Computers, Variables and Types Engineering 1D04, Teaching Session 2.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Objects and Classes Continued Engineering 1D04, Teaching Session 10.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Arrays Version 1.1. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Objects and Classes Engineering 1D04, Teaching Session 9.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
CHAPTER EIGHT ARRAYS © Prepared By: Razif Razali1.
Computer Programming for Engineers
Comments, Conditional Statements Continued, and Loops Engineering 1D04, Teaching Session 4.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
int [] scores = new int [10];
Programming Fundamentals. Today’s Lecture Array Fundamentals Arrays as Class Member Data Arrays of Objects C-Strings The Standard C++ string Class.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
1 float Data Type Data type that can hold numbers with decimal values – e.g. 3.14, 98.6 Floats can be used to represent many values: –Money (but see warning.
Chapter VII: Arrays.
Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Two Dimensional Arrays and Complex Conditions
Arrays, Part 1 of 2 Topics Definition of a Data Structure
One-Dimensional Array Introduction Lesson xx
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
Suggested self-checks: Section 7.11 #1-11
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

Arrays, Type Casting and Constants Engineering 1D04, Teaching Session 5

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng1 High Score System  We want to produce a program to keep track of the high scores in a video game.  The top ten scores and the names of the players must be recorded in order.  We must have a mechanism for inserting a new score and a mechanism for displaying the current scores.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng2 High Score System  Following the ideas from the ticket system example, write a high score system that allows the names and scores of the top ten players to be saved.  Provide a method to add a new score and a method to print the current high scores.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng3 remember: Ticket Example public partial class Form1 : Form { public Form1() { InitializeComponent(); } int ticket; void reset() { ticket = 0; } int getTicket() { ticket = ticket+1; return ticket; } Plan a high score system …

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng4 int player1score, player2score, player3score,...;... add_score(){ if (score > player10score){ if (score > player9score){ ow... } High Score System  Not so easy... maybe it looked something like this

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng5  Aren’t computers supposed to make it easier to deal with large amounts of similar information? print_scores () {... "score1: " + player1score + "score2: " + player2score + "score3: " + player3score +... } High Score System

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng6  Arrays are a method of storing a number of similar items in a way that is easy to access.  As an example, let us see how we could find the sum of a number of integers. Introduction to Arrays

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng7  Consider the following numbers: 59, 100, 26, 35  (This would form an array x, with elements x 0, x 1, x 2, x 3 and each element must be the same type of number.)  Once we have named them like this how do we add them? Introduction to Arrays We can name those numbers: x 0 x 1 x 2 x 3

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng8  Consider the following numbers: 59, 100, 26, 35  Once we have named them like this how do we add them? s = 0 for i = 0,1,2,3 s = s + x i Introduction to Arrays We can name those numbers: x 0 x 1 x 2 x 3

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng9  Consider the following numbers: 59, 100, 26, 35  Once we have named them like this how do we add them? s = 0 for i = 0,1,2,3 s = s + x i Introduction to Arrays We can name those numbers: x 0 x 1 x 2 x 3 s = 0; for (i=0; i<=3; i++) { s = s+x[i]; }

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng10  Consider the following numbers: 59, 100, 26, 35  Once we have named them like this how do we add them? s = 0 for i = 0,1,2,3 s = s + x i Introduction to Arrays We can name those numbers: x 0 x 1 x 2 x 3 s = 0; for (i=0; i<=3; i++) { s = s+x[i]; } index in square brackets

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng11 Introduction to Arrays int [] x = {59, 100, 26, 35}; int i, s; double ave; s = 0; for (i=0; i<=3; i++) { s = s+x[i]; } We can declare an array with values for each element in the array The elements in the array are automatically numbered, starting from 0 Indicates the variable is an array

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng12 Introduction to Arrays int [] x = {59, 100, 26, 35}; int i, s; double ave; s = 0; for (i=0; i<=3; i++) { s = s+x[i]; } do we really have to count the elements in the array?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng13 Introduction to Arrays int [] x = {59, 100, 26, 35}; int i, s; double ave; s = 0; for (i = 0; i < x.Length; i++) { s = s+x[i]; } do we really have to count the elements in the array? No

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng14 Introduction to Arrays  How do we declare the array if we are not initializing the values in the array? int [] x = new int[10]; we will discuss “new” in some detail later maximum elements in the array remember the index number starts from 0 what do you think x.Length returns now?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng15 Introduction to Arrays  How do we declare the array if we are not initializing the values in the array? int [] x = new int[10]; we will discuss “new” in some detail later maximum elements in the array remember the index number starts from 0 what do you think x.Length returns now? 10 = the max number of elements in x

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng16  Arrays are a method of storing a number of similar items in a way that is easy to access.  Accessing an item in the array is easy - just put its index number in the square brackets. int [] score = new int[10]; string [] name = new string[10]; score[5] = 1000; name[43] = "alan"; recap: Arrays

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng17  You can also use an integer variable to access a specific element in an array.  Using a variable to select an element from an array is very useful when combined with loops. int [] score = new int[10]; int i = 5; score[i] = 1000; recap: Arrays

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng18 double b=25, c=30, d=60, e=10, sum, average; int numTerms = 4; sum = b; sum = sum + c; sum = sum + d; sum = sum + e; average = sum / numTerms; recap: Arrays  Recall an example from an earlier session: Take a few minutes now to do this using an array instead of b,c,d and e. In other words, use an array called terms instead of b,c,d,e.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng19 double [] terms = {25.0, 30.0, 60.0, 10.0}; double sum, average; int i; sum = 0.0; for (i = 0; i < terms.Length; i++) sum = sum + terms[i]; average = sum / terms.Length; recap: Arrays  Using an array (each element is a double) is this okay if we want an answer that is a double? make sure you understand why this is not <=

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng20 double [] terms = {25.0, 30.0, 60.0, 10.0}; double sum, average; int i; sum = 0.0; for (i = 0; i < terms.Length; i++) sum = sum + terms[i]; average = sum / terms.Length; recap: Arrays  Using an array (each element is a double) is this okay if we want an answer that is a double? What if terms and sum are integers? make sure you understand why this is not <=

Aside: Type Casting © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng21

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng22 int [] terms = {25, 30, 60, 10}; double average; int i, sum; sum = 0; for (i = 0; i < terms.Length; i++) sum = sum + terms[i]; average = (double)sum / terms.Length; Type Casting  Now each element is an integer at least one of the values must be a double or the computer will perform an integer division! this is called type casting

Implicit Versus Explicit Casting  In C# 1/3 = 0 and 1.0/3.0 =  What does 1.0/3 equal? © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng23

Implicit Versus Explicit Casting  In C# 1/3 = 0 and 1.0/3.0 =  1.0/3 equals  The reason is that the 3 is implicitly promoted to be a double before the division operation  It is best to not rely on the promotion rules  For all literals that could be floating point numbers, use.0 on the end © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng24

Back to Arrays © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng25

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng26 double [] terms = {25.0, 30.0, 60.0, 10.0}; double sum, average; int i; sum = 0.0; for (i = 0; i < terms.Length; i++) sum += terms[i]; average = sum / terms.Length; recap: Arrays  Use an array (each element is a double) more shorthand

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng27 const int numScores = 10; int [] score = new int[numScores]; string [] name = new string[numScores]; High Score System  Using an array for our high score system would vastly simplify the situation. this is how we declare a constant It is much better to use a constant for the maximum size of the array rather than a magic literal. why?

Aside: Constants © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng28

Constants  Constants do not change  Equates a value with a name  Improve readability by using the symbolic name throughout the program  Change value in only one place  A loop over numScores is easier to read and to modify than a loop over a hard coded literal  Constants often use ALL_CAPS © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng29

Back to Arrays © Copyright 2006 David Das, Ryan Lortie, Alan Wassyng30

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng31 High Score System  Assuming that we have entered/calculated the high scores, how could we print out all of them?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng32 void print_scores() { int i; string result = ""; for (i = 0; i < score.Length; i++) result = result + "score[" + (i + 1) + "] = " + score[i] + " - " + name[i] + "\n"; MessageBox.Show(result); } High Score System  How could we print out all the high scores? what will the output look like?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng33 High Score System  How do we enter the high scores into the array so that they are in the order we want?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng34 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values?

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng35 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve5000

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng36 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve > 7000? No.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng37 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve > 4000? Yes. Mark it.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng38 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve5000 Move the last entry 1 down in the array

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng39 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve5000 Then move the second last entry 1 down in the array

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng40 Alice7000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve5000 And eventually move the entry identified 1 down in the array

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng41 Alice7000 Eve5000 Bob4000 Charlie2000 Dave1000 High Score System  Assume the name and score arrays hold the following values? Now add this new entry: Eve5000 Put new entry in the array

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng42 High Score System  Algorithm  Determine where the new score belongs. Start looking from the top until we find a lower score and mark that index.  Each score from that index to the end is shifted down one element to make room. It is important to start this at the end of the array. The bottom score “falls off” if the array is already full.  The new score is inserted at the identified index.

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng43 High Score System  Add a new entry - newScore, newName:  Find where it fits mark=0 while (mark ≤ lastElement and score mark >=newScore) mark = mark+1  If at end of list don’t do anything, otherwise …  if (mark ≤ lastElement) for j = lastElement downto mark+1 score j = score j-1 name j = name j-1 score mark = newScore name mark = newName

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng44 void add_score(int newScore, string newName) { int mark; //index of "marked” entry int j;//index used to move entries down mark = 0; while (mark <= score.Length-1 && score[mark] >= newScore) mark++; if (mark <= score.Length-1) //only if new is better { for (j = score.Length-1; j > mark; j--) { score[j] = score[j-1]; name[j] = name[j-1]; } score[mark] = newScore; name[mark] = newName; } High Score System

© Copyright 2006 David Das, Ryan Lortie, Alan Wassyng45 void add_score(int newScore, string newName) { int mark; //index of "marked” entry int j;//index used to move entries down mark = 0; while (mark <= score.Length-1 && score[mark] >= newScore) mark++; if (mark <= score.Length-1) //only if new is better { for (j = score.Length-1; j > mark; j--) { score[j] = score[j-1]; name[j] = name[j-1]; } score[mark] = newScore; name[mark] = newName; } High Score System Use print_scores and add_score in a program that will store a name and score on a form, and then add the name / score if a button is clicked, and show current scores if another button is clicked