10/06/08MET CS 563 - Fall 2008 5. Arrays and Vectors 1 Multidimensional Types: 5. Arrays and Vectors Need: ability to define and manipulate variable objects.

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
Advertisements

Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
10/14/08MET CS Fall Vectors 1 Multidimensional Types: 5. 2 Vectors declare / define objects initialize objects access objects and, if multidimensional,
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
10/20/08MET CS Fall Pointers, Arrays & Pointers. Call by Reference 1 6. Pointers. Arrays & Pointers. Call by Reference with Pointers 6.1.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Searching Arrays. COMP104 Array Sorting & Searching / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and save its.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
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.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Data Structure and Algorithms
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
L what is a void-function? l what is a predicate? how can a predicate be used? l what is program stack? function frame? l what’s call-by-value? l what’s.
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.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Arrays float Scores[9]; ? index: element // one dimensional array 2.
L what is a void-function? l what is a boolean function? l is it possible for a function to have no parameters? l what is program stack? function frame?
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
آرايه ها اصول كامپيوتر 1.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays Kingdom of Saudi Arabia
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
4.1 Introduction Arrays A few types Structures of related data items
Arrays Kingdom of Saudi Arabia
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

10/06/08MET CS Fall Arrays and Vectors 1 Multidimensional Types: 5. Arrays and Vectors Need: ability to define and manipulate variable objects that have multiple values and access the individual values separately f(x), x=1, 2,…,100 m(i, j), i=1,..5, j=1,…3 student(first="adam", last="smith", id=7814) all values are of the same type  arrays and vectors values are of the different type  structures and classes

Questions Asked When Introducing New Types: How do we declare / define objects initialize objects access objects and, if multidimensional, access values of individual elements/fields compute with objects and their individual fields: operators, IO, functions; pass object as parameter to & returned value from function 10/06/08MET CS Fall Arrays and Vectors 2

10/06/08MET CS Fall Arrays and Vectors Arrays: Declaration Examples 1. points in space with three coordinates (x, y, z): array with 3 elements of type float: float point[3]; 2. scores of a class of 30 students int scores[30]; point[0] point[1] point[2] point scores scores[0] scores[1] … scores[29] element or indexed variable [ ] - 1 index starts with 0, not 1

10/06/08MET CS Fall Arrays and Vectors 4 Declaration – Syntax: [ ] ;Notes: capacity is the maximal number of elements an array can hold size is the number of elements in array, size <= capacity the index starts from 0, not from 1; thus the index of the last element is - 1, while index points to the first free slot array occupies contiguous space in memory array-name a-name[0] … a-name[size-1] a-name[size] … a-name[capacity - 1 ] last element slot 1 st elementlast element 1 st free element slot must be const integral value

10/06/08MET CS Fall Arrays and Vectors 5 Array Access Examples: 1.cout << point[1]; 2. scores[9] = 89; cout << scores[6]; 3.Adding the values of all array elements: two alternative styles for loops: for ( i = 0; i < arraySize ; i++ ) total += a[ i ]; for ( i = 0; i < = arraySize - 1 ; i++ ) total += a[ i ]; Note: Note: The array element is a single valued variable of the corresponding type and behaves/can be manipulated as any other data object of this type. The 10th element of array point is assigned the value 89 The 7th element of array point is printed Indicates size of the array: PREFERRED Indicates range of index

10/06/08MET CS Fall Arrays and Vectors 6 Array Initialization Examples: 1. float point[3]= {1, 2, 3}; 2. int scores[30] = {0}; //all elements are initialized to 0 3. int scores[30] = {1, 2,3}; //first three elements are initialized to 1,2,3 //the remaining elements are initialized to 0 point[0]point[1]point[2]

10/06/08MET CS Fall Arrays and Vectors 7 Example: arrayBasics.cpp declaration initialization print array, ten elements per row sum all array elements increment all array elements add/remove elements from array (within capacity) and keep track of changes in array size

