ADVERTISEMENT
ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.