Koya Technical Institute Introduction To C++ Programming: Arrays
Koya Technical Institute Introduction To C++ Programming: Arrays
--
Arrays
1 --
-- --
Lecture 10 --
April 17, 2017
1
K.T.I 2017-2018 By M.Wshyar
Array Declaration?
- An array declaration is very similar to a variable
declaration. First a type is given for the elements of
the array, then an identifier for the array and within
square brackets, the number of elements in the array.
- Syntax of array:
2
K.T.I 2017-2018 By M.Wshyar
Example of Array Declaration?
- int score[ 5 ];
-This is like declaring 5 variables of type int:
score[0], score[1], … , score[4]
-int age[45]; // array age consist of 45 integers.
-float grade[3];
// array grade consists of 3 floating point value
- The variables making up the array are referred to as
- Indexed variables
- Subscripted variables
- Elements of the array
3
K.T.I 2017-2018 By M.Wshyar
Example of Array Declaration?
// array of 10 uninitialized ints
int Ar[10];
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
0 1 2 3 4 5
4
K.T.I 2017-2018 By M.Wshyar
Example of Array Declaration?
Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
To access an individual element we must apply a
subscript to array named Ar.
-A subscript is a bracketed expression.
- The expression in the brackets is known as the index.
- First element of array has index 0. Ar[0]
Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
Last element has an index one less than the size of
the array.
Ar[9]
Incorrect indexing is a common error.
5
K.T.I 2017-2018 By M.Wshyar
Initialization during declaration.
int Age[5] = {23, 5, 2, 19, 31};
Age[0]=23;
Age[1]=5;
Age[2]= 2;
Age[3] = 19;
Age[4] = 31;
6
K.T.I 2017-2018 By M.Wshyar
Subscripting
-- -- --
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
7
K.T.I 2017-2018 By M.Wshyar
Example
8
K.T.I 2017-2018 By M.Wshyar
Array and loops
Note: In the first “for loop” all elements are set to one. The
second “for loop” will print each element.
9
K.T.I 2017-2018 By M.Wshyar
Sum of the elements
10
K.T.I 2017-2018 By M.Wshyar
Average
11
K.T.I 2017-2018 By M.Wshyar
140
Any Questions
12
K.T.I 2017-2018 By M.Wshyar