Transcript Week 5

4.
Fourth step for Learning
C++ Programming
ㅎㅎ
• Two functions
• Recursive function
• Call by value
• Call by reference
• Array
• 2-D Array
• Array Searching
Writing a function
You have decide on what the function will look like:
Return type
Name
Types of parameters (number of parameters)
You have to write the body (the actual code).
2
[ Practice 01 Two functions ]
3
[ Explain 01 Two functions ]
4
[ Practice 02 Recursive function ]
5
[ Explain 02 Recursive function ]
6
[ Practice 03 Call by value ]
7
[ Explain 03 Call by value ]
①
③
②
8
[ Practice 04 Call by reference ]
9
[ Practice 04 Call by reference ]
①
③
②
10
C++ Arrays
An array is a sequence of consecutive memory
elements.
The contents of all elements are of the same
type.
Could be an array of int, double, char, …
We can refer to individual elements by giving the
position number (index) of the element in the
array.
11
Memory and Arrays
4 bytes
Each int is 4 bytes
•foo[0]
•int foo[6];
•foo[1]
•foo[5]
12
C++ Arrays indexing start at 0 !!!!!!!
The first element is the 0th element!
If you declare an array of n elements,
the last one is number n-1.
If you try to access element number n
it is an error!
13
Array Subscripts
The element numbers are called
subscripts.
foo[i]
• A subscript can be any integer
expression:
• These are all valid subscripts:
foo[17] foo[i+3] foo[a+b+c]
14
Initialization Rules for Arrays
Ο1. int cards[4] = {3, 6, 8, 10};
//valid
Ο2. int hand[4] = {};
//valid
3. hand[4];
X
//invalid
4. float hotelTips[5] = {5.0,
O
2.5};
//valid - hotelTips[0] = 5.0,
- hotelTips[1] = 2.5
Ο5. long totals[500] = {0};
//valid
Ο6. short things[] = {1, 5, 3, 8};
//valid
15
[ Practice 05 Array ]
16
[ Explain 05 Array ]
index→
0 1 2
index → 0
1
2
17
[ Practice 06 Array 2 ]
18
[ Explain 06 Array 2 ]
19
2-D Array: int A[3][4]
Col 0
Col 1
Col 2
Col 3
Row 0
A[0][0]
A[0][1]
A[0][2]
A[0][3]
Row 1
A[1][0]
A[1][1]
A[1][2]
A[1][3]
Row 2
A[2][0]
A[2][1]
A[2][2]
A[2][3]
20
2-D Array: int A[3][4] Memory Organization
•A[0]
•char A[4][3];
•A is an array of size
4.
•Each element of A is
an array of 3 chars
•A[1]
•A[2]
•A[3]
{
{
{
{
•A[0][0]
•A[0][1]
•A[0][2]
•A[1][0]
•A[1][1]
•A[1][2]
•A[2][0]
•A[2][1]
•A[2][2]
•A[3][0]
•A[3][1]
•A[3][2]
21
[ Practice 07 2-D Array ]
22
[ Expain 07 2-D Array ]
23
[ Practice 08 Array Searching ]
24
[ Explain 08 Array Searching ]
25
Bubble-Sort description
The index j in the inner loop travels up the array,
comparing adjacent entries in the array
(at j and j+1), while the outer loop causes the inner
loop to make repeated passes through the array.
After the first pass, the largest element is guaranteed
to be at the end of the array, after the second pass,
the second largest element is in position, and so on.
26
[ Practice 09 Bubble Sort ]
27
[ Explain 09 Bubble Sort ]
28
Thank you