What data type should all the elements in an array be?
What is an Array?
Array : Array is an collection of similar type of data referenced under the same name. It is a linear data structure. indexing of an Array starts from 0 and ends on (n - 1) .where n=size of an Array. Each element can be accessed directly by only using its index.
We declare an Array as Syntax: Data type array_name[ size of an array];
The data type should be same for all the elements in an array. example : int ,float ,string ,char etc. for example the data type of an Array is float then it can only store the float values.
If we declare an Array of size 5 of float type . It can be written as
float a[ 5 ]; //here a is the name of an Array .
indexing will be start from 0 and ends on 4 .
the elements of an Array is as shown.
a[0]=4.5;
a[1]=2.0;
a[2]=1.1;
a[3]=7.8;
a[4]=8.8;
As per above example we can only store the float value if we declare an Array as float data type. we can't add a int value or char value . we can store only the values , which declared as data type.
Let's understand with one more example:
We declare an Array of String data type . String is an collection of character closed under the double quotes . It takes one extra byte. It can be written as ,
String name[5]; // here name is the name of an Array .
Indexing will be start from 0 and ends on 4 .
The elements of an Array is as shown.
name[0]="Samir";
name[1]="Sumit";
name[2]="Rekha";
name[3]="Raj";
name[4]="Ram";
We can only store the String value , if we declare an Array as String data type. we can't add a int value or char value . we can store only the values , which declared as data type.
What about char data type ? what happened when we select the data type as char . Let's Understand.
We declare an Array of char data type . character closed under the single quotes . It takes one byte. It can be written as ,
Char alphabet[5]; // here alphabet is the name of an Array .
Indexing will be start from 0 and ends on 4 .
The elements of an Array is as shown.
name[0]='s';
name[1]='u';
name[2]='e';
name[3]='a';
name[4]='m';
We can only store the char value , if we declare an Array as char data type. we can't add a int value or String value . we can store only the values , which declared as data type.
As we see above all the three example , it confirmed that the same data type should all elements in an array have.
Tags:
data structure