0% found this document useful (0 votes)
11 views34 pages

Week 08

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views34 pages

Week 08

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CE-116

COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]

Computer Engineering Department


WEEK NO:08

2
Array index out of bounds
• An array is a series of elements, each accessed by an index of
that array.
If I say
• int arr[5] = { 20, 30, 40, 50, 60 };
• arr has 5 elements in it, accessed through arr[0] to arr[4].
• The first element, 20, is access through arr[0].
• The second element, 30, is accessed through arr[1].
• The third element, 40, is accessed through arr[2].
• The fourth element, 50, is accessed through arr[3].
• The last (5th) element, 60, is accessed through arr[4].

3
Array index out of bounds
• If an index is "out of bounds", it means that it would be attempting to access an
array element that doesn't exist.
For example,
int arr[5] = { 20, 30, 40, 50, 60 }; // declare an array of length 5.
arr[5] = 70; // 5 here is out of bounds, because valid array indices only go from 0 to 4
arr[-1] = 42; // -1 here is out of bounds, because arrays start at index 0.

• If you were to attempt to access an out-of-bounds index, you invoke undefined


behavior, and your program is wrong.
• The best way to check for out-of-bounds array indices is to not let it happen in the
first place. Design clear logic in your loops so that it never happens.
• In C++, there is no guard against indices that are out of bounds
4
Array index out of bounds
• The output of the above
int main()
program is as follows.
{
The elements of array :
int arr[] = {1,2,3,4,5};
1
cout<<"The elements of array : ");
2
for(int i = 0; i<6; i++)
3
cout<<“\n“<<arr[i]<<endl;
4
return 0;
5
}
32765
5
Array index out of bounds

• Now let us understand the above program.


• The array arr has assigned values only till subscript 4. So
when the array elements are printed, arr[5] results in a
garbage value.

6
Arrays in memory

• Recall simple variables:


• Allocated memory in an "address"
• Array declarations allocate memory for entire array
• Sequentially-allocated
• Means addresses allocated "back-to-back"
• Allows indexing calculations
• Simple "addition" from array beginning (index 0)

7
Arrays in memory

8
Range-based for loop statement

• The C++ language introduced a new concept of the range-based for


loop in C++.
• which is much better than the regular For loop.
• A range-based for loop does not require large coding to implement for
loop iteration. It is a sequential iterator that iterated each element of
the container over a range (from beginning to end).
Syntax
for (range_declaration : range_expression ) loop statement

9
Range-based for loop statement

• range_declaration: It is used to declare a variable whose type is the


