Q:

C++ program | Different ways to print array elements

belongs to collection: C++ programs on various topics

0

C++ program | Different ways to print array elements

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ template program with arrays... >>
<< C++ | Create an object of a class and access class...