You are on page 1of 10

Lecture 22: Arrays

Course: Programming For Engineers-1

Asma Ahmad

FAST, National University of Computer and Emerging Sciences, Islamabad


Motivation
 The ordinary variables are capable of
holding only one value at a time
 If you write second value the old value will
be over-written
 What if we want to store more than one
value at a time in a single variable
 Suppose we want to arrange the %age
marks obtained by 100 students in
ascending order
 We can make 100 variables……
 Or construct one variable capable of
storing all 100 values (Arrays)
Arrays
 Arrays are just like one-dimensional matix
 i.e; one column and many rows
 Or one row and many columns
3
4
10
15
16
Arrays
 When we declare variables arbitrary
memory locations are assigned to them
 Array
 Same type of elements at contiguous
location
 Same name and type

 To refer to an element, specify


 Array name and position number
Declaring Arrays
 Declaring arrays - specify:
 Name
 Typeof array
 Number of elements

int c[ 10 ];
float hi[ 3284 ];
 Declaring multiple arrays of same type
 Similar
format as other variables
 Example
int b[ 100 ], x[ 27 ];
Getting Values
 int MyArray[5];
cin>>MyArray[0];
cin>>MyArray[1] ;
cin>>MyArray[2] ;
cin>>MyArray[3] ;
cin>>MyArray[4] ;
 Or
for(int i = 0; i < 5; i++)
cin>>MyArray[i];
Examples Using Arrays
 Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
 If not enough initializers, rightmost elements become
0
 If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 };
 Sets all the elements to 0
 If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
5 initializers, therefore n is a 5 element array

You might also like