Posted on Leave a comment

C++ Arrays

Spread the love
  • C++ includes arrays as other programming languages.
  • Vectors are more versatile/singular/powerful than arrays and it’s a recommendation to switch to vector as fast as possible.
  • Arrays stores fixed-size sequential collection of elements of the same type.
  • Arrays consists of  contiguous memory locations.
  • Lowest address correspond to the first element and the highest address to the last element of the array.

Declaring arrays

Type arrayName [ arraySize ]; //this is known as single-dimension array

  • Array size must be an integer greater than cero.

Example

int members[7]; //array of type integer with 7 elements

Initializing Arrays

  • Initialize an array single statement

int members[4] = {10, 23, 42, 7}; 

Array Index and Value
Array Index and Value

The number of elements inside the braces { } cannot be longer than the value between the square braces[ ]

#include <iostream>
#include <array>
using namespace std;
 
 
int main () {

   // create an array of 5 integers declaring it

int n[5];
 
   // initialize elements of array n to 10-14  
    // n[0]= 10;
    // n[1]= 11;    
    // n[2]= 12;   
    // n[3]= 13;
    // n[4]= 14; 

    for (int i=0; i< 5; i++){
        n[i] = 10+i;
    }
       

   // output each array element's value   

   //cout << n[3] << endl;    
   for (int o= 0; o<5; o++){
       cout << "array index -> " << o << ", value -> " << n[o] << endl;
   }             
 
 // get the array size
 cout << sizeof(n)/sizeof(n[0]) << " array size" <<endl;
   return 0;
}
Leave a Reply

Your email address will not be published. Required fields are marked *