Home » C++ programs

C++ program | Different ways to print array elements

In this program, we are going to learn how to print array elements in C++? We are using some of the ways (normal and pointer) to print the array elements.
Submitted by IncludeHelp, on December 22, 2019

Given an array and we have to print its elements using different ways.

Here, we are using the following ways,

  • Subscription notation (with array name)
  • Pointer/offset notation (with array name)
  • Pointer subscription notation (with pointer name)
  • Pointer/offset notation (with pointer name)

C++ program:

// Different ways of accessing array elements in C++

#include <iostream>
using namespace std;

int main(void)
{
    const int len = 5;
    int intArray[len] = { 100, 200, 300, 400, 500 };
    int* ptr;

    cout << "Array elements (Subscript Notation) : " << endl;
    for (int i = 0; i < len; i++)
        cout << "intArray[" << i << "] = " << intArray[i] << endl;

    cout << "\nArray elements (Pointer/Offset Notation): \n";
    for (int index = 0; index < len; index++)
        cout << "*(intArray + " << index << ") = " << *(intArray + index) << endl;

    ptr = intArray;
    cout << "\nArray elements (Pointer Subscript Notation): \n";
    for (int i = 0; i < len; i++)
        cout << "ptr[" << i << "] = " << ptr[i] << endl;

    cout << "\nArray elements (Pointer/Offset Notation): \n";
    for (int index = 0; index < len; index++)
        cout << "*(ptr + " << index << ") = " << *(ptr + index) << endl;

    cout << endl;

    return 0;
}

Output

Array elements (Subscript Notation) :
intArray[0] = 100
intArray[1] = 200
intArray[2] = 300
intArray[3] = 400
intArray[4] = 500

Array elements (Pointer/Offset Notation):
*(intArray + 0) = 100
*(intArray + 1) = 200
*(intArray + 2) = 300
*(intArray + 3) = 400
*(intArray + 4) = 500

Array elements (Pointer Subscript Notation):
ptr[0] = 100
ptr[1] = 200
ptr[2] = 300
ptr[3] = 400
ptr[4] = 500

Array elements (Pointer/Offset Notation):
*(ptr + 0) = 100
*(ptr + 1) = 200
*(ptr + 2) = 300
*(ptr + 3) = 400
*(ptr + 4) = 500


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.