same as the types of the collected elements represented by the
range_expression or reference to that type.
• range_expression: It defines an expression that represents the suitable
sequence of elements.
• loop statement: It defines the body of the range-based for loop that
contains one or more statements to be repeatedly executed till the end
of the range- expression.
Note:
If we don't know the data type of the container elements, we can use the
auto keyword that automatically identifies the data type of the
range_expression.
10
Program to print each element of the array
using-range based for loop
• Let's consider an example to print the int and // use auto keyword to automatically specify the
double array using the range-based for loop in
C++. data type of darr container.
for ( const auto &var : darr )
#include <iostream>
{
using namespace std;
int main () cout << var << " " ;
{ }
int arr1 [5] = { 10, 20, 30, 40, 50}; return 0;
double darr [5] = { 2.4, 4.5, 1.5, 3.5, 4.0 };
}
// use range based for loop Output
for ( const auto &var : arr1 ) 10 20 30 40 50
{ 2.4 4.5 1.5 3.5 4.0
cout << var << " " ;
} 11
Program to demonstrate the vector in range
based for loop
• Let's write a simple program to // display vector elements
implement the vector in range based
for loop. for ( int x : vect)
#include <iostream> {
#include <vector> cout << x << " ";
using namespace std; }
return 0;
int main() }
{ Output
int x; // declare integer variable
5 10 25 20 25
// declare vector variable
vector <int> vect = {5, 10 , 25, 20, 25};
12
Program to print the arrays using Range based
for loop in C++ with reference
• Let's consider an example to print the array itemRef *= 3;
elements using range based for loop in C++.
}
#include <iostream>
#include <array> cout << endl << " After modification of the elements: "
<< endl;
#include <cstdlib>
using namespace std; for (int x : data){
int main(){ cout << x << " ";
Int x; }
array<int, 7> data = {1, 3, -2, 4, 6, 7, 9}; cout << endl;
cout << " Before updating the elements: " << endl; return 0; }
for (int x : data){
Output
cout << x << " ";
Before updating the elements:
}
// pass the references 1 3 -2 4 6 7 9
for (int &itemRef : data){ After modification of the elements:
13
3 9 -6 12 18 21 27
What is the difference between traditional for
loop and range-based for loop?
traditional for loop range-based for loop
• A traditional for loop is used to repeatedly • On the other hand, we have a new range-
execute the block of code till the specified based for loop available in the C++ . It has
condition is true. A traditional for loop has two parameters, range declaration, and the
three parameters, initialization of the range_ expression. It is also used to
repeatedly execute the block of code over a
variable, specify the condition, and the range.
last one is counter that is incremented by
one if the condition remains true.
Syntax
Syntax:
for ( range_declaration : range_ expression )
for ( variable_initialization;
specify_condition; updated_counter) {
{ loop _statement;
// statement to be executed;
// statement to be executed;
}
}
14
What is the difference between traditional for
loop and range-based for loop?

• The range_declaration is used to declare the type of


variable related to the range_expression (container).
• range_expression:
It is just like a container that holds the same types of
elements in a sequential manner.
• The loop_statement
The statement which is executed inside for loop.
15
Advantages of the range-based for loop
• It is easy to use, and its syntax is also simple.
• A range-based for loop does not require the calculation of the
number of elements in a containers
• It recognizes the starting and ending elements of the containers.
• We can easily modify the size and elements of the container.
• It does not create any copy of the elements.
• It is much faster than the traditional for loop.
• It usually uses the auto keyword to recognize the data type of the
container elements.
16
Use defined constant for the Size of an Array
• Array indices always start at 0 and end with a value one less than the
size of the array.
• Consider changing a program where the size of an array (say 50)
appears several dozen times over thousands of lines.
• You might be looking for 49, 50 or perhaps 51. You must understand
every instance where a number in this range was used. You might have
to find where 25 ( = 50/2) was used. You can’t be certain you have
completed the job.
• In order to write code that is easily and correctly modifiable, you
should use a defined constant for the array size.
• Define a constant SIZE, and use that. Then you have only one point
where you need to change the size:
• const int SIZE = 50;
17
#define

#define is a useful C++ component that allows the


programmer to give a name to a constant value before
the program is compiled.

18
Program initializing an array with a declaration
output
#include <iostream> while ( grades[idx] > MAX_GRADE )
using namespace std; {
#define MAX_GRADE 100 cout<< "\nThe highest grade possible is “
#define STUDENTS 10 << MAX_GRADE<<endl ;
int grades[STUDENTS], idx; cout<< "\nEnter correct grade: " ;
cin>>grades[idx] ;
int total = 0; //used for average
}
main()
total += grades[idx];
{
}
for( idx=0;idx< STUDENTS;idx++)
cout<< "\n\nThe average score is "<<(total /
{ STUDENTS);
cout<<"Enter Student "<<idx return 0;
+1<<"\'s grade: "; }
cin>>grades[idx] ; 19
Program initializing an array with a declaration
Output Enter Student 1's grade: 122
Enter Student 1's grade: 77 The highest grade possible is 100
Enter Student 2's grade: 88
Enter Student 3's grade: 90
Enter correct grade:
Enter Student 4's grade: 66
Enter Student 5's grade: 43
Enter Student 6's grade: 65
Enter Student 7's grade: 87
Enter Student 8's grade: 23
Enter Student 9's grade: 65
Enter Student 10's grade: 76
The average score is 68 20
Multidimensional arrays
• A multidimensional array has more than one subscript.
• A two-dimensional array has 2 subscripts; a three-dimensional array has 3
subscripts, and so on.
E.g., int table[5][3];
// 5 rows and 3 cols and store integer
table[0][0] table[0][1] table[0][2]
table[1][0] table[1][1] table[1][2]
table[2][0] table[2][1] table[2][2]
table[3][0] table[3][1] table[3][2]
table[4][0] table[4][1] table[4][2]

21
Multidimensional arrays
E.g.,
int n[5][3] = { { 20,43,45 }, { 65,4,34 },
{ 23,56,67 }, { 45,56,78 }, { 66,76,90 } };

22
Multidimensional arrays
E.g.,
int n[5][3] = { { 20,43,45 }, { 65,4,34 },
{ 23,56,67 }, { 45,56,78 }, { 66,76,90 } };

• To display all the data in array n,


for(int i=0;i<5;i++)
for(int j=0;j<3;j++)
cout<<n[i][j];

23
Multidimensional arrays

24
Multidimensional arrays
#include <iostream> for ( int j = 0; j < 2; j++ )
using namespace std; {

int main () { cout << "a[" << i << "][" << j << "]:
// an array with 5 rows and 2 columns. ";
int a[5][2] = { {0,0}, {1,2}, {2,4}, cout << a[i][j]<< endl;
{3,6},{4,8}}; }

// output each array element's value return 0;


for ( int i = 0; i < 5; i++ ) }

25
Multidimensional arrays
When the above code is compiled and executed, it produces the following
result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
26
Multidimensional arrays
#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] = { {
{ 10, 11 }, cout<<"\t"<<arr[i][j];
{ 20, 21 }, }
{ 30, 31 }, cout<<endl;
{ 40, 41 } }
}; }

