Array and Pointer - 2
Array and Pointer - 2
Session #2
1 One-dimensional arrays
OUTLINE
2 Two-dimensional arrays
3 Addresses and Pointers
4 Pointer Arithmetic
1. One-dimensional arrays
int main() {
data_type array_name[size]; // Example 1: Initialization in the
declaration
int temp1[5];
temp1[5] = {98, 87, 92, 79, 85};
return 0;
}
…ctd
#include <iostream>
int main()
{
int temp[5] = {10, 12, 5, 8, 4};
int sum = 0;
for (int i=0; i<5; i++){
sum = sum + temp[i];
}
cout<<"The sum is: "<<sum<<endl;
return 0;
}
Input and Output of Array Values
}
…ctd
#include <iostream> // Output values of the array
cout << "Outputting array values:" <<
using namespace std; endl;
for (int i = 0; i < size; i++) {
int main() { cout << "Element " << i << ": " <<
const int size = 5; // You can change the size of the myArray[i] << endl;
array as needed }
int myArray[size];
return 0;
// Input values into the array }
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; i++) {
cout << "Enter value for element " << i << ": ";
cin >> myArray[i];
}
…ctd
Enter 5 integers:
Enter value for element 0: 4
OUTPUT Enter value for element 1: 5
Enter value for element 2: 6
Enter value for element 3: 5
Enter value for element 4: 2
Outputting array values:
Element 0: 4
Element 1: 5
Element 2: 6
Element 3: 5
Element 4: 2
Example: find maximum value in array
#include <iostream>
int main() {
const int size = 5;
Result:
int myArray[size] = {42, 17, 89, 56, 23};
int maxVal = myArray[0];
for (int i = 1; i < size; ++i) {
if (myArray[i] > maxVal) {
maxVal = myArray[i];
}
}
cout << "Result " << maxVal << endl;
return 0;
}
2. Two-dimensional arrays
int x = 10;
cout<<"Address of x: " << &x << endl;
…cont
int *ptr;
// Declaration of an integer pointer
cont…
int y = 20;
// Initializing the pointer with the address of
variable y
int *ptr = &y;
cont…
OUTPUT
❖ Array Names as Pointers
Example:
#include <iostream>
return 0;
}
…ctd
Element 0: 10
OUTPUT Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
4. Pointer Arithmetic
0
15
int sum = 0;
:
ts
for (int i = 0; i < size; ++i) {
en
em
sum += *ptr; // Add the value at the current memory location to the
el
sum
y
ra
ptr++; // Move to the next element in the array
ar
}
of
m
// Output the sum
Su
cout << "Sum of array elements: " << sum << endl;
return 0;
}
…cont
● A structure is a user-defined
data type.
● Declared using the struct
keyword.
Creating Structure
Instances
● Mistake: Accessing
uninitialized members.
● Solution: Always initialize
structure members.