Arrays in CPP
Pointers
Definition: A pointer is a variable that holds the memory address of another object (typically another variable).
- Memory Address Example:
1000-> 'a'1004-> Variable 1 (e.g.,var1)1008-> Variable 2 (e.g.,var2)
Pointer Variable Declaration:
- Syntax:
<type> *<variable name> - Example:
int *a;// Pointer to an integer (initial value is garbage)double *b;// Pointer to a double (initial value is garbage)char *c;// Pointer to a char (initial value is garbage)
- Syntax:
References
- Definition: A reference is an alternative name (alias) for a variable or an object.
- Usage: Commonly used in parameter passing to functions.
- Reference Declaration Syntax:
<type> &<variable name> = <variable>- Example:
int j = 1;int &r = j;// Nowris an alias forj. Changingrchangesj.
Address Operator
- Address Operator:
&is a unary operator that returns the memory address of a variable.- Address Operator Usage:
int var1 = 5;int *pint = &var1;//pintpoints to the address ofvar1
Arrays
- Relationship with Pointers: An array name is a constant pointer to the first element of the array, meaning we cannot change the address the pointer refers to.
- Array Declaration:
- Syntax:
<type> <array name>[<length>]; - Example:
int a[10];int b[6] = {0, 2, 4, 8, 10, 12};// Initializes an array with specified values
- Syntax:
Array Access
- Accessing Array Elements:
- Example of Accessing an Element:
cout << a[3] << endl;// Outputs 7 ifacontains {1, 3, 5, 7, 9}
- Output Address of Array:
cout << "The address of a is: " << a << endl;
Traversing Arrays
- Traversing Example:
int a[5];
for (int i=0; i<5; i++) {
a[i] = i * 2 + 1;
}
for (int i=0; i<5; i++) {
cout << a[i] << " ";
}
- Output:
1 3 5 7 9
Searching in Arrays
- Search Position in Array:
int search = 7;
for (int i=0; i<5; i++) {
if (search == a[i]) {
cout << i << endl;
}
}
Example Output:
3- Finding Maximum in Array:
int max = a[0];
for (int i=1; i<5; i++) {
if (max < a[i]) max = a[i];
}
cout << max << endl; // Output: 9
- Finding Minimum in Array:
int min = a[0];
for (int i=1; i<5; i++) {
if (min > a[i]) min = a[i];
}
cout << min << endl; // Output: 1
Parallel Arrays
- Using Two Parallel Arrays:
int mark[5] = {71, 63, 55, 79, 90};
string name[5] = {"Amy", "Billy", "Cathy", "Debby", "Emily"};
for (int i=0; i<5; i++) {
cout << name[i] << "'s mark: " << mark[i] << endl;
}
- Example Output:
- Amy's mark: 71
- Billy's mark: 63
- Cathy's mark: 55
- Debby's mark: 79
- Emily's mark: 90
2D Arrays
- Declaring a 2D Array:
char board[3][3]={{'O','X','X'},{'O','X','O'},{'X','O','O'}};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
- Example Output:
O X X
O X O
X O O