You are on page 1of 9

Arrays in C++

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[0]=80.5; for(int i=0; i<5;i++)

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++) avg=sum/10; //average value of array


for(index=1;index<10;index++)
sales[index]=0.0; //initialization {

for(index=0;index<10;index++) if(sales[index]>sales[maxIndex])

maxIndex=index;
cin>>sales[index]; //reading
}

for(index=0;index<10;index++) largestSale=sales[maxIndex]; //max value in


cout<<sales[index];//printing array
Two-dimensional arrays
Two-dimensional arrays can be initialized when they are
declared:
double sales[3][4]={{500,600,300,700},
{4000,2000,500,300},
{500,6000,300,400}};
Elements of each row are enclosed within braces and
separated by commas
All rows are enclosed within braces
For number arrays, if all components of a row arent specified,
unspecified ones are set to 0.
Exercises
1. Write a C++ program that sorts for a given random
array of size n.
2. Write a C++ program that gives the transpose of a
given an nxn square matrix (apply multidimensional
array concept)

You might also like