C++ Arrays and Loops

πŸ”πŸ“¦ C++ Arrays and Loops

In C++, arrays and loops are commonly used together to store, access, and process multiple values efficiently.
Below are clear examples showing how loops work with arrays.


1. Access Array Elements Using for Loop

int arr[] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {
cout << arr[i] << ” “;
}

Output:

10 20 30 40 50

2. Array Size Using sizeof

int arr[] = {5, 10, 15, 20};

int size = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < size; i++) {
cout << arr[i] << ” “;
}


3. User Input into Array (Using Loop)

int arr[5];

for (int i = 0; i < 5; i++) {
cin >> arr[i];
}


4. Sum of Array Elements

int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}

cout << sum;

Output:

15

5. Find Maximum Element in Array

int arr[] = {10, 45, 23, 8};
int max = arr[0];
for (int i = 1; i < 4; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

cout << max;


6. Reverse an Array Using Loop

int arr[] = {1, 2, 3, 4, 5};

for (int i = 4; i >= 0; i–) {
cout << arr[i] << ” “;
}


7. Range-Based for Loop (foreach)

int arr[] = {100, 200, 300};

for (int x : arr) {
cout << x << ” “;
}


8. Modify Array Elements Using Loop

int arr[] = {1, 2, 3};

for (int i = 0; i < 3; i++) {
arr[i] = arr[i] * 2;
}

for (int x : arr) {
cout << x << ” “;
}

Output:

2 4 6

9. 2D Array with Nested Loops

int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << ” “;
}
cout << endl;
}


10. Search an Element in Array

int arr[] = {5, 10, 15, 20};
int key = 15;
bool found = false;
for (int i = 0; i < 4; i++) {
if (arr[i] == key) {
found = true;
break;
}
}

cout << found;


Common Mistake ❌

arr[5]; // out of bounds

⚠️ Leads to undefined behavior.


Key Points

  • Loops make array processing easy and efficient

  • Index starts from 0

  • Use sizeof to calculate array length

  • Nested loops are used for 2D arrays

  • Range-based loops are cleaner and safer

You may also like...