Example 4: Pointers in for-Loop

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.


Code Example

#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;
}

Explanation & Output

Code Breakdown:

  1. Declaring and Initializing Pointers:
    • 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]).
  2. Using Pointers in a for Loop (First Loop):
    • *(ptr + i) accesses the elements of the array using pointer arithmetic.
    • This avoids the need for indexing (numbers[i]).
  3. Modifying Array Elements Using Pointers (Second Loop):
    • *(ptr + i) += 5; increases each element’s value by 5.
  4. Using a Pointer Directly in a for Loop (Third Loop):
    • Instead of using an index (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.

Expected Output:

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.