Download presentation
Presentation is loading. Please wait.
Published bySharyl Wells Modified over 9 years ago
1
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied verbatim from ECE 103 material by prof. Phillip Wong @ PSU
2
Syllabus Introduction to Arrays Declaring 1-D Arrays Variable-Length Array Accessing 1-D Arrays Arrays and Memory Addresses (1-D) Examples
3
2 Introduction to Arrays A simple variable (AKA scalar) stores a single item of a specified data type: A single memory cell is reserved An array variable stores multiple items of the same data type: A block of identical memory cells is reserved In C, arrays are stored in row-major order Fortran, by contrast, stores in column-major order
4
3 Each array item is called an element Elements are stored consecutively in memory in C++ An element is accessed by using the array name with an index value, AKA subscript element #0 element #1 element #2 : element #n Stored @ address A Stored @ address A + sizeof( element ) Stored @ address A + 2·sizeof( element ) Stored @ address A + n·sizeof( element )
5
4 Declaring 1-D Arrays Declaration: datatype array_name[size]; datatype can be: Standard type (e.g., char, int, float, or double) User-defined type Or another array or struct array_name follows the same naming rules as simple variables
6
5 size is the maximum number of items the array should hold; specified in square brackets Example: /* Homework 1 grades for up to 20 students */ int HW1_grade[ 20 ]; /* Homework 2 grades for up to 20 students */ int HW2_grade[ 20 ]; size is a constant positive integral value The array size is fixed and must be known at compile-time (C90)
7
6 Example: /* OK: 10 is a literal constant */ int v[ 10 ]; /* OK: ARY_SIZE is a macro constant */ #define ARY_SIZE 10 int v[ ARY_SIZE ]; /* ERROR: if ary_size is a variable */ int ary_size = 10; int v[ ary_size ]; // Compile-time error C does not automatically initialize all arrays to zero when first declared; only static ones
8
7 Variable Length Arrays C99 allows the size of an array to be determined at run-time: // C99 VLA Example #include int main( void ) { // main int sz; printf( "Enter desired 1-D array size: ” ); scanf( "%d", &sz ); int b[ sz ]; for( int i = 0; i < sz; i++ ) { b[ i ] = 0; } //end for return 0; } //end main C99
9
8 An array can be declared and initialized at the same time by using braces { } Example: double x[3] = { 1.0, 2.5, 6.2 }; // 1.0 2.5 6.2 double x[3] = { 1.0, 2.5 }; // 1.0 2.5 0.0 double x[3] = { 0.0 }; // 0.0 0.0 0.0 The size can be omitted if the 1-D array is initialized during declaration Example: int grades[ ] = { 85, 89, 88, 95, 100, 54 }; Size is automatically set to 6, with low-bound 0 and high- bound 5
10
9 Accessing an Array (1-D) Each array element is assigned an index Lowest index starts at zero (0) If size is the declared array size, then the highest index is size -1 When declaring an array, brackets indicate the maximum size you want When referencing an element of an array, brackets specify which element to access
11
10 Example: int v[ 5 ]; Array elements are: v[0], v[1], v[2], v[3], v[4] First index is 0. Last index is 4 The array index is any expression that evaluates to an integer value Example: Assume j and k contain integers: v[2] or v[k] or v[j+k] or v[j+k*2] Usually the index is a positive integer or zero. Negative indices are legal, but result in undefined behavior
12
11 Warning: Using an array index outside the declared range (bounds) may access incorrect or illegal memory areas. Memory corruption results! Example: int A[3] = {2, 4, 6}; /* Legal indices: 0,1,2 */ /* Accesses memory that does not belong to A */ sum = 0; for( k = 0; k <= 3; k++ ) { sum = sum + A[k]; } //end for // Now we overwrite memory that does not belong to A[] A[-1] = 0; A[3] = 0; C does not perform run-time bounds checking
13
12 Initialize array elements before accessing them! Example: #define N 4 int v[N], s = 0; v[0]=1; v[1]=3; v[2]=-5; v[3]=2;/* Initialize */ for( k = 0; k < N-1; k++ ) { s += v[k] * 2; // Accessing value of element v[k] = k; // Assigning value to element } //end for
14
13 In C++ (or in C) an array cannot be copied to another array with a single assignment operator That is one of the language weaknesses To copy an array, each element must be individually copied (either one at a time or with a loop) Example: int a[3], b[3] = {2, 1, 0}; /* a = b will NOT work!!! */ /* This works */ a[0]=b[0]; a[1]=b[1]; a[2]=b[2]; /* This also works */ for( k = 0; k < 3; k++ ) a[k] = b[k];
15
14 Example: /* Program to calculate Body Mass Index (BMI) */ #include #define N 100 int main( void ) { // main float w[N], h[N], BMI[N]; /* Weight, height, BMI arrays */ int k = 0, i; while( k++ < N ) { printf("[%2d] Enter weight (lb): ", k); scanf("%f", &w[k]); if (w[k] <= 0) break; printf("[%2d] Enter height (in): ", k); scanf("%f", &h[k]); BMI[k] = w[k] / (h[k]*h[k]) * 703; } //end for for( i = 1; i < k; i++ ) { // Display BMI results printf("[%2d] %5.2f %5.2f : %3.1f\n", i,w[i],h[i],BMI[i] ); } //end for return 0; } //end main
16
15 Arrays and Memory Addresses (1-D) When a program runs, a block of memory is allocated to hold the contents of the array The block has a base address in memory Array elements are stored consecutively in the block starting at the base address. The address assigned to an element depends on both the index and the data type size
17
16 Example: /* Assuming 1 byte characters */ char M[3] = { 40, 30, 20 }; /* Assuming 1 byte characters */ char name[3] = { 'C', 'a', 't’ }; AddressEX: base=620Array IndexContents base620040 base+1621130 base+2622220 AddressEX: base=738Array IndexContents base738067 base+1739197 base+27402116
18
17 Example: /* Assuming 4 byte integers */ int x[3] = { 1024, -2048, 4096 }; /* Assuming 8 byte doubles */ double y[3] = { 1.0, 5.25, -3.1e15 }; AddressEX: base=1200Array IndexContents base120001024 base+412041-2048 base+8120824096 AddressEX: base=8192Array IndexContents base819201.0 base+8820015.25 base+1682082-3.1e15
19
18 The array name by itself is the address of the first element in the array Example: Note: & is also used as “address-of” operator in C In the prior example for array M : M is the name of the array M has the value 620 M[0] is the first element of the array M[0] has the value 40 &M[0] is the address of M[0] &M[0] has the value 620 Therefore, M is equivalent to &M[0] AddrIndexCont 620040 621130 622220
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.