Array
Array:
In many applications, we need to
handle a large volume of data in terms of reading, processing and printing. To
process such large amount of data, we need a powerful data type that facilitate
efficient sorting, accessing and manipulation of data items. C++ supports a
derived data type known as array that can be used for such applications.
Array is an important part of almost
all programming language. It provides an powerful feature and can be used to
form complex data structures like stack and queue.
Definition:
An array can be
defined as a collection of homogeneous (similar type) elements.
An array is a fixed
size sequenced collection of elements of the same data type.
Declaration
of Array:
Syntax:
Data_type
array_name [size];
Data_type is type of elements
to be stored in the array, size specifies the number of elements to be
stored in the array. Size is also known as subscript and it must be an integer
value. The subscripts of an array starts from 0 onwards.
For Example:
int
num[10];
The
array will store ten integer values, its name is num. The first element
of an array have the subscript 0. To access particular element in array we give
subscript value like,
array_name[subscript];
For Example:
num[5];
The
first element in every array is the 0th element. Thus, the
first element of array num is referred to as num[ 0 ], the second
element of array num is referred to as num[ 1 ], the fifth
element of array num is referred
to as num[ 4 ], and, in general, the nth element of
array num is referred to as num[
n - 1 ] i.e. num[9].
The
size of an array can be determined as follows:
size=(upperbound – lowerbound) +1
For Example:
size of array num=( 9 – 0 ) + 1 = 10
Initializing
Array:
ANSI C allows
automatic array variable to be initialized in declarations by constants. These
initializing expression must be constant values. The constants are specified
within braces and separated by commas.
For Example:
int num[10]={12, 23, 25, 27, 30, 32,
89, 40};
char name[10]={‘P’, ’A’, ’T’, ’I’,
’L’};
Each
constant in the brace is assigned, in sequence, to an element of the array
starting with index 0. If there is not enough constants for whole array, the
remaining elements of array are initialized to 0.
Accessing Array Elements:
Individual
elements of an array can be accessed using following syntax:
Syntax:
array_name[index/subscript];
For Example:
num[3] = 5; //To
assign value to array
cin>>num[3];
// To read a particular
value
cou<<num[3]; // To write a
particular value
Program:
#include<iostream.h>
int
main()
{
int a[4];
int i;
for ( i = 0; i < 4; i++ )
{
a[i] = 0;
}
for ( i = 0; i < 4; i++ )
{
cout<<"a
= "<<a[i];
}
return 0;
}

Comments
Post a Comment