UNIT1 :
Introduction to Array
Adjectives of this unit
- What Is Array ?
- Advantage And Disadvantage Of Array .
- Types Of Array .
- Declaration Of Array .
- Example Of Array.
T.SUB: Abdulmalik A Alsarori
What Is Array
It is a collection of fixed number of elements
,wherein all of elements have the same data
type.
It is used to store multiple values in a single
variable.
Note:
- Consecutive group of memory locations that
all have the same type.
- The collection of data is indexed or
numbered, and at starts at 0 and the highest
element index is one less than total number
of elements in the array.
Advantage and disadvantage of array
Advantage of array :
- use of less line of code.
- easy access to all the elements.
- traversal through the array.
- sorting becomes easy.
disadvantage of array :
- allows a fixed number of elements.
Type of array
One dimensional array .
Two dimensional array.
Multidimensional array.
One dimensional array “ single array”
In this type of array, it stores elements in
a single dimension. And, In this array, a
single specification is required to describe
elements of the array.
Declaration of One Dimensional Array
To declare an array in C++, you need to
define
- The data type of elements in the array
- The name of the array
- The size of the array
Syntax:
Data_type Array_Name [size];
Note :
size of array is any positive integer or
constant variable.
Example
For Example:
define SIZE =7
int score[SIZE];
Suppose, we have array int score[7] as shown in below
figure:
Initializing One Dimensional Array
we can initialize one-dimensional array at compile
time and at run time.
Compile Time Initialization:
Arrays can be initialized at the time they are declared.
This is also known as compile-time initialization.
- int std[5]= {1,2,3,4,5}
1 2 3 4 5
std0 std1 std2 std 3 std4
- int std[]= {1,2,3,4,5}
1 2 3 4 5
std0 std1 std 2 std3 std4
Initializing One Dimensional Array
- int std [5]= {0}
0 0 0 0 0
std0 std1 std2 std3 std4
- int std[5]={1,2}
1 2 0 0 0
std0 std1 std2 std3 std4
Initializing One Dimensional Array
Run Time Initialization:
An array can be explicitly initialized at run
time. This approach is usually applied for
initializing large arrays.
example: int std[5];
for(int i=0, i<=4 ,i++)
cout<<“enter the element of array”<<i,
cin>> std[i];
Examples out put
#include<stream.h>
void main() {
int arr[5];
for(i = 0; i < 5; i++)
{
cout <<"Enter a[“ << i <<"]:", i);
cin>>arr[i];
}