Lecture_4
.pdf
Note use of const keyword. Only const variables can specify array sizes.
|
Element |
Value |
|
0 |
2 |
|
|
|
1 |
4 |
|
|
|
||
|
2 |
6 |
|
|
3 |
8 |
|
|
4 |
10 |
|
|
5 |
12 |
|
|
6 |
14 |
|
|
7 |
16 |
|
|
8 |
18 |
|
|
9 |
20 |
|
|
|
|
|
Total of array element values is 55 |
12 |
12 3 5 -9 8 4 10 0 7 11
Total of array elements values is 51
13
Strings as 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' |
14 |
|
Strings as Arrays |
|
• |
Input from keyboard |
|
|
char string2[ 10 ]; |
|
|
cin >> string2; |
|
|
– Puts user input in string |
|
|
• Stops at first whitespace character |
|
|
• Adds null character |
|
|
– If too much text entered, data written beyond |
|
|
array |
|
• |
• We want to avoid this |
|
Printing strings |
|
|
|
– cout << string2 << endl; |
|
|
• Does not work for other array types |
|
|
– Characters printed until null found |
15 |
Enter the string "hello there": hello there string1 is: hello
string2 is: string literal
string1 with spaces between characters is: h e l l o
string1 is: there
Examples of reading
strings from the keyboard
and printing them out.
Can access the characters in a string using array notation. The loop ends when the null character is found.
16
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
17
– Repeat these steps for every element
Bubble sort
Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one).
Sorting Arrays
•Example:
–Go left to right, and exchange elements as necessary
•One pass for each element
–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) |
19 |
|
Sorting Arrays
• Swapping variables
int x = 3, y = 4; y = x;
x = y;
•What happened?
–Both x and y are 3!
–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 |
20 |
