Download presentation
Presentation is loading. Please wait.
Published byDana Hensley Modified over 8 years ago
1
1 Principles of Computer Science I Honors Section Note Set 3 CSE 1341
2
2 Today: Arrays – Part 1
3
3 The Array Array –Can store multiple pieces of data –Homogeneous-typed data structure –Stored contiguously in memory –Each piece of data is an element –Each element can be accessed with one identified and an index.
4
4 The Array Arrays are zero subscripted. Contiguous in memory amt. of memory = size of datatype * number of elements h[9] h[8] h[7] h[6] h[5] h[4] h[3] h[2] h[1] h[0] ? ? ? ? ? ? ? ? ? ? Basic Declaration: int h[10];
5
5 Array Declaration and Initialization int g[3] = {9}; int n[3] = {2, 4, 6}; Initialization List Partial Initialization List ??? n[0]n[1]n[2] 426 ??? g[0]g[1]g[2] 090
6
6 Size Declarators Size declarators must be literals or named constants –Cannot be a variable –Compiler needs to know how much memory to set aside for the array. int temp; cin >> temp; int myArray[temp];
7
7 Accessing Array Elements Name of an array is like a constant pointer to a location in memory Name of array used with a subscript to access individual elements of the array int g[5] = {9, 4, 2}; g[0] = 0; for (int i=0; i<4; i++) g[i]++; subscript – bracket notation subscript can be a variable
8
8 “Off By One” and No Bounds Checking int g[35] = {0}; int i = 0; cout << “Let’s enter some grades!”; for (i = 0; i <= 35; i++) {... } Past the end of the array Compiler doesn’t care if you do this Not a syntax error but almost always a logic error
9
9 Some Grades… int g[35] = {0}; int i = 0; cout << “Let’s enter some grades!”; for (i = 0; i < 35; i++) { cout << “Enter a grade or -1 to quit: “; cin >> g[i]; if(g[i] == -1) break; }
10
10 Passing Some Grades to a Function int g[35] = {0}; int i = 0; cout << “Let’s enter some grades!”; for (i = 0; i < 35; i++) { cout << “Enter a grade or -1 to quit: “; cin >> g[i]; if(g[i] == -1) break; } average(g, i); double average(int g[], int sz) { int sum = 0; for (int i = 0; i < sz; i++) sum += g[i]; return static_cast (sum)/sz; } Just sending a memory address
11
11 Arrays to Functions When passing arrays to functions –function call has no [ ] –function header & prototype have empty [ ] –the array is always passed by “reference” you’re just passing a memory address
12
12 Character Arrays char fName[] = “Mark”; char lName[] = “Fontenot”; cout << lName << “, “ << fName << endl; null-terminated c-string You can display the entire c-string by passing the name of the array to cout DOES NOT WORK FOR numerical-based arrays
13
13 char pWord[25]; cin >> pWord; Will read characters to the first white-space character
14
14 Remember… Arrays are zero-subscripted –last subscript is SizeDeclarator – 1 Use subscripts to access array Arrays are always passed by reference Array contents cannot be copied with = operator – must use loop
15
15 Questions??? ?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.