10/06/08MET CS Fall Arrays and Vectors 8 Definition: (vectorParameters.cpp) /** Prints array ten elements per a – int size - number of elements */ void print(int a[], int size) { for ( int i = 0; i < size ; i++ ){ cout<<setw(4)<< a[ i ]; if ( i % 10 == 9) cout << endl; } Call: const int CAPACITY = 30; int a[ CAPACITY ] = { 1, 3, 5, 4, 7}; int a_size = 5; … print(a, CAPACITY); print(a, a_size); Arrays as Parameters to Functions--Example Prototype: void print(int [], int);

10/06/08MET CS Fall Arrays and Vectors 9 Definition: return_type fct_name ( element_type ar_name [],type1 par1,…){…} void print ( int a[], int size) {…} Prototype: return_type fct_name ( element_type [],type1,…); void print( int [], int); Call: fct_name (ar_name, par1,…) print(a, CAPACITY); print(a, a_size); Arrays as Parameters to Functions--Syntax

10/06/08MET CS Fall Arrays and Vectors 10 Arrays Are Passed "By Reference" Important Implementation Fact: name of array a = address of first element and a[0] accesses the 1 st element … a[i] accesses the (i-1) element Therefore passing the name of the array to a function gives the function access to the actual object of the calling environment and allows the function to make changes to it, i.e. Arrays are always passed by reference!

10/06/08MET CS Fall Arrays and Vectors 11 The print function does not change any array elements. Good style requires that this is indicated by the const qualifier in the parameter list: void print(int a[], int size) {…} one should write void print( const int a[], int size) {…} The functionality remains exactly the same, but the addition explicitly shows entities that are not affected by the function. Use const to Indicate Function Does Not Change the Array—Example

10/06/08MET CS Fall Arrays and Vectors 12 Returning Arrays from Functions—Somewhat Tricky When passing an array to function we used the syntax el_type ar_name[] e.g. int a[] in the parameter list and el_type [] e.g. int [] in the prototype. It would seem logical to use the latter as a return type for an array, e.g. int [] doubler(int a[], int size);//ILLEGAL! Unfortunately this is illegal. (It also produces a bunch of syntax error messages not related to the real cause of the problem.) el_type [] is not a separate array type but just a notation to be used in the list of parameters passed to the function to indicate that the name of an array will be passed to the function. Arrays can be function parameters but not function return types!

10/06/08MET CS Fall Arrays and Vectors 13 Returning Arrays from Functions— References and Pointers We saw that there is no array return type. To still return an array from a function one must consider the following constraints: A function returns a single value An array has multiple values These two contradictory constraints can be satisfied in two ways: the array is changed directly in the function, which is in fact equivalent to a function returning values. Implementation is not a problem because the array is passed by reference to define and use a return type that can hold the name of the array, i.e. a memory address  pointers

10/06/08MET CS Fall Arrays and Vectors 14 Example: arrayParameters.cpp Define and use the functions: void print( const int [], int ); void arrayIncrement(int [], int, int ); void arrayAddElements(int [], int&, int );

10/06/08MET CS Fall Arrays and Vectors 15 Example: Adding Elements to Array /** Adds elements to array as specified by user and reads in their a – int capacity - maximum number elements array can size - number of elements */ void arrayAddElements(int a[], int& size, int capacity) { cout << "How many elements do you want to add " <<"(at most " << capacity - size << " )"; int number; cin >> number; int init = size; cout << "Enter values for " << number << " new elements " << endl; for ( int i = init; i < init + number ; i++ ){ cin >> a[i]; size++; } Function needs both capacity and size size must be passed as a reference

10/06/08MET CS Fall Arrays and Vectors 16 // Fig. 5.1: Array Initialization and Adding All Elements const int arraySize = 12; int a[ arraySize ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; int total = 0; cout << "Print array a \n"; for ( int i = 0; i < arraySize ; i++ ) cout<< setw(4)<< a[ i ]; for ( i = 0; i < arraySize ; i++ ) total += a[ i ]; cout << "\nTotal of array element values is " << total << endl; int b[ arraySize ] = { 0 }; cout << "\nPrint array b \n"; for ( i = 0; i < arraySize ; i++ ) cout<<setw(4)<< b[ i ]; int c[ arraySize ] = {3, 3, 3, 0 }; cout << "\nPrint array c \n"; for ( i = 0; i < arraySize ; i++ ) cout<<setw(4)<< c[ i ]; return 0; Print array a Total of array element values is 383 Print array b Print array c

10/06/08MET CS Fall Arrays and Vectors 17 Sorting an array of integers In ascending order: Bubble Sort Pass through the array comparing any two neighbor elements a[i] and a[i+1], i = 0,1,…, - 2 and swapping them if a[i] > a[i+1] At the end of the 1st pass the largest value will "bubble up" to the last array position. Repeat the procedure till the entire array is sorted, i.e. a total of - 1 times (passes) Similarly when sorting in descending order the largest value will “sink” to the bottom of the array. This is why the bubble sort is also referred to as sink sort Files: swap.cpp, swap.h, arraysBubbleSort.cpp

10/06/08MET CS Fall Arrays and Vectors 18 Bubble Sort ( Bubble Sort (arraysBubbleSort.cpp) Enter 10 integers: You entered the following 10 integers: #include "swap.h" #include using namespace std; int main() { int const CAPACITY=20; int a[CAPACITY]; int size = 10; cout << "Enter " << size << " integers: \n"; for (int i=0; i < size; i++) cin >> a[i]; cout << "You entered the following " << size << " integers: \n"; for (int i=0; i < size; i++) cout << setw(4) << a[i];

10/06/08MET CS Fall Arrays and Vectors 19 // Bubble Sort - descending order The array sorted in descending order is: traversal from highest to lowest index Note: array elements are passed by value in function calls unless otherwise specified, as they are regular one-valued variables and treated as such. arrays are passed by reference as the name of the array is an address for (int pass=1; pass < size; pass++) for (int i=size-1; i > 0; i--) if(a[i-1] < a[i]) swap(a[i],a[i-1]); cout << "\n\nThe array sorted in descending order is:\n"; for (int i=0; i < size; i++) cout << setw(4) << a[i];

Function Definition and Header Files 10/06/08 MET CS Fall Arrays and Vectors 20 swap.cpp: #include "swap.h" void swap(int& a, int& b) { int s; s=a; a=b; b=s; } swap.h: #ifndef SWAP #define SWAP void swap(int&, int&); #endif SWAP