Home >Backend Development >C++ >How to Print Array Elements in C ?

How to Print Array Elements in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-14 17:21:02843browse

How to Print Array Elements in C  ?

Printing Array Elements in C

In C , printing arrays is straightforward and does not require any specific libraries. Here's how you can do it:

Looping Through Array Elements:

The most common method is to iterate over each element of the array and print its value using a loop. For instance:

int main() {
  // Initialize an array
  int myArray[] = {1, 2, 3, 4, 5};

  // Loop through the array and print each element
  for (int i = 0; i < 5; i++) {
    cout << myArray[i] << endl;
  }

  return 0;
}

Using iterators:

Another approach is to use iterators, which provide a way to traverse the elements of a container, including arrays. The syntax is:

int main() {
  // Initialize an array
  int myArray[] = {1, 2, 3, 4, 5};

  // Use an iterator to traverse the array
  for (int* it = myArray; it != myArray + 5; it++) {
    cout << *it << endl;
  }

  return 0;
}

Additional Considerations:

When printing arrays, keep in mind the following:

  • Make sure the index does not exceed the size of the array, as this may result in undefined behavior.
  • When using iterators, make sure to increment the iterator appropriately to avoid infinite loops.

The above is the detailed content of How to Print Array Elements in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn