Array Traversal Using Pointers

CCBeginner
Practice Now

Introduction

Pointer arithmetic refers to the addition or subtraction of a pointer by an integer value. Using pointers, we can traverse an array in both forward and backward direction. In this lab, we will learn how to traverse an array using pointers in C language.

Create a new C file

Let us create a new C file called main.c in the ~/project/ directory.

#include<stdio.h>

int main() {

    return 0;
}

Declare an array and a pointer

#include<stdio.h>

int main() {
    int arr[5] = {1,2,3,4,5}; // Declare an array of size 5
    int *p; // Declare a pointer of integer type
    return 0;
}

Point the pointer to the first element of the array

#include<stdio.h>

int main() {
    int arr[5] = {1,2,3,4,5};
    int *p;
    p = arr; // Point the pointer to the first element of the array
    return 0;
}

Traverse the array using pointer increment

#include<stdio.h>

int main() {
    int arr[5] = {1,2,3,4,5};
    int *p;
    p = arr;
    for(int i=0; i<5; i++) {
        printf("%d ",*p); // Print the value pointed by the pointer
        p++; // Move the pointer to the next element
    }
    return 0;
}

Traverse the array using pointer decrement

#include<stdio.h>

int main() {
    int arr[5] = {1,2,3,4,5};
    int *p;
    p = &arr[4]; // Point the pointer to the last element of the array
    for(int i=4; i>=0; i--) {
        printf("%d ",*p);
        p--; // Move the pointer to the previous element
    }
    return 0;
}

Summary

In this lab, we have learned how to traverse an array using pointers in C programming language. We used pointer increment and decrement to traverse the array in forward and backward direction respectively.

Other C Tutorials you may like