Array Traversal Using Pointers

CCBeginner
Practice Now

Introduction

Pointer arithmetic is a powerful feature in C that allows you to manipulate memory addresses by adding or subtracting values. One of the most common applications of pointer arithmetic is array traversal. Using pointers, we can efficiently move through arrays in both forward and backward directions.

In this lab, you will learn how to create and initialize arrays, set up pointers to access array elements, and use pointer arithmetic to traverse arrays. This technique is fundamental in C programming and forms the basis for many advanced data manipulation operations.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c(("C")) -.-> c/PointersandMemoryGroup(["Pointers and Memory"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/CompoundTypesGroup -.-> c/arrays("Arrays") c/PointersandMemoryGroup -.-> c/pointers("Pointers") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/arrays -.-> lab-123301{{"Array Traversal Using Pointers"}} c/pointers -.-> lab-123301{{"Array Traversal Using Pointers"}} c/output -.-> lab-123301{{"Array Traversal Using Pointers"}} end

Creating a Basic C Program

Let us begin by creating a new C file in the VSCode editor. This file will contain our main program for array traversal using pointers.

  1. In the WebIDE, locate the Explorer panel on the left side and navigate to the ~/project directory.

  2. Right-click on the project folder and select "New File". Name the file main.c.

  3. Copy the following basic C program structure into the file:

#include <stdio.h>

int main() {
    printf("Array Traversal using Pointers\n");

    return 0;
}
  1. Save the file by pressing Ctrl+S or using File > Save from the menu.

  2. Let us compile and run this program to ensure everything is set up correctly. Open a terminal in the WebIDE by selecting Terminal > New Terminal from the menu, and run:

cd ~/project
gcc main.c -o main
./main

You should see the following output:

Array Traversal using Pointers

This confirms that your C development environment is working properly. In the next steps, we will modify this program to work with arrays and pointers.

Declaring and Initializing Arrays and Pointers

In this step, we will learn how to declare an array and a pointer, which are the fundamental components for array traversal using pointers.

Understanding Arrays and Pointers

An array in C is a collection of elements of the same type stored in contiguous memory locations. For example, an integer array with 5 elements will reserve space for 5 integers in memory, one after another.

A pointer is a variable that stores the memory address of another variable. We can use pointers to indirectly access the value stored at a particular memory address.

Let us modify our main.c file to include an array and a pointer:

#include <stdio.h>

int main() {
    printf("Array Traversal using Pointers\n\n");

    // Declare and initialize an array of 5 integers
    int arr[5] = {10, 20, 30, 40, 50};

    // Declare a pointer of integer type
    int *ptr;

    // Print the array elements using array notation
    printf("Array elements using array notation:\n");
    for(int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    return 0;
}

In this code:

  • We declared an integer array arr with 5 elements and initialized it with values 10, 20, 30, 40, and 50.
  • We declared an integer pointer ptr which will be used later to point to the array elements.
  • We printed the array elements using traditional array notation.

Compile and run the program to see the array elements:

gcc main.c -o main
./main

You should see the following output:

Array Traversal using Pointers

Array elements using array notation:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

In the next step, we will connect the pointer to the array and access array elements using the pointer.

Linking Pointers with Arrays and Forward Traversal

In this step, we will establish the connection between our pointer and the array, then use the pointer to traverse the array in the forward direction.

Connecting a Pointer to an Array

In C, an array name without an index represents the address of the first element of the array. This means we can assign this address directly to a pointer variable.

Let us modify our main.c file to link the pointer with the array and traverse it:

#include <stdio.h>

int main() {
    printf("Array Traversal using Pointers\n\n");

    // Declare and initialize an array of 5 integers
    int arr[5] = {10, 20, 30, 40, 50};

    // Declare a pointer of integer type
    int *ptr;

    // Assign the address of the first element of the array to the pointer
    ptr = arr;  // This is equivalent to ptr = &arr[0]

    // Print the array elements using array notation
    printf("Array elements using array notation:\n");
    for(int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    // Print the array elements using pointer notation
    printf("\nArray elements using pointer notation (forward traversal):\n");
    for(int i = 0; i < 5; i++) {
        printf("*(ptr + %d) = %d\n", i, *(ptr + i));
    }

    return 0;
}

In this updated code:

  • We assigned the address of the first element of the array arr to the pointer ptr.
  • We added a new loop that traverses the array using pointer arithmetic.
  • The expression *(ptr + i) accesses the value at the memory location ptr + i. When i is 0, this is the first element of the array; when i is 1, it's the second element, and so on.

Compile and run the program to see the results:

gcc main.c -o main
./main

You should see the following output:

Array Traversal using Pointers

Array elements using array notation:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Array elements using pointer notation (forward traversal):
*(ptr + 0) = 10
*(ptr + 1) = 20
*(ptr + 2) = 30
*(ptr + 3) = 40
*(ptr + 4) = 50

Notice that both methods produce the same output. This demonstrates that pointer arithmetic can be used to access array elements just like traditional array indexing.

Implementing Pointer Increment for Array Traversal

In the previous step, we accessed array elements using the expression *(ptr + i). While this works perfectly fine, C provides a more concise way to traverse an array using pointers: the increment operator (++).

When we increment a pointer, it moves to the next memory location based on the size of the data type it points to. For an integer pointer, incrementing it moves it to the next integer in memory.

Let us modify our main.c file to use pointer incrementation for array traversal:

#include <stdio.h>

int main() {
    printf("Array Traversal using Pointers\n\n");

    // Declare and initialize an array of 5 integers
    int arr[5] = {10, 20, 30, 40, 50};

    // Declare and initialize a pointer to the first element of the array
    int *ptr = arr;  // Same as ptr = &arr[0]

    // Print the array elements using pointer incrementation
    printf("Array elements using pointer incrementation:\n");
    for(int i = 0; i < 5; i++) {
        printf("*ptr = %d\n", *ptr);
        ptr++;  // Move the pointer to the next element
    }

    // Reset the pointer to the beginning of the array
    ptr = arr;

    // Print all elements in a single line using pointer incrementation
    printf("\nAll elements in a single line: ");
    for(int i = 0; i < 5; i++) {
        printf("%d ", *ptr++);  // Print and then increment
    }
    printf("\n");

    return 0;
}

In this updated code:

  • We initialize the pointer ptr directly when we declare it.
  • Inside the first loop, we use *ptr to access the current element and then use ptr++ to move to the next element.
  • After the first loop, we reset ptr to point to the beginning of the array again.
  • In the second loop, we use the post-increment operator *ptr++, which first uses the current value of ptr and then increments it.

Compile and run the program to see the results:

gcc main.c -o main
./main

You should see the following output:

Array Traversal using Pointers

Array elements using pointer incrementation:
*ptr = 10
*ptr = 20
*ptr = 30
*ptr = 40
*ptr = 50

All elements in a single line: 10 20 30 40 50

This demonstrates how to use pointer incrementation to traverse an array. The key point is that ptr++ automatically takes into account the size of the data type when it moves to the next element.

Implementing Backward Traversal using Pointer Decrement

In the previous steps, we traversed the array in the forward direction. Now, let us learn how to traverse the array in the reverse direction using pointer decrementation.

For backward traversal, we need to:

  1. Initialize the pointer to point to the last element of the array
  2. Decrement the pointer to move backwards through the array

Let us modify our main.c file to implement backward traversal:

#include <stdio.h>

int main() {
    printf("Array Traversal using Pointers\n\n");

    // Declare and initialize an array of 5 integers
    int arr[5] = {10, 20, 30, 40, 50};

    // Forward traversal using pointer increment
    int *ptr = arr;
    printf("Forward traversal using pointer increment:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", *ptr);
        ptr++;
    }
    printf("\n\n");

    // Backward traversal using pointer decrement
    // Point to the last element of the array
    ptr = &arr[4];  // or ptr = arr + 4

    printf("Backward traversal using pointer decrement:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", *ptr);
        ptr--;  // Move the pointer to the previous element
    }
    printf("\n\n");

    // Alternative approach: Start from the last element and decrement in the loop condition
    printf("Alternative backward traversal approach:\n");
    for(ptr = &arr[4]; ptr >= arr; ptr--) {
        printf("%d ", *ptr);
    }
    printf("\n");

    return 0;
}

In this updated code:

  • We first perform a forward traversal using pointer increment.
  • For backward traversal, we set the pointer to the last element of the array using ptr = &arr[4].
  • Inside the loop, we print the current element and then decrement the pointer using ptr--.
  • We also show an alternative method where the decrement is part of the for loop's update statement.

Compile and run the program to see the results:

gcc main.c -o main
./main

You should see the following output:

Array Traversal using Pointers

Forward traversal using pointer increment:
10 20 30 40 50

Backward traversal using pointer decrement:
50 40 30 20 10

Alternative backward traversal approach:
50 40 30 20 10

This demonstrates how to traverse an array in both forward and backward directions using pointer arithmetic. The ability to increment and decrement pointers makes it easy to move through arrays in any direction.

Summary

In this lab, you have learned how to traverse arrays using pointers in C programming. Here are the key concepts we covered:

  1. Array and Pointer Basics:

    • Arrays in C store elements in contiguous memory locations
    • Pointers store memory addresses and can be used to access those locations
  2. Pointer-Array Relationship:

    • The array name (without index) represents the address of the first element
    • We can assign this address to a pointer to establish a connection with the array
  3. Forward Traversal Techniques:

    • Using pointer arithmetic: *(ptr + i)
    • Using pointer incrementation: *ptr followed by ptr++
    • Combining dereference and increment: *ptr++
  4. Backward Traversal Techniques:

    • Initialize the pointer to the last element: ptr = &arr[size-1]
    • Use pointer decrementation: ptr-- to move backwards
    • Loop condition can check when pointer reaches the beginning of the array

Pointer arithmetic is a powerful feature in C that enables efficient memory manipulation and provides flexibility when working with arrays and other data structures. This technique forms the foundation for more advanced programming concepts such as dynamic memory allocation, linked lists, and other complex data structures.