How do I use arrays in C++?

C++Server Side ProgrammingProgramming

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. To use an array in C++, you'll need to declare it first, for example,

int arr[10];

This declares an array of type int of size 10. This can store 10 integers in contiguous memory. To Refer to any of its element, you need to use the array access operator and provide it the index of the element you want to access. The indexing in C++ array start from 0. So in the array arr, we have 10 elements with indices 0, 1, 2, ... 9. To access the third element, ie, the element at index 2, you'd write: arr[2].

You can access all the elements in a loop like −

#include<iostream>
using namespace std;

int main() {
   int arr[10];

   // Create a loop that starts from 0 and goes to 9
   for(int i = 0; i < 10; i++) {
      cin >> arr[i]; // Input the ith element
   }

   // Print the elements you took as input
   for(int i = 0; i < 10; i++) {
      cout << arr[i] << endl; // Input the ith element
   }
}

Output

This will give the output −

1
5
-6
45
12
9
-45
12
3
115
raja
Published on 28-Feb-2018 06:42:13
Advertisements