Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.

Similar presentations


Presentation on theme: "Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program."— Presentation transcript:

1 Arrays

2 Related data items Collection of the same types of data. Static entity – Same size throughout program

3 Arrays Simple data type => data element contains a single value Array is a structured data-type (Collection of values): 15 84.35 ‘A’ 85 79 92 57 68 80

4 Array Fundamentals Arrays can hold a few data items or tens of thousands. The data items grouped in an array can be simple types such as int or float, or they can be user-defined types such as structures and objects.

5 Array Fundamentals Arrays are like structures in that they both group a number of items into a larger unit. A structure usually group items of different types but an array group items of the same type. More importantly, the items in a structure are accessed by name, while those in an array are accessed by an index number. Using an index number to specify an item allows easy access to a large number of items.

6 One Dimensional Array 31 34 38 36 30 29 26 int WeeklyTemp[7]; 0 1 2 3 4 5 6 WeeklyTemp 4 bytes cout<< WeeklyTemp[0]; cout<< WeeklyTemp[2]; cout<< WeeklyTemp[4];

7 Declaring Array Variables datatype arrayName[arraySize]; Example: double myList[10]; Array Size: MUST BE constant - constant literal - constant identifier int size = 4; double myList[size]; // Wrong const int size = 4; double myList[size]; // Correct double myList[20]; // Correct

8 Array Elements The items in an array are called elements (in contrast to the items in a structure, which are called members). All the elements in an array are of the same type; only the values vary.

9 Input/Output of Array elements int marks[3]; marks[0] = 76; marks[1] = 65; marks[2] = 27; cout<<marks[2]<<marks[0]<<marks[1];

10 Input/Output of Array elements – Using Loops int marks[5]; for(int i=0;i<5;i++) cin>>marks[i]; for(int j=0;j<5;j++) cout<<marks[j];

11 Indexed Variables Array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arraySize-1. For example: int marks[5];  Five int values: marks[0], marks[1], marks[2], marks[3], marks[4]

12 Using Indexed Variables An indexed variable can be used in the same way as a regular variable. For Example: myList[2] = myList[0] + myList[1];

13 Example Code

14 OUTPUT

15 No Bound Checking C++ does not check array’s boundary. So, accessing array elements using subscripts (index variable) beyond the boundary does not cause syntax errors, But the operating system might report a memory access violation (Compiler or System may crash!)

16 Arbitrary Initial Values When an array is created, its elements are assigned with arbitrary values. int marks[5]; for(int i=0;i<5;i++) cout<<marks[i];

17 Initializing an Array dataType arrayName[Size] = {value0, value1,..., valuek}; Example: int myList[4] = {32, 11, -6, 65};

18 Declaring, creating, initializing Using the Shorthand Notation int myList[4] = {32, 11, -6, 65};  This shorthand notation is equivalent to the following statements: int myList[4]; myList[0] = 32; myList[1] = 11; myList[2] = -6; myList[3] = 65;

19 Initializing Wrong way int myList[4]; myList = {32, 11, -6, 65};

20 Implicit Size C++ allows you to omit the array size For example, the following declaration is fine/correct: int myList[ ] = {63, 9, 3, 13}; C++ automatically figures out how many elements are in the array. int myList [ ]; // WRONG

21 Partial Initialization C++ allows you to initialize a part of the array. double myList[4] = {1.9, 4.65}; //correct - The above example assigns values 1.9, 4.65 to the first two elements of the array. - The other two elements will be set to zero. - Note: If an array is declared, but not initialized, all its elements will contain “garbage”, like all other local variables.

22 Copying Arrays Can you copy array using a syntax like this? int list[3]; int myList[3]; list = myList; // WRONG This is not allowed in C++. You have to copy individual elements from one array to the other as follows: for (int i = 0; i < 3; i++) { list[i] = myList[i]; }

23 Arrays of Structures

24

25

26 C-Strings or Character Arrays The elements of an array can be just about anything (any-datatype) Consider an array whose elements are all characters (char type) – Called a C-String

27 Declaration of C-Strings Similar to declaration of any array: char name[30]; // no initialization char title[20] = “Hello World"; //initialized at declaration with a string char chList[6] = {‘H', ‘e', ‘l', ‘l‘, ’o’}; //initialized with list of char values

28 Initializing Character Arrays char city[ ] = "Dallas";

29 Printing Character Array For a character array, it can be printed using one print statement. Character arrays are handled differently than other types of arrays For example: char city[ ] = "Dallas"; cout << city; // Correct int marks [ ] = {20,65,30}; cout << marks; // Wrong

30 Character Array (string) Input Declare strings 1 element bigger than planned size to allow for ‘\0’ (null character) char city[10]; cin>> city; //User enters Islamabad When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

31 Example-2: Reversing an Array Write a program to create an array of 10 elements, assign each element value (1 to 50). Print the array values. Then, Reverse the values stored in array. Output the final array values.

32 Two Dimensional Arrays

33 A two dimensional array stores data as a logical collection of rows and columns Each element of a two-dimensional array has a row position and a column position (indicated by two indexes) To access an element in a two-dimensional array, you must specify the name of the array followed by: – a row index – a column index

34 Declaration and Initialization Declaration of a two-dimensional array requires a row size and a column size A consecutive block of (row size)*(column size) memory locations are allocated. All array elements must be of the same type. Elements accessed by two offsets: a row offset and a column offset.

35 Example //Declaration int data[2][3]; ??? ??? row 0 row 1 col 0col 1col 2

36 Declaring Arrays datatype arrayName[rowSize][coulmnSize]; Example: double myList[2][4]; rowSize, and coulmnSize: MUST BE constant - constant literal - constant identifier

37 Declaring and Initializing Arrays int myList[3][2] = {{22,33}, {44,55}, {66,77}};  myList has 3 Rows and 2 coulmns in each row  In memory: 2233 4455 6677 012012 0 1 Coulmn Indexes Row Indexes

38 Initialization Examples int temp[4][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}}; int temp[][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

39 Example: Input Using cin Nested for loops are often used when inputting and assigning values to a two-dimensional array. //Declaration double table[10][10]; for (int i=0; i<10; ++i) //every row for (int j=0; j<10; ++j ) //every col cin >> table[i][j];

40 Example: Assignment //Declaration const int RSIZE=3; Const int CSIZE=2; double v[RSIZE][CSIZE]; for (int i=0; i<RSIZE; ++i)//every row for (int j=0; j<CSIZE; ++j )//every col v[i][j] = i+j; 01 12 23 V

41 Example: Computations Compute the average value of an matrix with n rows and m columns. double sum=0; double average; for (int i=0; i<n; i++)//every row for (int j=0; j<m; j++ )//every col sum += array[i][j]; average = sum / (n*m);

42 Passing Arrays to Functions

43 Higher-Dimensional Arrays - An array can be declared with multiple dimensions. 2 Dimensional3 Dimensional - Multiple dimensions get difficult to visualize graphically. double Coord[100][100][100]; Single value 1D Array 2D Array 3D Array

44 Larger-Dimension Arrays Arrays with more than two dimensions allowed in C++ but not commonly used Example: int response[4][10][6]; – First element is response[0][0][0] – Last element is response[3][9][5]

45 Common Programming Errors Forgetting to declare an array – Results in a compiler error message Using a subscript that references a nonexistent array element – For example, declaring array to be of size 20 and using a subscript value of 25 – Not detected by C++ compilers and will probably cause a runtime error

46 (Nested Loops) – Example Program -Write a program to that creates a matrix of size 5 by 5 (5 Columns, and 5 Rows). The program should ask the user to enter values in each matrix element. Then the program should display the left-diagonal elements of the matrix. Example: 1234 5678 9101112 13141516 Output 1,6,11,16,


Download ppt "Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program."

Similar presentations


Ads by Google