Understanding Arrays in C++ Programming

lecture six arrays n.w
1 / 33
Embed
Share

Learn about arrays in C++ programming, including declaration, indexing, memory allocation, and accessing elements. Understand the fundamentals of arrays and their role in storing multiple variables efficiently.

  • C++
  • Arrays
  • Programming
  • Memory
  • Variables

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Lecture Six Arrays

  2. Arrays An array, is a list of individual items that all have the same fundamental type. An array can hold multiple variables with the same type in adjacent memory locations. The variables in the array all use the array name and are distinguished from one another by their subscripts. A subscript is a number that indicates the position of the particular array element being used. An element is a single object in an array. A subscript is used to directly access a particular array element. Data Structure Saturday, May 3, 2025 2

  3. Array Declaration In C++, you declare an array by using the following syntax: type arrayName [size]; Where type is any simple type, (int, float, char, ) arrayName is any legal identifier, and size (in the square brackets) represents the number of elements the array contains. Saturday, May 3, 2025 Data Structure 3

  4. Array Declaration For example, the following statement declares an array of five elements, each of which is type double: double moneyCollected[5]; The elements in an array are numbered from zero to one less than the size of the array. Saturday, May 3, 2025 C++ Programming Language 4

  5. Arrays The array declaration int someNumbers[7]; declares an array that holds seven integers. The name of the array represents the beginning address of the array. cout << someNumbers; The following statement produces identical output because the name of the array is the address of the array s first element: cout << &someNumbers[0]; Similarly, the following two statements produce the same results: cout << (someNumbers + 1); cout << &someNumbers[1]; The first statement display the address of someNumbers plus one more integer, so if the array is stored at memory address 3000, for example, and integers are four bytes, then the statement displays 3004. The second statement display the address of the second element of the someNumbers array. Saturday, May 3, 2025 C++ Programming Language 5

  6. Arrays The subscript that is used to access an element of an array indicates how much is added to the starting address to locate a value. For example, if you declare an array as Int someNumbers[7]; and if an int requires four bytes of storage in your system, when you access the value of someNumbers[2], you access the value of exactly two integers, or eight bytes away from the beginning address of the array. Saturday, May 3, 2025 C++ Programming Language 6

  7. Initialization Syntax: int X[4] = {2, 4, 7, 9}; Behavior: initialize elements starting with leftmost, i.e. Remaining elements are initialized to zero. element 0. X 2 4 7 9 0 1 2 3 Initialize all to 0: int X[4]={0}; Saturday, May 3, 2025 Data Structure 7

  8. STORING VALUES IN AN ARRAY This program segment shows the declaration of a four-element integer array named rent, and also shows how you can assign a rent value to each array element. int rent[4]; rent [0]= 250; rent [1]= 375; rent [2]= 460; rent [3]= 600; Data Structure 8 Saturday, May 3, 2025

  9. STORING VALUES IN AN ARRAY int rent[4] = {250, 375, 460, 600}; The four values listed within the curly braces are assigned, in sequence, to rent[0], rent[1], rent[2], and rent[3]. If you declare an array without a size, but provide initialization values, C++ creates an array with the exact size you need. For example, the following two array declarations create identical arrays: int rent[4] = {250, 375, 460, 600}; int rent[] = {250, 375, 460, 600}; Saturday, May 3, 2025 C++ Programming Language 9

  10. Operations with Arrays Assignment x[0] = 6; y[2] = 3.1; Access m = x[2]; p = y[0]; Input/Output: the elements are handled as their types, e.g. Cin<<&x[2]<< &y[3]; Cout<<x[0]<< y[2]; /* output 6 and 3.1 */ /* Assign 3.1 to element y[2] */ /* Assign 6 to element x[0] */ Saturday, May 3, 2025 Data Structure 10

  11. Arithmetic Operations int main() { double x[5]; Variable Declaration for the array } x[0] = 1; x[1] = 2; x[2] = x[0] + x[1]; x[3] = x[2] / 3; x[4] = x[3] * x[2]; /* X[2] = 3 */ /* X[3] = 1 */ /* X[4] = 3 */ Saturday, May 3, 2025 Data Structure 11

  12. for loops for loops are ideal for processing elements in the array. int main() { int i; double values[4] = {3.14, 1.0, 2.61, 5.3}; double sumValues = 0.0; for (i=0; i<4; i++) { sumValues = sumValues + values[i]; } cout<< Sum = %lf\n <<sumValues; } Saturday, May 3, 2025 Data Structure 12

  13. for loops for loops are ideal for processing elements in the array. int main() { int i; double values[4] = {3.14, 1.0, 2.61, 5.3}; double sumValues = 0.0; ERROR! Out of bound for (i=0; i<=4; i++) { sumValues = sumValues + values[i]; } cout<< Sum = %lf\n << sumValues; } Saturday, May 3, 2025 Data Structure 13

  14. Example int main() { double grades[5] = {90, 87, 65, 92, 100}; double sum; int i; cout<<"The first grade is: %.1f\n", grades[0]; sum = 0; for(i=0; i<5; i++) { sum += grades[i]; } cout<<"The average grade is: %.1f\n", sum / 5; grades[2] = 70; /* Replaces 65 */ grades[3] = grades[4]; /* Replaces 92 with 100 */ } Data Structure 14 Saturday, May 3, 2025

  15. ACCESSING AND USING ARRAY VALUES #include<iostream> int main(){ const int SIZE = 5; int singleInt = 52; int arrayInt[SIZE] = {12, 36}; cout << "SingleInt is " << singleInt << endl; cout << "First array element is " << arrayInt[0] << endl; ++singleInt; ++arrayInt[0]; cout << "After incrementing, " << "singleInt is " << singleInt << endl; cout << "After incrementing, " << "first array element is " << arrayInt[0] << endl; singleInt = singleInt * 2; arrayInt[0] = arrayInt[0] * 2; cout << "After doubling, singleInt is " << singleInt << endl; cout << "After doubling, first array element is " << arrayInt[0] << endl; return 0;} Saturday, May 3, 2025 C++ Programming Language 15

  16. ACCESSING AND USING ARRAY VALUES const int SZ_OF_ARRAY = 5; int arrayInt[SZ_OF_ARRAY] = {34, 56, 12, 3, 99}; for(int x = 0; x < SZ_OF_ARRAY; ++x) cout << arrayInt[x] << endl; Saturday, May 3, 2025 C++ Programming Language 16

  17. ACCESSING AND USING ARRAY VALUES #include<iostream> int main() { const int NUM_PRICES = 10; double price[NUM_PRICES]; int sub; for(sub = 0; sub < NUM_PRICES; ++sub) { cout << "Enter a price "; cin >> price[sub]; } cout << endl << "The entered prices, in reverse order:" << endl; for(sub = NUM_PRICES - 1; sub >= 0; --sub) cout << price[sub] << " "; cout << endl; return 0; } Saturday, May 3, 2025 C++ Programming Language 17

  18. Constants for capacity Good programming practice: use #define for constants in your program For example: #define MaxLimit 25 int grades[MaxLimit]; for(int i; i<MaxLimit; i++){ }; If size needs to be changed, only the capacity MaxLimit needs to be changed. Saturday, May 3, 2025 Data Structure 18

  19. 2-D Arrays int cave[ArraySize][ArraySize]; Column 0 1 2 3 1 5 9 2 6 3 7 11 15 4 8 0 1 Row 10 14 12 16 2 13 3 Saturday, May 3, 2025 Data Structure 19

  20. 2D Arrays Column 0 1 2 3 1 5 9 2 6 3 7 11 4 8 myMatrix[0][1] 2 0 1 Row 10 12 2 myMatrix[2][3] 12 myMatrix[row][col] int myMatrix[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} }; Saturday, May 3, 2025 Data Structure 20

  21. Physically, in one block of memory int myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} }; ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28 1 2 3 4 5 6 7 8 row 1 row 2 Array elements are stored in row major order. Row 1 first, followed by row2, row3, and so on Saturday, May 3, 2025 Data Structure 21

  22. 2D Array Name and Addresses int myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} }; ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28 1 2 3 4 5 6 7 8 myMatrix: pointer to the first element of the 2D array myMatrix[0]: pointer to the first row of the 2D array myMatrix[1]: pointer to the second row of the 2D array Saturday, May 3, 2025 Data Structure 22

  23. Accessing 2D Array Elements int myMatrix[2][4] = { {1,2,3,4} , {5,6,7,8} }; 1 2 3 4 5 6 7 8 Indexing: myMatrix[i][j] is same as (myMatrix[i] + j) ( (myMatrix + i))[j] (( (myMatrix + i)) + j) (&myMatrix[0][0] + 4*i + j) Saturday, May 3, 2025 Data Structure 23

  24. Declaration #define ROWS 3 #define COLS 5 int table[ROWS][COLS]; Saturday, May 3, 2025 Data Structure 24

  25. for (int i=0; i < ROWS; i++) { for (int j=0; j < COLS; j++ ) { cout<<" x[%d][%d]: %d", i, j, x[i][j]; } cout<<"\n ; } 2D Arrays often require nested loops two variables Saturday, May 3, 2025 Data Structure 25

  26. Table A = { {13, 22, 9, 23}, {17, 5, 24, 31, 55}, {4, 19, 29, 41, 61} }; 13 17 4 22 5 19 9 23 31 41 ? 55 61 24 29 1 6 11 2 7 3 8 4 9 5 10 ? Table B = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; 12 13 14 Saturday, May 3, 2025 Data Structure 26

  27. USING CHARACTER ARRAY STRINGS In C++ a character variable can hold a single character value, such as A or $ . Single character values are always expressed within single quotation marks. In C++, if you want to express multiple character values as a constant, such as a first name or a book title, you use double quotation marks. A C++ value expressed within double quotation marks is commonly called a string, or a literal string. Saturday, May 3, 2025 Data Structure 27

  28. String When you want to store related characters that are used together, such as someone s name, then the characters constitute a string. You also can store the individual characters of a string in an array. However, C++ programmers do not refer to an array of characters as a string unless the last usable character in the string is the null character. The null character is represented by the combination \0 (backslash and zero), or by using the constant NULL. Saturday, May 3, 2025 Data Structure 28

  29. String Declaration If you want to declare a string named firstName and initialize it to Mary , each of the following statements provides the same result. char firstName[] = "Mary"; char firstName[] = {"Mary"}; char firstName[5] = "Mary"; char firstName[5] = {"Mary"}; char firstName[5] = {'M', 'a', 'r', 'y', '\0'}; Saturday, May 3, 2025 Data Structure 29

  30. String Declaration One way to accept multiple word names is to use the C++ getline()function. This function reads characters into an array up to a size limit, or until the newline character is encountered, whichever comes first. #include<iostream> int main)( { const int SIZE = 10; char name[SIZE]; cout << "Enter a name ; cin.getline(name, SIZE); cout << "You entered " << name << endl; return 0;} Saturday, May 3, 2025 Data Structure 30

  31. Manipulating Strings with Character You need to add the statement #include <strings.h> to the beginning of any program that uses a str... function . Saturday, May 3, 2025 Data Structure 31

  32. Manipulating Strings with Character Saturday, May 3, 2025 Data Structure 32

  33. Example //// Concatenate - concatenate two strings #include <iostream.h> #include <strings.h> int main(){ char szString1[256]; cout << Enter string #1: ; cin >> szString1; char szString2[128]; cout << Enter string# 2: ; cin >> szString2; char szString[260]; strncpy(szString, szString1,128); strncat(szString, - ,4); strncat(szString, szString2, 128); cout << \n << szString<< \n ; return 0;} Saturday, May 3, 2025 C++ Programming Language 33

More Related Content