Professional Documents
Culture Documents
1 Ghalib University
Table of contents
1. Arrays
2. Types of Arrays
2 Ghalib University
Arrays
An array is a sequence of objects of same data type.
or subscript.
variable name.
3 Ghalib University
Types of Arrays
1) One-dimensional arrays
2) Multi-dimensional arrays
4 Ghalib University
One-Dimensional Array
One-dimensional array is also called as a list or linear array.
-
-
-
-
-
temp[23] 15.3
5 Ghalib University
Declaration of One-Dimensional Array
Defining the name of array, its data type and total number of elements
locations is reserved in the computer memory for storing the data into
elements of the array.
DataType Array_name[n];
The index of the first element is 0 and of the last element is n-1.
The index value is written within square brackets after the array name.
as temp[n-1].
To entering data into array you can use either
cin object or assignments statements.
e.g cin>>a[1]; or a[1]=12;
To get or print data of array you can use
cout object or assignments statements.
e.g cout<<a[1]; or int b=a[1];
7 Ghalib University
Example 1
Write a program in C++ to enter integer type data into an array and
then to print the values in reverse order.
#include<iostream>
using namespace std;
int main(){
int abc[5];
for(int i=0;i<=4;i++){
cout<<"Enter value in element "<<i<<endl;
cin>>abc[i];
}for(int i=4;i>=0;i--){
cout<<"Value in a["<<i<<"]"<<abc[i]<<endl;
} return 0;
}
8 Ghalib University
Example 2
Write a program in C++ to input data into an array of 5 elements .
Calculate the sum and average of the elements and then print the sum and average on
the screen.
#include<iostream>
using namespace std;
int main(){
float abc[5],sum,avg;
for(int i=0;i<=4;i++){
cout<<"Enter value in element "<<i<<endl;
cin>>abc[i];
} sum=avg=0.0;
for(int i=4;i>=0;i--){
sum=sum+abc[i];
}avg=sum/5;
cout<<"Sum of array values = "<<sum<<endl;
cout<<"Average of array values = "<<avg;
10 Ghalib University
Initializing One-Dimensional Arrays
Like other variables, the values in the elements of an array can also be assigned when
The assigning of values to the elements of the array at the time of its declaration is
For example, to declare an array “temp” of type double with 5 elements, with values
Double temp[5]={66.3,77.7,99.2,63.9,59.3};
If the number of elements in an array is greater than the values in the list, then the
11 Ghalib University
Example 1
Write a program to initialize the values in an array and the print these values on the
screen.
#include<iostream>
using namespace std;
int main(){
12 Ghalib University
Any question…?????????????
13 Ghalib University