Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Slides:



Advertisements
Similar presentations
Chapter 9 – One-Dimensional Numeric Arrays. Array u Data structure u Grouping of like-type data u Indicated with brackets containing positive integer.
Advertisements

Introduction to C Programming
EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 10.
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
 2006 Pearson Education, Inc. All rights reserved Arrays.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
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.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using for/while loops for sequential access t Demo programs.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Computer Organization and Design Pointers, Arrays and Strings in C
Fundamentals of Characters and Strings
Chapter 7 Part 1 Edited by JJ Shepherd
Arrays in C.
Pointers and Pointer-Based Strings
COMS 261 Computer Science I
7 Arrays.
Chapter 9: Data Structures: Arrays
C++ Programming Lecture 20 Strings
Lecture 2 Arrays & Pointers September 7, 2004
COMS 261 Computer Science I
Presentation transcript:

Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9

3/13/02 Program 4 questions? –revised test1 and my version of the program –program should always process at least one customer Program 6 (and HW2) may be done by two people working together

2 9.1 The Array Data Type Array collection of elements with a common name –Entire array is referenced through the name Array elements are of the same type — the base type –Base type can be any fundamental, library- defined, or programmer -defined type For now: arrays are static - they have a fixed number of elements

4 Array Elements Individual elements of the array are referenced by sub_scripting the group name –Subscripts are denoted as expressions within brackets: [ ] –The index type is integer and the index range must be 0... n -1 where n is the number of elements in the array

6 Array Declaration

7 Sample Declarations Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000 ;

8 Sample Declarations Then the following are all correct array declarations. int A[10]; char B[MaxStringSize]; float C[M*N]; int Values[MaxListSize]; Rational D[N-15];

Array Initialization An array can be initialized at the time it is declared char grades[5] = {'A', 'B', 'C', 'D', 'F'}; int primes[] = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23} if values provided do not fill the array, remainder of elements will be 0 double x[10] = {1.5, 2.5, 3.5, 4.5, 5.5}

9 Subscripting Suppose int A[10]; // array of 10 ints To access an individual element we must apply a subscript to array name A –A subscript is a bracketed expression The expression in the brackets is known as the index –First element of A has index 0 A[0]

10 Subscripting –Second element of A has index 1, and so on A[1] –Last element has an index one less than the size of the array A[9] Incorrect indexing is a common error –be careful not to index past the end of the array

11 Array Elements Suppose int A[10]; // array of 10 uninitialized ints To access an individual element we must apply a subscript to array name A

12 Array Element Manipulation Given the following: int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12;

13 Array Element Manipulation cin >> A[k]; // where the next input value is 3

Array Processing None of the operators are defined for an array – > arithmetic comparison To do the same thing to every element in an array, use a loop

14 Inputting Into An Array int A[MaxListSize]; int n = 0; int CurrentInput; while((n > CurrentInput)) { A[n] = CurrentInput; ++n; }

15 Displaying An Array // List A of n elements has // already been set for (int i = 0; i < n; ++i) { cout << A[i] << " "; } cout << endl;

Partially filled arrays You don't have to use all the elements of an array –don't always know how many elements you will need –declare array big enough to handle all cases it is your job to keep track of how many elements are valid

3/15/01 HW 2: Planning for program 6 –you may do this in pairs –look at P6 handout for ideas –this is a planning exercise - you are not writing code P5 - start thinking about how to organize the main playing loop of a Yahtzee game

Cheating making copies of other students programs is NOT appropriate behavior I will be comparing all Program 4 submissions to check for copying Acknowledge anyone that you get help from in your readme

17 Access to Array Elements Sequential Access –Process elements in sequential order starting with the first Random Access –you can access elements in random order

Array Elements Use, +, - to test and modify array elements At times it might benefit you to pass an entire array to a function Can pass array elements to functions –actual function call swap (s[3], s[5]);

24 swap.cpp // FILE: Exchange.cpp // Exchanges two type float values void exchange (float& a1, float& a2) { float temp; temp = a1; a1 = a2; a2 = temp; }

25 Arrays as Function Arguments Arrays are always passed by reference –Passing the array address –contents can be changed Points to remember –function definition needs only [] to indicate that the actual argument is an array –You can use the reserved word const to prevent the contents of an array from being changed

Reading Part of an Array Sometimes it is difficult to know how many elements will be in an array Scores example –150 students –200 students Always allocate enough space at compile time Remember to start with index [0]

Searching and Sorting Arrays Look at 2 common array problems –Searching –Sorting How do we go about finding the smallest number in an array? –Assume 1st is smallest and save its position –Look for one smaller –If you locate one smaller save its position

43 Linear Search The idea of a linear search is to walk through the entire until a target value is located If the target is not located some type of indicator needs to be returned

46 Sorting in Ascending Order Selection Sort Idea of the selection sort is to locate the smallest value in the array Then switch positions of this value and that in position [0] We then increment the index and look again for the next smallest value and swap Continue until sorted

Section 1 3/18/02

character arrays arrays can have any base type char arrays are useful for storing text C used a char array for strings –use null character to designate the end of the string C++ has a string class

literal strings A literal string constant is a sequence of zero or more characters enclosed in double quotes "Are you aware?\n" Individual characters of string are stored in consecutive memory locations The null character ('\0') is appended to strings so that the compiler knows where in memory strings ends

C-style strings array of char with a null character as the last element –null character has ASCII code 0 –'\0' 'w''o''r''d''\0' operators = and == not defined for C-style strings

Declaring and initializing Declaring uninitialized char cstr[15]; Declaration with initialization char letters[] = "abcde"; char grades[] = {'A', 'B', 'C', 'D', 'F', '\0'} char notString[] = {'A', 'B', 'C', 'D',} In first case above, the null character is appended for you

string.h int strlen( char[])number of characters in array; doesn't count '\0' void strcpy( char[], char[]) copy one C-style string to another int strcmp( char[] char[])compare two C-style strings void strcat( char[], char[])append one C-style string to another

length vs number of elements char word = "word"; word has 5 elements BUT strlen( word) = 4

assigning values NOT ALLOWED char a[] = "stuff", b[]; b = a; How do you do this? strcpy( b, a); Now b also contains "stuff"

comparing C-style strings == not defined for strings –use strcmp strcmp( a, b) returns 0 if the strings are the same returns a number >0 if a comes after b lexicographically returns a number < 0 if a comes before b

reading strings char a[10]; cin >> a; whitespace delimited to read multiple words, use getln cin.getline( a, 10); the number is the number of elements in the array

concatenating C-style strings char str1[]="cat", str2[]="top"; strcat(str2, str1); after this code has executed, str2 will contain "topcat"

42 C++ string class library is string (no.h) declaration and initialization

string Class #include Various operations on strings are defined –assignment with = –comparison with == –concatenation with +, += –length() function returns the string length –c_str() returns a C-style string as const

16 Remember Arrays are always passed by reference Can use const if array elements are not to be modified You do not need to include the array size within the brackets when defining an array parameter Initialize array with 0 or some other known value

Common Programming Errors Watch non int subscripts (ASCII value) Enumerated types can be used Out of range errors –C++ no range error checking Lack of subscript to gain access Subscript reference to non-array variable Type mixing when using with functions Initialization of arrays

66 Common Programming Errors No prefix to reference a struct member Incorrect prefix reference to a struct member Missing ; following definition of struct Initialization of struct members