Lecture Programming in C++ - Chapter 9: One-dimensional numeric arrays. On completion of this chapter students will know how to: Create and manipulate arrays, trace and debug loops that manipulate arrays, reserve memory during program execution, use arrays to solve problems.
Chapter 9 – OneDimensional Numeric Arrays Array Data structure Grouping of liketype data Indicated with brackets containing positive integer constant or expression following identifier – Subscript or index Loops commonly used for manipulation Lesson 9.1 OneDimensional Arrays Declaration indicates name and reserves space for all elements Values assigned to array elements using assignment statements Array names classified as identifiers Programmer sets size of array explicitly Lesson 9.1 Array Length Determined by expression or value enclosed in brackets in declaration General form for declaration type name[value]; Value in brackets can be constant variable, expression, or literal const int N = 26; double b[N]; Lesson 9.1 int a[25]; int b[5+2]; Array Length Must be integer constant greater than 0 Only integer type variables (with modifiers) – int, char – signed, unsigned, short, long Always within brackets following identifier Valid Examples: int c[32]; int c[25], b[43.5]; Invalid Lesson 9.1 Array Subscripts First index or subscript is 0 int a[2]; – – – – Data type of elements is int Name of array is a Number of elements is 2 Valid subscripts are 0 and 1 Address as a[0] and a[1] Lesson 9.1 Printing Array Elements Use cout Treat like single variable Print one element at a time Example: cout num_elem; for (j = 0; j > a[j]; } First line of file contains number of array elements File Input – Sentinel Value Particular predefined value contained in file that indicates end of data group Loop and read data value by value until sentinel is read for (j = 0; a[j] != 1; j++) Where –1 is the { sentinel value infile1 >> a[j]; } Loop to Print Data From Array (scores is array of 20 test scores) for (int j = 0; j