int i,j;

27
Multidimensional arrays

28
Multi Dimensional Arrays

▪ A multidimensional array is an array with more than one dimension.


▪ It is the homogeneous collection of items where each element is accessed
using multiple indices.
▪ Multidimensional Array Declaration
datatype arrayName[size1][size2]...[sizeN];
where,
▪ datatype: Type of data to be stored in the array.
▪ arrayName: Name of the array.
▪ size1, size2,…, sizeN: Size of each dimension.
29
Multi Dimensional Arrays

▪ int arr1 [2] [4];

▪ The array int arr1 [2] [4] can store total (2*4) = 8 elements.

▪ In C++ int data type takes 4 bytes and we have 8 elements in the
array ‘arr1’ of the int type.

▪ Total size = 4*8 = 32 bytes.

30
Two Dimensional Arrays

▪ A two-dimensional array in C++ is a collection of elements organized


in rows and columns.

▪ It can be visualized as a table or a grid, where each element is


accessed using two indices: one for the row and one for the column.

▪ Like a one-dimensional array, two-dimensional array indices also


range from 0 to n-1 for both rows and columns.

31
Two Dimensional Arrays

Syntax of 2D array:
data_Type array_name[n][m];
Where,
n: Number of rows.
m: Number of columns.

32
Two Dimensional Arrays
// c++ program to illustrate the two dimensional array // Printing the element of 2D array
#include <iostream> for (int i = 0; i < 3; i++) {
using namespace std; for (int j = 0; j < 4; j++) {
int main() cout << array1[i][j] << " ";
{ }
int count = 1; cout << endl;
int array1[3][4]; }
// Initialize 2D array using loop
for (int i = 0; i < 3; i++) { return 0;
for (int j = 0; j < 4; j++) { }
array1[i][j] = count;
count++;
}
} 33
Two Dimensional Arrays
// C Program to print the elements of a Two-Dimensional array
#include <stdio.h>
int main(void)
{
// an array with 3 rows and 2 columns.
int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
// output each array element's value
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("Element at x[%i][%i]: ", i, j);
printf("%d\n", x[i][j]);
}
}
return (0);
} 34

You might also like