Professional Documents
Culture Documents
Introduction
.
Arrays
An array is a series of elements of the same type placed in
contiguous memory locations that can be identified by an
index
In C++, arrays may have from one to several dimensions
Eg: An array containing float values of five studentresults
Instead of declaring five variables of studentresult with their own data
type and identifier, we can declare them as an array of size five
The five float values are stored in contiguous memory
locations, and all five can be accessed using the same
identifier, with the proper index
2
One Dimensional Arrays
A one-dimensional array is a list of related variables.
Syntax:
dataType
arrayName[intSize];
Where intSize is an integer and determines the size of the array
3
Array Elements
The items in an array are called
elements
All the elements in an array are of the
same type; only the values vary
4
Example: array declaration and
initialization
float studenresult[5]; // array declaration
float studentresult[5]={80, 70, 90, 85, 96}; // array
initialization
float studentresult[5]={80,70,90}; // last two elements
initialized to zero
float studentresult[5]={ }; // all elements initialized to
zero
Assigning and Accessing array
values
Example: Assigning values
float studresult[5]; Displaying values
studresult[1]=70.5; cout<<Result:<<i+1<<studr
studresult[2]=75; esult[i];
studresult[3]=95; cout<<endl;
}
studresult[4]=90.5;
Example2: reading, averaging and printing in
array
double sales[10]; for(index=0;index<10;index++)
{
int index,maxIndex=0;
sum+= sales[index];
double largestSale, sum=0, avg; }
for(index=0;index<10;index++) if(sales[index]>sales[maxIndex])
maxIndex=index;
cin>>sales[index]; //reading
}