Академический Документы
Профессиональный Документы
Культура Документы
ARRAY &
STRUCTURES
4.1
ARRAY
( TATASUSUNAN)
Introduction
An array is a list of more than one variable with
the same name.
Most applications require the processing of multiple
data items that have common characteristics.
Each array element (individual data item) is
referred to by specifying the array name followed by
one or more subscripts / index (position of
elements).
Two type of array:
One dimensional
Multi dimensional
Introduction
Example 1:
name [0]
name [1]
name [2]
name [3]
name [4]
name [5]
Elements
Indexs/
subscripts
Size
Introduction
Elements
Example 2:
age [0]
20
age[1]
17
age [2]
22
age [3]
Elements
Size
(Only at declaration)
Indexs / Subscripts
(Start with 0 until n-1)
One Dimensional
Array
One-dimensional array is an array with one
subscript.
Syntax :
DataType arrayVariable[element-size];
Example:
One Dimensional
Array
Initialization :
You must assign an initial value to the array
elements before using them.
example :
float Height[3]={145.5,169.8,179.0};
145.5
169.8
Height [0]
179.0
Height [1]
Height [2]
Sem[0] Sem[1]
Sem[2] Sem[3]
Sem[4]
Sem[5]
One Dimensional
Array
Example 1 :
#include<iostream.h>
void main()
{ int quantity [4] = {5,7,12,32};
cout<<"\nInsert quantity:";
cin>>quantity[2];
cout<<"\nElement
cout<<"\nElement
cout<<"\nElement
cout<<"\nElement
}
in
in
in
in
index
index
index
index
0:"<<quantity[0];
1:"<<quantity[1];
2:"<<quantity[2];
3:"<<quantity[3];
One Dimensional
Array
Example 2 :
#include<iostream.h>
void main()
{
int num[10];
cout<<"Key in 5 integer number:\n";
for(int x=0; x<5; x++)
{
cin>>num[x];
}
cout<<"\nElements in num array :";
for(int y=0; y<5; y++)
{
cout<<num[y]<<"\t";
}
}
One Dimensional
Array
Example 3
#include<iostream.h>
int main()
{
int a;
int number[6];
for(a=0;a<6;a++)
{
number[a]=a+5;
cout<<"number["<<a<<"] is intialized with = <<number[a]<<endl;
}
return 0;
}
One Dimensional
Array
Example 4
#include <iostream.h>
int main ()
{
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
Two Dimensional
Array
Two Dimensional
Array
int a[3][4];
Row
Col
Two Dimensional
Array
Initialization :
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
a[0]
a[1]
a[2]
10
11
12
a[0]
a[1]
a[2]
a[3]
int b[4][3]={{2,5,6},{4,7,3},{1,6,7},{9,8,1}};
[0]
[1]
[2]
[3]
[0]
[1]
[2]
Two Dimensional
Array
Example 1:
#include<iostream.h>
void main()
{
int bil[3][4]={10,21,33,45,5,65,76,80,90,11,23,4};
for(int row=0;row<3;row++)
{
for(int col=0;col<4;col++)
{
cout<<bil[row][col]<<"\t";
}
cout<<endl;
}
}
Two Dimensional
Array
Example 2:
#include<iostream.h>
void main()
{ int BIL[3][5];
int r, c, count = 10;
for (r = 0; r < 3; r++)
{
for (c = 0; c < 5; c++)
{
BIL[r][c] = count+=5;
}
}
}