How To Print Array In C++ Using For Loop

Printing an array is one of the most basic operations in C++ programming. An array is a collection of variables that share the same data type and are stored contiguously in memory. In this tutorial, we will learn how to print the contents of an array using a for loop.

Steps:

Step 1: Declare and initialize the array

In order to print the contents of an array, we must first declare and initialize the array. Here is an example of how to declare and initialize an array of integers:

Step 2: Use a for loop to print the array

Once we have declared and initialized our array, we can use a for loop to print its contents. Here is an example of how to use a for loop to print the contents of our example array:

Explanation:

This for loop iterates through each element of the array, from index 0 to index 4 (inclusive). The std::cout statement inside the loop prints the value of the current element of the array, followed by a space. This will print the entire array in a single line.

Step 3: Add a new line character

By default, the contents of the array will be printed on a single line. If we want to print each element on a new line, we can add a new line character after each print statement. Here is an example of how to modify our for loop to print each element on a new line:

Explanation:

The “\n” character is a special character that represents a new line. By adding this character to the end of the std::cout statement, we tell the program to print each element of the array on a new line.

Step 4: Test your program

Now that we have written our program, we can test it to make sure it works correctly. Here is the full program that declares, initializes, and prints the contents of our example array:

Output:

1
2
3
4
5

Explanation:

This program declares and initializes an array of integers called “myArray”. It then uses a for loop to print each element of the array on a new line.

Now you know how to print an array in C++ using a for loop!