Arrays
Arrays
ARRAYS
1
Contents
Declaration of Arrays, Initialization of
Arrays.
Example using Arrays
Passing Arrays to Function, Sorting arrays
Computing Mean, Mode, Median using
Array
Searching arrays
Multiple Scripted Arrays
2
Definition
An array is a collection of similar data elements
have the same data type.
The elements of array are stored in consecutive
memory locations and are referenced by an index
(also known as subscript).
Subscript indicates an ordinal number of the
elements counted from the beginning of the array.
3
Arrays in C++
Data types are of two kinds:
- simple data types (e.g. int, float, double, char)
- Structured data type: (e.g. arrays)
An array is a collection of two or more adjacent memory cells,
called array elements, that are associated with a particular symbolic
name.
In C++ each array has: name, data type, size
Several operations are allowed on the array: Read, Write, Search,
Sum, Min, Max, Sort, etc..
Arrays are of two kinds:
- Arrays of one-dimension
- Arrays of two-dimension
4
One-Dimensional Arrays
Declaration of one-dimension array
Syntax: a type a name [ size ] ; // uninitialized array
a type a name [ size ] = { initialization list } ;
where
a type is any data type;
a name is the name given to the array;
size represents the number of elements in the array.
initialization list is the list of initial values given to
the array. 5
Declaration of Arrays
For example ,
int x [ 3 ];
- This tells the compiler to associate 3 memory cells
with name x.
- These cells will be adjacent to each other in memory.
- Each element of array x contains a value of integer
type
More than one array can be declared on a line
Syntax:
a name [ index ]
- index is the subscript that is used to reference the
desired element.
The array indexing starts from 0 until the fixed size -1.
8
Accessing One-Dimensional Array
Array x in memory:
Index 0 1 2
Values 24 20 10
9
Arrays
Name of array (Note that all elements of
this array have the same name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
OUTPUT
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37 11
Examples Using Arrays
Strings
Arrays of characters
All strings end with null ('\0')
Examples
char string1[] = "hello";
Null character implicitly added
string1 has 6 elements
char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0’ };
Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
12
Examples Using Arrays
Input from keyboard
char string2[ 10 ];
cin >> string2;
Puts user input in string
Stops at first whitespace character
Printing strings
cout << string2 << endl;
Does not work for other array types
13
1
2 // Treating character arrays as strings
3 #include <iostream>
4
5 using namespace std;
6
7
8
9 int main()
10 {
11 char string1[ 20 ], string2[] = "string literal";
12
13 cout << "Enter a string: ";
14 cin >> string1;
15 cout << "string1 is: " << string1
16 << "\nstring2 is: " << string2;
17
17 return 0;
18
18 }
19
int myArray[ 24 ];
myFunction( myArray, 24 );
Array size usually passed, but not
required
15
Passing Arrays to Functions
Arrays passed-by-reference
Functions can modify original array data
Value of name of array is address of first element
Function knows where the array is stored
16
1. // Array passed by reference
2. #include <iostream>
3. using namespace std;
4. void read_array(int a[], int n) {
5. for (int i = 0; i < n; i++) {
6. cin >> a[i];
7. }
8. for (int i = 0; i < n; i++) {
9. cout << a[i] << endl;
10. }
11. }
12. int main() {
13. int a[20];
14. int n;
15. cout << "Enter the number of elements in array:" << endl;
16. cin >> n;
17. read_array(a, n);
18. return 0;
19. } OUTPUT
17
1. //array elements passed by value
2. #include <iostream>
3. using namespace std;
4. void display(int a[5]) {
5. cout << "Enter the marks:";
6. for (int i = 0; i < 5; i++) {
7. cin >> a[i];
8. }
9. cout << "Displaying marks:"<<endl;
10. for (int i = 0; i < 5; i++) {
11. cout << "Student "<< i + 1<<": " << a[i] << endl;
12. }
13. }
14. int main() {
15. int a[5] = { 88,76,90,61,69 };
16. for (int i = 0; i < 5; i++) {
OUTPUT
17. cout << a[i] << endl;
18. }
19. display(a);
20. return 0;
21. }
18
Sorting Arrays
Sorting data
Important computing application
Virtually every organization must sort some
data
Massive amounts must be sorted
Bubble sort (sinking sort)
Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical), no change
If decreasing order, elements exchanged
Original: 3 4 2 7 6
Pass 1: 3 2 4 6 7 (elements exchanged)
Pass 2: 2 3 4 6 7
Pass 3: 2 3 4 6 7 (no changes needed)
Pass 4: 2 3 4 6 7
Pass 5: 2 3 4 6 7
Small elements "bubble" to the top (like 2 in this
example)
20
Sorting Arrays
Swapping variables
int x = 3, y = 4;
y = x;
x = y;
What happened?
Need a temporary variable
Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3
21
Computing Mean, Median and Mode
Using Arrays
Mean
Average
Median
Number in middle of sorted list
1, 2, 3, 4, 5 (3 is median)
Mode
Number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
Arrays of Two-Dimensions
Syntax ( in C++ ):
atype aname [nrows] [ncolumns] ;
Example:
Array in diagram:
23
Arrays of Two-Dimensions
]0[ 5 2 9
]1[ 7 0 4
24
1. //Write C++ program that reads array A of size (2 x 3) and finds the sum of the elements in each
row.
2. #include <iostream>
3. using namespace std;
4. int main() {
5.
6. int i, j , Rsum = 0 ;
7. int B[2][3];
8. cout << "Enter 6 array elements: " ;
9. for ( i = 0 ; i < 2 ; i++ )
10. for ( j = 0 ; j < 3 ; j++)
11. cin >> B[i][j] ;
12. // Process the array now
13. for ( i = 0 ; i < 2 ; i++ )
14. {
15. for ( j = 0 ; j < 3 ; j++)
16. {
17. Rsum = Rsum + B[i][j];
18. }
19. cout << " sum of row no. " <<i<< " is " << Rsum<<endl;
20. Rsum = 0;
21. }
OUTPUT
22. return 0;
23. }
25
Searching Arrays
Search array for a key value
Linear search
Compare each element of array with key value
Start at one end, go to other
Useful for small and unsorted arrays
Inefficient
If search key not present, examines every element
26
The problem:
Write C++ program that searches for an integer in array of 10
integers. A proper message should be printed out.
The Analysis:
A given array of integer numbers is going to be searched in order
to find a given number.
Requirements:
Input: an integer number n, an array A of 10 integers
Output: a message “yes found” or “no not found” according to
whether the number is found or not.
27
1. // search element from array
2. #include <iostream>
3. using namespace std;
4. int main() {
5. int L[10];
6. int CurElem, SearchVal;
7. bool Found;
8. // ------------------------ Reading L ---------------------------
9. cout << "Enter 10 integers:";
10. for (CurElem = 0; CurElem < 10; CurElem++) {
11. cin >> L[CurElem];
12. }
13. cout << "Enter the number that you want to search for: ";
14. cin >> SearchVal;
15. Found = false;
28
18. for (CurElem = 0; CurElem < 10 && !Found; CurElem++) {
19. if (L[CurElem] == SearchVal)
20. {
21. Found = true; // Set Found to true if the number is found
22. }
23. }
24. if (Found == true)
25. cout << " Yes, the number is found ";
26. else
27. cout << " No, the number is not found";
28. return 0;
29. }
OUTPUT
29
1. //Example to find the largest number of array
2. #include <iostream>
3. using namespace std;
4. int main() {
5. int a[20];
6. int i, n;
7. int large = -1;
8. cout << "Enter the number of elements in array:" << endl;
9. cin >> n;
10. cout << "Enter elements of array" << endl;
11. for (i = 0; i < n; i++) {
12. cin >> a[i];
13. }
14. for (i = 0; i < n; i++) {
15. if (a[i] >= large) {
16. large= a[i];
17. }
18. } OUTPUT
19. cout << "The largest number of array=" << large << endl;
20. return 0;
21. }
30