What is an array?
Array is an collection of similar type of data referenced under the same name .It is a non primitive (size is not fixed)data type . In an array it collects only same type of data .Array is an linear type of data structure. Elements are arranged in a sequence. If the array is integer then all element will be of integer type .If an array is char data type then all element will be char type. Each element can be accessed directly by only using its index.
There are two types of an Array
1-D Array
Declaration of an 1-D Array
Syntax :
Data_type array_name [size]; //C++
example :int a[7];
Data_type array_name[]=new data_type[size]; //JAVA
For example, int a[]=new int[5]; or int []a=new int[5]; in this example int is a data type of an array means only integer type of element can be stored in an array having name as a. the size of array is 5 means it contains 5 element . and indexing of element starts from 0 and the last index of an array is 4 . we represent each index as a[0],a[1],a[2],a[3],a[4],a[5]. if the size of an array is n then the last index will be array_name[n-1].
How to store the data.
example :
int []marks=int[3]; // we can also declare as : int []marks={98,89,88};
marks[0]=98;
marks[1]=89;
marks[2]=88;
System.out.println(marks[2]); // the output will be 88.
If we not store the value in any of one index it will give a null or 0 value.
WAP (write a program) to input 5 element in 1-D array.
By using C++ programming language
#include<iostream.h>
#include<conio.h>
void main(){
clrscr(); // for clearing the screen .
int a[5] ,i;
cout<<"enter 5 elements"; // 23 34 45 56 67
for(i=0;i<5;i++){
cin>>a[i]; }
cout<<"array elements are"<<endl ; // endl for next line.
for(i=0;i<5;i++){
cout<<"element"<<i+1<<"="<<a[i] <<endl;
getch();
}
OUTPUT:
enter 5 elements
23 34 45 56 67
array elements are
element 1=23
element 2=34
element 3=45
element 4=56
element 5= 67
2-D Array
How to declare an 2-D Array
Syntax :
Data type array_name[size][size]; // C++
Data_type [ ] [ ] array_name = new Data_type[no of row ] [no of column]; //JAVA
How to store the data
Functions of an Array:
- Sorting ( sort() )
- length ( length() )