What is an Array:
An array is “a group of elements forming a complete unit
The following are characteristics of an array:
- An array is a collection of elements.
- All elements contained in an array are of the same kind.
- This collection forms a complete set.
Declaring and Initializing static arrays
Syntax:
element-type array-name [number of elements] = {optional initial values}
Example:
int MyNumber[] ={1,2,3,4,5}
int MyNumber[4] = {32, 87, 120, 247};
int MyNumber[4] = {0}; // initialize all integers to 0
Accessing data stored in an Array
#include <iostream>
using namespace std;
int main (){
int Arr[4] = {32, 87, 120, 247};
cout << “First element at index 0: “ << Arr[0] << endl; //32
cout << “Second element at index 1: “ << Arr[1] << endl; //87
cout << “Third element at index 2: “ << Arr[2] << endl; //120
cout << “Fourth element at index 3: “ << Arr[3] << endl; //247
return 0;
}
Modifying Data Stored in an Array
#include <iostream>
using namespace std;
int main(){
const int length = 4;
int Arr [length] = {0};
cout << “Enter index of the element to be changed: “;
int nElementIndex = 0;
cin >> nElementIndex;
cout << “Enter new value: “;
cin >> Arr [nElementIndex];
cout << “First element at index 0: “ << Arr [0] << endl;
cout << “Second element at index 1: “ << Arr [1] << endl;
cout << “Third element at index 2: “ << Arr [2] << endl;
cout << “Fourth element at index 3: “ << Arr [3] << endl;
return 0;
}
Example:
#include<iostream>
int main(){
int a[100],n;
// Input n
do{
cout<<"\n n=
"; cin>>n;
if(n<1||n>100) cout<<"\n Input n again !";
}while (n<1||n>100);
// input array
for (int i=0; i<n;i++){
cout<<"\n
a["<<i<<"]= ";
cin>>a[i];
}
// Print array
cout<<"\n Print values of array:
";
for (i=0;i<n;i++)
cout<<a[i]<<",
";
getch();
return 0;
}