In this tutorial, we will explore the concept of arrays. We will learn how to read the array and print it. Here we will provide the comprehensive information from basics.
Understanding arrays in C++
An array is the fundamental data structure used in C++ to store the elements which are of same data type. Essentially, it is collection of same types of values surrounded by curly braces. For example, arrays can hold integers, floats, strings, characters, and more. We use arrays; consequently, they allow for efficient storage and handling of multiple values under a single variable.
Array of Integers: {1,2,3,4,5} Array of Strings: {"One","Two","Three","Four"}
Methods to Read and Print arrays
-
Using Loops
-
Using Functions
1. Using Loops
The most common method for reading and printing an array is to use loop.
#include <iostream> using namespace std; int main() { // Declaring the array with size 5 int arr[5]; // Reading the array from the user for (int i = 0; i < 5; i++) { cout << "Enter element " << (i + 1) << ": "; cin >> arr[i]; // Storing value at index i } cout << "Printing the array elements: " << endl; // Printing the array elements for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }
Input:
Enter element 1: 2 Enter element 1: 5 Enter element 1: 6 Enter element 1: 8 Enter element 1: 7
Output:
Printing the array elements: 2 5 6 8 7
Explanation:
In this program, we use a ‘for’ loop where the index ‘i’ moves from 0 to 4; consequently, it stores the input values at the corresponding indices of the array.
When printing, the program first traverses the array and then displays the value at each index ‘i’.
2. Using Functions
To enhance the organization of code, we can use separate functions for reading the array and for printing its elements.
#include <iostream> using namespace std; // Function to read array elements void readArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << "Enter element " << (i + 1) << ": "; cin >> arr[i]; //Storing element at index i } } // Function to print array elements void printArray(int arr[], int size) { cout << "Array elements: "<<endl; for (int i = 0; i < size; i++) { cout << arr[i] << " "; } } int main() { int size; cout<<"Enter size of array: "; cin>>size; int arr[size]; // Defining array readArray(arr, size); // Function call to read array printArray(arr, size); // Function call to write array return 0; }
Input:
Enter size of array: 3 Enter element 1: 5 Enter element 2: 6 Enter element 3: 8
Output:
Array Elements: 5 6 8
Explanation:
In this program, ‘readArray’ function asks user to enter array elements and simultaneously store them into array. After that, the ‘printArray’ function then displays the values of the array. Using functions, therefore, increases the organization and readability of the program.