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.

Slides:



Advertisements
Similar presentations
 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.
Advertisements

5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Arrays Chapter 6.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 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.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved. 1 C Arrays.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 Pearson Education, Inc. All rights reserved Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Arrays. Introduction This chapter serves as an introduction to the important topic of data structures. Arrays are data structures consisting of related.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
 Pearson Education, Inc. All rights reserved Arrays.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 2008 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Chapter 05 (Part III) Control Statements: Part II.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
7 Arrays and Vectors.
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
CSC 113: Computer Programming (Theory = 03, Lab = 01)
C Arrays.
C Arrays.
7 Arrays.
Introduction to C++ Programming
7 Arrays.
Arrays Kingdom of Saudi Arabia
MSIS 655 Advanced Business Applications Programming
6 C Arrays.
7 Arrays.
7 Arrays and Vectors.
Arrays Arrays A few types Structures of related data items
7 Arrays and Vectors.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

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 items.  To use arrays to store, sort and search lists and tables of values.  To declare arrays, initialize arrays and refer to the individual elements of arrays.  To manipulate a character array as string.

7.1 Introduction 3  Arrays  Data structures containing related data items of same type  Always remain the same size once created  Character arrays can also represent strings  C-style pointer-based arrays vs. vectors (object- based) Vectors are safer and more versatile

7.2 Arrays 4  A variable int number;  An array  Consecutive group of memory locations All of which have the same type int number[7]; 4 4 number: int number: int index

7.2 Arrays 5  Index  Position number used to refer to a specific location/element Also called subscript  Place in square brackets Must be positive integer or integer expression  First element has index zero

6

7.2 Arrays 7  Examine array c in Fig. 7.1  c is the array name  c has 12 elements ( c[0], c[1], … c[11] ) The value of c[0] is –45

Examples  Write/Read the elements of an array  Example: int grade[100], input, count = 0; do { cin >> input; grade[count++] = input; } while (input != -1); for (int i=0; i<count; i++) cout << grade[i] << endl; int grade[100], input, count = 0; do { cin >> input; grade[count++] = input; } while (input != -1); for (int i=0; i<count; i++) cout << grade[i] << endl;

Common Programming Error  It is important to note the difference between the “ seventh element of the array ” and “ array element 7. ”  Array subscripts begin at 0, so the “ seventh element of the array ” has a subscript of 6, while “ array element 7 ” has a subscript of 7 and is actually the eighth element of the array.  To avoid such errors, we refer to specific array elements explicitly by their array name and subscript number (e.g., c[ 6 ] or c[ 7 ] ).

7.3 Declaring Arrays 10  Declaring an array  Arrays occupy space in memory  Programmer specifies type and number of elements Example int c[ 12 ]; c is an array of 12 int s Array ’ s size must be an integer constant greater than zero.  Multiple arrays of the same type can be declared in a single declaration Use a comma-separated list of names and sizes Example: int array1[20], array2[50];

Good Programming Practice  We prefer to declare one array per declaration for readability, modifiability and ease of commenting.  Example: int mathGrade[100];//store grades for math class Int engGrade[100]; //store grades for English class

Examples  int grades[100];  double interest[12];  char name[10];  long amount[50];

7.4 Examples Using Arrays 13  Using a loop to initialize the array ’ s elements  Declare array, specify number of elements  Use repetition statement to loop for each element Use body of repetition statement to initialize each individual array element

Declare n as an array of int s with 10 elements Each int initialized is to 0

n[ j ] returns int associated with index j in array n Each int has been initialized to 0

7.4 Examples Using Arrays 16  Initializing an array in a declaration with an initializer list  Initializer list Items enclosed in braces ( {} ) Items in list separated by commas Example int n[] = { 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 Creates a five-element array Index values are 0, 1, 2, 3, 4 Initialized to values 10, 20, 30, 40, 50, respectively

7.4 Examples Using Arrays 17  If fewer initializers than elements in the array Remaining elements are initialized to zero Example int n[ 10 ] = { 0 }; Explicitly initializes first element to zero Implicitly initializes remaining nine elements to zero  If more initializers than elements in the array Compilation error

Declare n as an array of int s Compiler uses initializer list to initialize array

Common Programming Error  Forgetting to initialize the elements of an array whose elements should be initialized is a logic error. int deposit[12]; Int sum = 0; for (int i=0; i<10; i++) { sum += deposit[i]; } cout << sum << endl; int deposit[12]; Int sum = 0; for (int i=0; i<10; i++) { sum += deposit[i]; } cout << sum << endl;

7.4 Examples Using Arrays (1) 21  Specifying an array ’ s size with a constant variable and setting array elements with calculations  Initialize elements of 10-element array to even integers  Use repetition statement that calculates value for current element, initializes array element using calculated value

Declare constant variable arraySize using the const keyword Use array index to assign element’s value Declare array that contains 10 int s

7.4 Examples Using Arrays (1) 24  Constant variables  Declared using the const qualifier  Also called name constants or read-only variables  Must be initialized with a constant expression when they are declared and cannot be modified thereafter  Can be placed anywhere a constant expression is expected

Software Engineering Observation  Defining the size of each array as a constant variable instead of a literal constant can make programs more scalable.

Good Programming Practice  Defining the size of an array as a constant variable instead of a literal constant makes programs clearer. This technique eliminates so- called magic numbers.  Discuss the following example: int gades[10]; …//input grades for (int i=0; i<10; i++) cout << grades[i] << endl; int gades[10]; …//input grades for (int i=0; i<10; i++) cout << grades[i] << endl;

Common Programming Error 27  Not assigning a value to a constant variable when it is declared is a compilation error.  Assigning a value to a constant variable in an executable statement is a compilation error.  Incorrect example const int arraySize; //Wrong. Why? int a = 1, b = 2; const int arraySize = a + b; //Wrong. Why?

7.4 Examples Using Arrays (2) 28  Summing the elements of an array  Array elements can represent a series of values We can sum these values Use repetition statement to loop through each element Add element value to a total

Declare array with initializer list Sum all array values

7.4 Examples Using Arrays (3) 30  Using bar charts to display array data graphically  Present data in graphical manner E.g., bar chart  Examine the distribution of grades  Nested for statement used to output bars

Declare array with initializer list

For each array element, print the associated number of asterisks

7.4 Examples Using Arrays (4) 33  Using the elements of an array as counters  Use a series of counter variables to summarize data  Counter variables make up an array  Store frequency values

Declare frequency as array of 7 int s Generate random integers in range 1 to 6 Increment frequency values at the index associated with the random number

7.4 Examples Using Arrays (5) 36  Using arrays to summarize survey results  40 students rate the quality of food rating scale: 1 means awful, 10 means excellent  Place 40 responses in an array of integers  Summarize results  Each element of the array used as a counter for one of the survey responses.

Array responses will store 40 responses Array frequency will contain 11 int s (ignore the first element) For each response, increment frequency value at the index associated with that response Initialize responses with 40 responses Initialize frequency to all 0 s

 C++ has no array bounds checking  Does not prevent the computer from referring to an element that does not exist Could lead to serious execution-time errors

Common Programming Error  Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error.  For example: int frequency[4] = {1, 2, 3, 4}; for (int i=0; i<5; i++) cout << frequency[i] << endl;

Portability Tip  The (normally serious) effects of referencing elements outside the array bounds are system dependent. Often this results in changes to the value of an unrelated variable or a fatal error that terminates program execution.

Manipulating Strings 41  Using character arrays to store and manipulate strings  Arrays may be of any type, including char s 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', '\0' };  Array contains each character plus a special string- termination character called the null character ( '\0' )

Manipulating Strings 42  Can also be initialized with individual character constants in an initializer list char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };  Can also input a string directly into a character array from the keyboard using cin and >> cin >> string1; cin >> may read more characters than the array can store  A character array representing a null-terminated string can be output with cout and <<

Common Programming Error  Not providing cin >> with a character array large enough to store a string typed at the keyboard can result in loss of data in a program and other serious runtime errors. char inStr[5]; cin >> inStr; char inStr[5]; cin >> inStr; What will happen if you input a string such as “apple”?

Store "string literal" as an array of characters Initializing an array of characters using cin Output array using cin

Accessing specific characters in the array Loop until the terminating null character is reached