Programming Fundamentals Lec 07
Programming Fundamentals Lec 07
Fundamentals
Lecture 07
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
0 1 2 3 4 5
*Programming Fundamentals
Array
How to Refer Array Elements
*We can reference array elements by using the array’s subscript. The
first element has a subscript of 0. The last element in an array of
length n has a subscript of n-1.
*When we write a program, we refer to an individual array element
using indexing.
*To index a subscript, use the array name and the subscript in a pair
of square brackets:
a[12];
Declaration Examples
Subscripting
*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.
Subscripting
Ar[3] = 1; 1 --
int x = Ar[3];
-- -- --
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]
*Programming Fundamentals
Array
To declare an array, define the variable type, specify the name of the
array followed by square brackets and specify the number of
elements it should store:
string cars[4];
To insert values to it:
* int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};
*Programming Fundamentals
2 Dimensional Array - (2D * { 40, 41 }
Arrays) * };
* Printing a 2-D array: * int i,j;
* #include<iostream> cout<<"Printing a 2D Array:\
n";
* using namespace std;
* for(i=0;i<4;i++)
* main( )
* {
* {
* for(j=0;j<2;j++)
* int arr[4][2] = {
* { cout<<"\
* { 10, 11 }, t"<<arr[i][j]; }
* { 20, 21 }, cout<<endl; }
* { 30, 31 }, * }
*Programming Fundamentals
Structures
* Structure is a collection of variables of different data types under
a single name.