Arrays in C++ part 1

Arrays in C++

An array is a data structure which allows a collective name to be given to a group of elements which all have the same type. An individual element of an array is identified by its own unique index.

An array is a fixed number of elements of the same type stored sequentially in memory.
Therefore, an integer array holds some number of integers, a character array holds some
number of characters, and so on. The size of the array is referred to as its dimension. To
declare an array in C++.

Basics of Arrays

How to declare an array in C++?

int array[5]; //declare array of size 5.
 

How to initiate arrays in C++?

//initialize position 0-4 with the numbers.
array[5]= {1,3,5,7,9}

//Remember arrays always start from position 0!

How to access positions into the array?

// print on the screen the value of position 5 in our array
cout<< "position 5 is:" << array[5]<<endl;

Length of an array in C++

There is no general way to find the length of an array. You must keep the size (both the maximum, and currently filled size) of the array in variables.


const int max_size = 365;
...
int array[max_size];

//Initialize all the elements to 0.
int array[20];
. . .
for (int i=0; i<20; i++) {
 array[i] = 0;
}

Here is examples using arrays in C++:

// Passing arrays and individual array elements to functions.
#include <iostream>
#include <iomanip>
using namespace std;

const int arraySize = 5;
//passing array to function.
void modifyArray( int array[], int size)
{
 // multiply each array element by 2
 for ( int k = 0; k < size; k++ )
 array[ k ] *= 2;
}// end of modifyArray

// modify specify element of the array
void modifyElement( int element )
{
 element=2*element;
 cout << "Value of element is: "<< element << endl;
} // end of modifyElement

int main()
{
 //declare and initialize myArray
 int myArray[ arraySize ] = { 0, 1, 2, 3, 4 };

//output original array elements
 cout<< "Array contains: ";
 for ( int i = 0; i < arraySize; i++ )
 cout << " "<< myArray[ i ];
 cout << endl;

//pass array a to modifyArray
 modifyArray( myArray, arraySize );

//output modified array elements and mul by 2
 cout << "The values after modified array are:";
 for ( int j = 0; j < arraySize; j++ )
 cout<<" "<< myArray[ j ];
 cout<<endl;

 cout << "Passing array element and multiply it by 2 is:" << myArray[3] << endl;
 modifyElement( myArray[3] );

 return 0;
} // end main

Program output


Array contains: 0 1 2 3 4
The values after modified array are: 0 2 4 6 8
Passing array element and multiply it by 2 is:6
Value of element is: 12

You must be logged in to post a comment.

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com
%d bloggers like this: