0% found this document useful (0 votes)
22 views

5.0 Array

Computer programming

Uploaded by

al salam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

5.0 Array

Computer programming

Uploaded by

al salam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Array

Array
• A data structure used to store a collection of data of the same data
type that can be individually referenced by adding an index to a
unique identifier.
• Once defined, the size of an array is fixed and cannot increase to
accommodate more elements.
• The array indices start with 0. Meaning x[0] is the first element stored
at index 0.
• If the size of an array is n, the last element is stored at index (n-1). In
this example, x[5] is the last element.
Array

x0=0; x[0]=0;
x1=1; x[1]=1;
x2=2; x[2]=2;
x3=3; x[3]=3;
x4=4; x[4]=4;
x5=5; for(count=0; count<5; count++) { x[5]=5;
cout<<x[count];
}
Array Declaration & Initialization
• Syntax: dataType arrayName [ arraySize ];
dataType arrayName [ arraySize ]={ elem1, elem2, elem3..}

• The arraySize must be an integer constant greater than zero and type can be any valid
C++ data type.

int intArray[5];
int intArray[5] = {1, 2, 3, 4, 5};
int intArray[ ] = {1, 2, 3, 4, 5};
// intArray is an array variable which stores 5 integer values
// The number of values between braces { } can not be larger than the number of
// elements that we declare for the array between square brackets [ ]
Accessing Array
• An element is accessed by indexing the array name.
• Place the index of the element within square brackets after the name
of the array.

int intArray[ ] = {1, 2, 3, 4, 5};


int temp = intArray[4]; // stores the value 5 to temp
Accessing Arrays
1. int x[5];
2. for(int i=0; i<5; i++){
3. x[i] = i+2;
4. }
Accessing Arrays
1. int x[5]={1,2,3,4};
2. for(int i=0; i<5; i++){
3. if(x[i] != NULL){
4. cout<<x[i];
5. }
6. }
Arrays in functions
1. int main(){ 8. void printMsg(int arr[]){
2. int x[5]={1,2,3,4}; 9. for(int i=0; i<5; i++){
3. x[4] = 5; 10. if(arr[i] != NULL){
4. printMsg(x); 11. cout<<arr[i];
5. getch(); 12. }
6. return 0; 13. }
7. } 14. }

You might also like