Chapter 7 Array. Array. C++, How to Program

Similar documents
Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Arrays. Week 4. Assylbek Jumagaliyev

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Control Structures of C++ Programming (2)

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

C++ PROGRAMMING SKILLS Part 4: Arrays

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Programming for Engineers Arrays

by Pearson Education, Inc. All Rights Reserved. 2

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Fundamentals of Programming Session 15

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 04 FUNCTIONS AND ARRAYS

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Array. Arrays. Declaring Arrays. Using Arrays

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

type arrayname [ size type arrayname [ size ] = { item ,, item size size

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Array. Prepared By - Rifat Shahriyar

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Chapter 9 Classes : A Deeper Look, Part 1

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

C++ Arrays. C++ Spring 2000 Arrays 1

C: How to Program. Week /Apr/23

Arrays (Deitel chapter 7)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Review of Important Topics in CS1600. Functions Arrays C-strings

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

ONE DIMENSIONAL ARRAYS

Multiple-Subscripted Arrays

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

BITG 1113: Array (Part 1) LECTURE 8

Arrays. Systems Programming Concepts

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Arrays and Applications

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

C Arrays Pearson Education, Inc. All rights reserved.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

tablica: array: dane_liczbowe

Instructor: Eng.Omar Al-Nahal

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Functions. Introduction :

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Data types. CISC 1600/1610 Computer Science I. Array syntax. Memory allocation. Zero-indexing 4/4/2016. Arrays

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

PROGRAMMAZIONE I A.A. 2017/2018

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

CS242 COMPUTER PROGRAMMING

CSC 211 Intermediate Programming. Arrays & Pointers

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

UNIT- 3 Introduction to C++

The C++ Language. Arizona State University 1

Module 6: Array in C

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

How to declare an array in C?

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

BITG 1113: Array (Part 2) LECTURE 9

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

FORM 2 (Please put your name and form # on the scantron!!!!)

Chapter 7 : Arrays (pp )


Exam 3 Chapters 7 & 9

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

C++ Final Exam 2017/2018

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Transcription:

Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory locations. Spring 2016 CISC 1600 Yanjun Li 2 1

Elements of An Array To refer to a particular location or element in the array, we specify the name of the array and the index of the element. The index must be integer or integer expression, its value must be larger than or equal to 0. First element has index zero. The element could be used as a variable. Example C[ 0 ] += 2; C[a+b] = 3; Spring 2016 CISC 1600 Yanjun Li 3 Example An array c has 12 elements ( c[0], c[1], c[11] ); the value of c[0] is 45. Spring 2016 CISC 1600 Yanjun Li 4 2

Declare An Array Declaration of an array: type arrayname[ arraysize ]; Example int c[ 12 ]; Array s size must be an integer constant greater than zero. Once declared, the size of the array is fixed. Arrays can be declared to contain values of data types like int, float, double, char, etc. Spring 2016 CISC 1600 Yanjun Li 5 Initialize An Array (1) With an initializer list Initializer list Items enclosed in braces ({}) and separated by commas. Examples int n[ 5 ] = { 10, 20, 30, 40, 50 }; int m[ 5 ] = { 10, 20, 30 }; The remaining elements are initialized to zero. int p[ ] = { 10, 20, 30, 40, 50 }; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list. Spring 2016 CISC 1600 Yanjun Li 6 3

Initialize An Array (2) Using a loop to initialize the array s elements Declare array, specify number of elements Use repetition statement to loop for each element Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ]=0; } Spring 2016 CISC 1600 Yanjun Li 7 Initialize An Array (3) Specifying an array s size with a constant variable and setting array elements with a loop statement. Example: const int arraysize = 10; int s[ arraysize ]; for (int i = 0; i < arraysize; i++) { s[ i ] = 2 + 2*i; } Spring 2016 CISC 1600 Yanjun Li 8 4

Initialize An Array (4) Read the value for each element one by one from the keyboard Example const int arraysize = 5; int array[arraysize]; for (int i=0;i<arraysize; i++) { cout << Please specify a value for element no. << i <<endl; cin >> array[i]; } Spring 2016 CISC 1600 Yanjun Li 9 Using An Array Usually use for loop to access each element of an array. C++ has no array bounds checking Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. You need to provide the correct array size. Spring 2016 CISC 1600 Yanjun Li 10 5

Print An Array Use a for loop to access each element of the array and print one by one. Example const int arraysize = 5; int array[arraysize] = { 1, 2, 4, 67, 3 }; for (int i=0; i<arraysize; i++) { cout <<array[i]<<endl; } Spring 2016 CISC 1600 Yanjun Li 11 Using An Array Example 1 Summing the elements of an array Example: const int arraysize = 6; int a [ arraysize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; for ( int i = 0; i < arraysize; i++) { total += a[i]; } cout << Total of array elements is <<total<<endl; Spring 2016 CISC 1600 Yanjun Li 12 6

Using An Array Example 2 Using the counter as the index of elements of an array. Example const int arraysize = 5; double optionalequipmentcost [arraysize]; for (int i =0; i< arraysize; i++) { //for house No.? } //after the user selected engine and paint options, //save the optional equipment cost in an array. optionalequipmentcost[i] = optionalequipment; Spring 2016 CISC 1600 Yanjun Li 13 Using An Array Example 3 Using character arrays to store and manipulate strings We can store character strings in char arrays Can be initialized using a string literal Example char string1[] = "Hi"; Equivalent to Char string1[] = {'H', 'i'}; char string1[] = { 'H', 'i', '\0' }; Array contains each character plus a special stringtermination character called the null character ('\0') Spring 2016 CISC 1600 Yanjun Li 14 7

Using An Array Example 3 Using character arrays to store and manipulate strings (Cont.) Can also input a string directly into a character array from the keyboard using cin and >> cin >> string1; cin reads characters from the keyboard until the first white-space character is encountered regardless of the array size. cin >> may read more characters than the array can store A character array representing a null-terminated string can be output with cout and << cout << string1; Spring 2016 CISC 1600 Yanjun Li 15 Passing Arrays to Functions (1) Functions that take arrays as arguments: void modifyarray (int array [ ], int size); To pass an array argument to a function int hourlytemperatures[ 24 ]; modifyarray( hourlytemperatures, 24 ); Array size is normally passed as another argument so the function can process the specific number of elements in the array Spring 2016 CISC 1600 Yanjun Li 16 8

Passing Arrays to Functions (2) Arrays are passed by reference Function call actually passes starting address of array So function knows where array is located in memory Caller gives called function direct access to caller s data Called function can manipulate this data Spring 2016 CISC 1600 Yanjun Li 17 Passing Arrays to Functions (3) Example double kitchenoption(int, int []); int kitchenoptions[5]={0}; optionalfeaturecost = kitchenoption(counter, kitchenoptions); double kitchenoption(int counter, int oc[]) { //part of this function int choice; cin>>choice; oc[counter-1] = choice; } Spring 2016 CISC 1600 Yanjun Li 18 9

Passing An Element to Functions Individual array elements passed by value Use the subscripted name of the array element as an argument Single pieces of data Spring 2016 CISC 1600 Yanjun Li 19 const array parameters Qualifier const Example: void funcone(const int [ ]); int a[] = {10,20,30}; funcone(a); Prevent modification of array values in the caller by code in the called function Elements in the array are constant in the function body Enables programmer to prevent accidental modification of data Spring 2016 CISC 1600 Yanjun Li 20 10

Searching Arrays with Linear Search Arrays may store large amounts of data May need to determine if certain key value is located in an array Linear search Compares each element of an array with a search key Just as likely that the value will be found in the first element as the last On average, program must compare the search key with half the elements of the array To determine that value is not in array, program must compare the search key to every element in the array Works well for small or unsorted arrays Spring 2016 CISC 1600 Yanjun Li 21 Multidimensional Array Multidimensional arrays with two dimensions Called two dimensional or 2-D arrays Represent tables of values with rows and columns Elements referenced with two subscripts ([x][y]) In general, an array with m rows and n columns is called an m-by-n array Multidimensional arrays can have more than two dimensions Spring 2016 CISC 1600 Yanjun Li 22 11

Declaring & Initializing Two-Dimensional Arrays Declaring two-dimensional array b int b[ 3 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ] 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ] 0 and 0 initialize b[ 2 ][ 0 ] and b[ 2 ][ 1 ] (implicitly). Row 0 Row 1 Row 2 Column 0 1 3 0 Column 1 2 4 0 Spring 2016 CISC 1600 Yanjun Li 23 Two-Dimensional Array Spring 2016 CISC 1600 Yanjun Li 24 12

Passing Multidimensional Arrays to Functions Multidimensional array parameters Size of first dimension is not required As with a one-dimensional array Size of subsequent dimensions are required Compiler must know how many elements to skip to move to the second element in the first dimension Example void printarray( const int a[][ 3 ] ); Function will skip row 0 s 3 elements to access row 1 s elements (a[ 1 ][ x ]) Spring 2016 CISC 1600 Yanjun Li 25 Multidimensional-Array Manipulations Commonly performed with for statements Example Modify all elements in a row for ( int col = 0; col < 4; col++ ) a[ 2 ][ col ] = 0; Example Total all elements total = 0; for ( int row = 0; row < 3; row++ ) for ( int col = 0; col < 4; col++ ) total += a[ row ][ col ]; Spring 2016 CISC 1600 Yanjun Li 26 13

Reference Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc. Spring 2016 CISC 1600 Yanjun Li 27 14