Pointers can be effectively used within for
loops in C++ to traverse arrays and other data structures efficiently. Using pointers in a loop can make the code more flexible and, in some cases, improve performance by avoiding unnecessary indexing operations.
This example demonstrates how pointers can be used in a for
loop to iterate through an array, access and modify its elements directly.
#include <iostream>
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Declare an array of integers
int* ptr = numbers; // Pointer pointing to the first element of the array
// Using pointer in a for-loop to iterate over the array
std::cout << "Array values using pointers: ";
for (int i = 0; i < 5; i++) {
std::cout << *(ptr + i) << " "; // Dereferencing pointer to access values
}
std::cout << std::endl;
// Modifying array values using pointers
for (int i = 0; i < 5; i++) {
*(ptr + i) += 5; // Increment each value by 5
}
// Using pointer arithmetic to print modified values
std::cout << "Modified array values: ";
for (int* p = numbers; p < numbers + 5; p++) {
std::cout << *p << " "; // Access values using pointer
}
std::cout << std::endl;
return 0;
}
int numbers[] = {10, 20, 30, 40, 50};
→ Creates an integer array.int* ptr = numbers;
→ A pointer ptr
is initialized to point to the first element of the array (numbers[0]
).for
Loop (First Loop):*(ptr + i)
accesses the elements of the array using pointer arithmetic.numbers[i]
).*(ptr + i) += 5;
increases each element’s value by 5
.for
Loop (Third Loop):i
), we use a pointer (p
) that starts at numbers
and iterates until p < numbers + 5
.*p
accesses the value at the pointer’s current position.Array values using pointers: 10 20 30 40 50
Modified array values: 15 25 35 45 55
This example shows how pointers can be used efficiently in loops to traverse and modify an array without relying on traditional indexing. This approach is particularly useful in scenarios like linked lists and dynamic memory operations.