SlideShare a Scribd company logo
CS-114 Fundamentals of Programming
Arrays
Instructor: Jahan Zeb
Department of Computer & Software Engineering (DC&SE)
College of E&ME
NUST
Introduction
 Arrays
– Structures of related data items
– Static entity (same size throughout program)
Arrays
 Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
 To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
 N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1
Arrays
 Array elements like other variables
– Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
 Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]
Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that
all elements of this array
have the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the
element within array c
Declaring Arrays
 When declaring arrays, specify
– Name
– Type of array
• Any data type
– Number of elements
– type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
 Declaring multiple arrays of same type
– Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
Examples Using Arrays
 Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
1
2 // Initializing an array.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 int n[ 10 ]; // n is an array of 10 integers
15
16 // initialize elements of array n to 0
17 for ( int i = 0; i < 10; i++ )
18 n[ i ] = 0; // set element at location i to 0
19
20 cout << "Element" << setw( 13 ) << "Value" << endl;
21
22 // output contents of array n in tabular format
23 for ( int j = 0; j < 10; j++ )
24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
25
Declare a 10-element array of
integers.
Initialize array to 0 using a
for loop. Note that the array
has elements n[0] to n[9].
26 return 0; // indicates successful termination
27
28 } // end main
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
1
2 // Initializing an array with a declaration.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 // use initializer list to initialize array n
15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
16
17 cout << "Element" << setw( 13 ) << "Value" << endl;
18
19 // output contents of array n in tabular format
20 for ( int i = 0; i < 10; i++ )
21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main
Note the use of the initializer
list.
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Examples Using Arrays
 Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
1
2 // Initialize array s to the even integers from 2 to 20.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 // constant variable can be used to specify array size
15 const int arraySize = 10;
16
17 int s[ arraySize ]; // array s has 10 elements
18
19 for ( int i = 0; i < arraySize; i++ ) // set the values
20 s[ i ] = 2 + 2 * i;
21
22 cout << "Element" << setw( 13 ) << "Value" << endl;
23
Note use of const keyword.
Only const variables can
specify array sizes.
The program becomes more
scalable when we set the array
size using a const variable.
We can change arraySize,
and all the loops will still
work (otherwise, we’d have to
update every loop in the
program).
24 // output contents of array s in tabular format
25 for ( int j = 0; j < arraySize; j++ )
26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
27
28 return 0; // indicates successful termination
29
30 } // end main
Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
1
2 // Using a properly initialized constant variable.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 const int x = 7; // initialized constant variable
11
12 cout << "The value of constant variable x is: "
13 << x << endl;
14
15 return 0; // indicates successful termination
16
17 } // end main
The value of constant variable x is: 7
Proper initialization of
const variable.
1
2 // A const object must be initialized.
3
4 int main()
5 {
6 const int x; // Error: x must be initialized
7
8 x = 7; // Error: cannot modify a const variable
9
10 return 0; // indicates successful termination
11
12 } // end main
d:cpphtp4_examplesch04Fig04_07.cpp(6) : error C2734: 'x' :
const object must be initialized
Uninitialized const results
in a syntax error. Attempting
to modify the const is
another error.
1
2 // Compute the sum of the elements of the array.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 const int arraySize = 10;
11
12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
13
14 int total = 0;
15
16 // sum contents of array a
17 for ( int i = 0; i < arraySize; i++ )
18 total += a[ i ];
19
20 cout << "Total of array element values is " << total << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
Total of array element values is 55
1
2 // Histogram printing program.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 int main()
13 {
14 const int arraySize = 10;
15 int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
16
17 cout << "Element" << setw( 13 ) << "Value"
18 << setw( 17 ) << "Histogram" << endl;
19
20 // for each element of array n, output a bar in histogram
21 for ( int i = 0; i < arraySize; i++ ) {
22 cout << setw( 7 ) << i << setw( 13 )
23 << n[ i ] << setw( 9 );
24
25 for ( int j = 0; j < n[ i ]; j++ ) // print one bar
26 cout << '*';
Prints asterisks corresponding
to size of array element,
n[i].
27
28 cout << endl; // start next line of output
29
30 } // end outer for structure
31
32 return 0; // indicates successful termination
33
34 } // end main
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *
'break’ statement
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{ // break condition
if (i == 3)
{
break; }
cout << i << endl;
}
return 0;
}
1
2
‘continue’ statement
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++) { //
condition to continue
if (i == 3)
{
continue; }
cout << i << endl; }
return 0;
}
1
2
4
5
Nested Loops
#include <iostream>
using namespace std;
int main()
{
int rows = 5; int columns = 3;
for (int i = 1; i <= rows; ++i)
{
for (int j = 1; j <= columns; ++j)
{ cout << "* "; }
cout << endl;
}
return 0;
}
* * *
* * *
* * *
* * *
* * *
Multiple-Subscripted Arrays
 Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
• a[0] is an array of 4 elements
• a[0][0] is the first element of that array
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscript
Array name
Column subscript
Multiple-Subscripted Arrays
 To initialize
– Default of 0
– Initializers grouped by row in braces
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1 2
3 4
1 0
3 4
Row 0 Row 1
Multiple-Subscripted Arrays
 Referenced like normal
cout << b[ 0 ][ 1 ];
– Outputs 0
– Cannot reference using commas
cout << b[ 0, 1 ];
• Syntax error
 Function prototypes
– Must specify sizes of subscripts
• First subscript not necessary, as with single-scripted arrays
– void printArray( int [][ 3 ] );
1 0
3 4
1
2 // Initializing multidimensional arrays.
3 #include <iostream>
4 Using namespace std;
5
6
7
8
9
10 int main()
11 {
12 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
13 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
14 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
15
16 cout << "Values in array1 by row are:" << endl;
Note the various initialization
styles. The elements in
array2 are assigned to the
first row and then the second.
Note the format of the
prototype.
28
32 for ( int i = 0; i < 2; i++ ) { // for each row
33
34 for ( int j = 0; j < 3; j++ ) // output column values
35 cout << array1[ i ][ j ] << ' ';
36
37 cout << endl; // start new line of output
38
39 } // end outer for structure
40
41
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0
For loops are often used to
iterate through arrays. Nested
loops are helpful with
multiple-subscripted arrays.

More Related Content

Similar to Lecture#5-Arrays-oral patholohu hfFoP.ppt (20)

PDF
I have written the code but cannot complete the assignment please help.pdf
shreeaadithyaacellso
 
PPTX
Synapse india dotnet development overloading operater part 3
Synapseindiappsdevelopment
 
PPTX
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
famidrabbifr
 
PDF
Arrays and strings in c++
GC University Faisalabad
 
PPTX
Lecture 5Arrays on c++ for Beginner.pptx
arjurakibulhasanrrr7
 
PPTX
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
PDF
array 2 (1)_merged.pdf
PradiptaPaul7
 
PPTX
2- Dimensional Arrays
Education Front
 
PDF
Chap 6 c++
Venkateswarlu Vuggam
 
PPT
Fp201 unit4
rohassanie
 
PPT
Chap 6 c++
Venkateswarlu Vuggam
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PPTX
Array,MULTI ARRAY, IN C
naveed jamali
 
PPTX
Arrays in C++
Kashif Nawab
 
PPTX
Lecture11 standard template-library
Hariz Mustafa
 
PDF
C++ practical
Rahul juneja
 
DOCX
Arrry structure Stacks in data structure
lodhran-hayat
 
PDF
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
PPT
pointers
teach4uin
 
PPT
SP-First-Lecture.ppt
FareedIhsas
 
I have written the code but cannot complete the assignment please help.pdf
shreeaadithyaacellso
 
Synapse india dotnet development overloading operater part 3
Synapseindiappsdevelopment
 
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
famidrabbifr
 
Arrays and strings in c++
GC University Faisalabad
 
Lecture 5Arrays on c++ for Beginner.pptx
arjurakibulhasanrrr7
 
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
array 2 (1)_merged.pdf
PradiptaPaul7
 
2- Dimensional Arrays
Education Front
 
Fp201 unit4
rohassanie
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
Array,MULTI ARRAY, IN C
naveed jamali
 
Arrays in C++
Kashif Nawab
 
Lecture11 standard template-library
Hariz Mustafa
 
C++ practical
Rahul juneja
 
Arrry structure Stacks in data structure
lodhran-hayat
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
pointers
teach4uin
 
SP-First-Lecture.ppt
FareedIhsas
 

More from SamanArshad11 (20)

PPTX
2 Anatogghhghhhmy2 lumbar vertebrae.pptx
SamanArshad11
 
PPTX
13.Kine II Sfhgggggggggghguspension-I.pptx
SamanArshad11
 
PPTX
MANAGEMENT OF PATIENTS WITH RENAL AND HEPATIC CONDITIONS.pptx
SamanArshad11
 
PPTX
Hypothyroidismfhffjggvjjhnjnvvdvsdvs.pptx
SamanArshad11
 
PPTX
Lecture 4 Cartilage and osification.pptx
SamanArshad11
 
PPT
gingival enlarvhvhnvnhvnvvnvnvhnbgment.ppt
SamanArshad11
 
PPTX
161573-virus-temvjhvnvnvnnvplate-16x9.pptx
SamanArshad11
 
PPTX
cirrhosis complicatigfvesdvfsfvrfvons.pptx
SamanArshad11
 
PPTX
Aortic Valve Diseases fdsfgsrdfd (1).pptx
SamanArshad11
 
PPTX
1645032866577_Preoperative health assessment & physical examination.pptx
SamanArshad11
 
PPTX
3dmcomplicationscld-121211215105-phpapp02-converted.pptx
SamanArshad11
 
PPTX
DENGUE MCjgugugigiguhujhjhuhjjhughyjQS .pptx
SamanArshad11
 
PPTX
Toxic shock syndromvje - kawasaki 2019.pptx
SamanArshad11
 
PPTX
CELL PHYSIOLO 7vv7v7vyv7yv7yvy7vy7vy8vu8gGY.pptx
SamanArshad11
 
PPTX
Lecture 2 Integumentart7tv7v7v6vy System.pptx
SamanArshad11
 
PPTX
FOP bdhhd dbdb dhdbd dbdbdbdbdbdb (1).pptx
SamanArshad11
 
PPTX
Lecture 07 8 LCA gyhjvjfjfv jfuf(2).pptx
SamanArshad11
 
PPTX
Lecture-5b - BCD Adder and Carry Propagation, Comparator (2).pptx
SamanArshad11
 
PPTX
042 oral patjlofy asvher sybchg jugv.pptx
SamanArshad11
 
PPT
Lecture#1-Fundamental bt nch xhhs (1).ppt
SamanArshad11
 
2 Anatogghhghhhmy2 lumbar vertebrae.pptx
SamanArshad11
 
13.Kine II Sfhgggggggggghguspension-I.pptx
SamanArshad11
 
MANAGEMENT OF PATIENTS WITH RENAL AND HEPATIC CONDITIONS.pptx
SamanArshad11
 
Hypothyroidismfhffjggvjjhnjnvvdvsdvs.pptx
SamanArshad11
 
Lecture 4 Cartilage and osification.pptx
SamanArshad11
 
gingival enlarvhvhnvnhvnvvnvnvhnbgment.ppt
SamanArshad11
 
161573-virus-temvjhvnvnvnnvplate-16x9.pptx
SamanArshad11
 
cirrhosis complicatigfvesdvfsfvrfvons.pptx
SamanArshad11
 
Aortic Valve Diseases fdsfgsrdfd (1).pptx
SamanArshad11
 
1645032866577_Preoperative health assessment & physical examination.pptx
SamanArshad11
 
3dmcomplicationscld-121211215105-phpapp02-converted.pptx
SamanArshad11
 
DENGUE MCjgugugigiguhujhjhuhjjhughyjQS .pptx
SamanArshad11
 
Toxic shock syndromvje - kawasaki 2019.pptx
SamanArshad11
 
CELL PHYSIOLO 7vv7v7vyv7yv7yvy7vy7vy8vu8gGY.pptx
SamanArshad11
 
Lecture 2 Integumentart7tv7v7v6vy System.pptx
SamanArshad11
 
FOP bdhhd dbdb dhdbd dbdbdbdbdbdb (1).pptx
SamanArshad11
 
Lecture 07 8 LCA gyhjvjfjfv jfuf(2).pptx
SamanArshad11
 
Lecture-5b - BCD Adder and Carry Propagation, Comparator (2).pptx
SamanArshad11
 
042 oral patjlofy asvher sybchg jugv.pptx
SamanArshad11
 
Lecture#1-Fundamental bt nch xhhs (1).ppt
SamanArshad11
 
Ad

Recently uploaded (19)

PPTX
ARENA BOLA 1&2 Contigency Plan - ASTRO Broadcast pptx
SobnavalleKhishmu
 
PPT
chapter 10.pptkkkkkkkkkkkkkkkkkkkkkkkkkk
trishalasharma7
 
PDF
Waddell Scavenger Hunt Presentation-2.pdf
peytonwaddell94
 
PPTX
03 Pradeep Sane_Ethics & Prof Resp03 Pradeep Sane_Ethics & Prof 03 Pradeep Sa...
Kislaychaurasia
 
PPTX
一比一原版(Newman毕业证)纽曼大学毕业证如何办理
Taqyea
 
PDF
cyanean_Lab_Reportdfd dfdsfsdfsd f dsf.pdf
REYESTACZAEDGARALEJA
 
PPTX
Basic ppt templatecbnvjmbjbhknkl,vhv.pptx
Apurvanand Sahay
 
PDF
WKA #18: Mirror Memoria - "TATTOO" TRANSCRIPT.pdf
Optimistic18
 
PDF
Sanchit batra best magician in India For all Events.pdf
Sanchit Batra
 
PDF
How Modern Filmmakers Plan, Shoot, and Deliver Blockbuster Movies.pdf
All Writers Destination
 
PPTX
一比一原版(DCU毕业证书)都柏林城市大学毕业证如何办理
Taqyea
 
PPTX
Gradec 1 HeaYTRJTYJRTYJRJlth 4th grading.pptx
mangalindanjerremyjh
 
PPTX
OTT Channel Migration_AABC Overview_Operations Briefing.pptx
SobnavalleKhishmu
 
PDF
WKA #6: The Adventures - "FOUND FAMILY" TRANSCRIPT.pdf
Optimistic18
 
PPTX
Line Up Activity For Kids and Adult.....
cynthiamarasigan
 
DOCX
The_Owl_and_the_Crow_Kalila_wa_Dimna.docx from fable
ranamutahir19
 
PPTX
原版德国德累斯顿国际大学毕业证(DIU毕业证书)如何办理
Taqyea
 
PPTX
一比一原版(UoD毕业证)邓迪大学毕业证如何办理
Taqyea
 
PDF
Peyton Waddell Scavenger Hunt Presentation.pdf
peytonwaddell94
 
ARENA BOLA 1&2 Contigency Plan - ASTRO Broadcast pptx
SobnavalleKhishmu
 
chapter 10.pptkkkkkkkkkkkkkkkkkkkkkkkkkk
trishalasharma7
 
Waddell Scavenger Hunt Presentation-2.pdf
peytonwaddell94
 
03 Pradeep Sane_Ethics & Prof Resp03 Pradeep Sane_Ethics & Prof 03 Pradeep Sa...
Kislaychaurasia
 
一比一原版(Newman毕业证)纽曼大学毕业证如何办理
Taqyea
 
cyanean_Lab_Reportdfd dfdsfsdfsd f dsf.pdf
REYESTACZAEDGARALEJA
 
Basic ppt templatecbnvjmbjbhknkl,vhv.pptx
Apurvanand Sahay
 
WKA #18: Mirror Memoria - "TATTOO" TRANSCRIPT.pdf
Optimistic18
 
Sanchit batra best magician in India For all Events.pdf
Sanchit Batra
 
How Modern Filmmakers Plan, Shoot, and Deliver Blockbuster Movies.pdf
All Writers Destination
 
一比一原版(DCU毕业证书)都柏林城市大学毕业证如何办理
Taqyea
 
Gradec 1 HeaYTRJTYJRTYJRJlth 4th grading.pptx
mangalindanjerremyjh
 
OTT Channel Migration_AABC Overview_Operations Briefing.pptx
SobnavalleKhishmu
 
WKA #6: The Adventures - "FOUND FAMILY" TRANSCRIPT.pdf
Optimistic18
 
Line Up Activity For Kids and Adult.....
cynthiamarasigan
 
The_Owl_and_the_Crow_Kalila_wa_Dimna.docx from fable
ranamutahir19
 
原版德国德累斯顿国际大学毕业证(DIU毕业证书)如何办理
Taqyea
 
一比一原版(UoD毕业证)邓迪大学毕业证如何办理
Taqyea
 
Peyton Waddell Scavenger Hunt Presentation.pdf
peytonwaddell94
 
Ad

Lecture#5-Arrays-oral patholohu hfFoP.ppt

  • 1. CS-114 Fundamentals of Programming Arrays Instructor: Jahan Zeb Department of Computer & Software Engineering (DC&SE) College of E&ME NUST
  • 2. Introduction  Arrays – Structures of related data items – Static entity (same size throughout program)
  • 3. Arrays  Array – Consecutive group of memory locations – Same name and type (int, char, etc.)  To refer to an element – Specify array name and position number (index) – Format: arrayname[ position number ] – First element at position 0  N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] – Nth element as position N-1
  • 4. Arrays  Array elements like other variables – Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ];  Can perform operations inside subscript c[ 5 – 2 ] same as c[3]
  • 5. Arrays c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
  • 6. Declaring Arrays  When declaring arrays, specify – Name – Type of array • Any data type – Number of elements – type arrayName[ arraySize ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats  Declaring multiple arrays of same type – Use comma separated list, like regular variables int b[ 100 ], x[ 27 ];
  • 7. Examples Using Arrays  Initializing arrays – For loop • Set each element – Initializer list • Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers, rightmost elements 0 – To set every element to same value int n[ 5 ] = { 0 }; – If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; • 5 initializers, therefore 5 element array
  • 8. 1 2 // Initializing an array. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 int n[ 10 ]; // n is an array of 10 integers 15 16 // initialize elements of array n to 0 17 for ( int i = 0; i < 10; i++ ) 18 n[ i ] = 0; // set element at location i to 0 19 20 cout << "Element" << setw( 13 ) << "Value" << endl; 21 22 // output contents of array n in tabular format 23 for ( int j = 0; j < 10; j++ ) 24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; 25 Declare a 10-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9].
  • 9. 26 return 0; // indicates successful termination 27 28 } // end main Element Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0
  • 10. 1 2 // Initializing an array with a declaration. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 // use initializer list to initialize array n 15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 16 17 cout << "Element" << setw( 13 ) << "Value" << endl; 18 19 // output contents of array n in tabular format 20 for ( int i = 0; i < 10; i++ ) 21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; 22 23 return 0; // indicates successful termination 24 25 } // end main Note the use of the initializer list.
  • 11. Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37
  • 12. Examples Using Arrays  Array size – Can be specified with constant variable (const) • const int size = 20; – Constants cannot be changed – Constants must be initialized when declared – Also called named constants or read-only variables
  • 13. 1 2 // Initialize array s to the even integers from 2 to 20. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 // constant variable can be used to specify array size 15 const int arraySize = 10; 16 17 int s[ arraySize ]; // array s has 10 elements 18 19 for ( int i = 0; i < arraySize; i++ ) // set the values 20 s[ i ] = 2 + 2 * i; 21 22 cout << "Element" << setw( 13 ) << "Value" << endl; 23 Note use of const keyword. Only const variables can specify array sizes. The program becomes more scalable when we set the array size using a const variable. We can change arraySize, and all the loops will still work (otherwise, we’d have to update every loop in the program).
  • 14. 24 // output contents of array s in tabular format 25 for ( int j = 0; j < arraySize; j++ ) 26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; 27 28 return 0; // indicates successful termination 29 30 } // end main Element Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20
  • 15. 1 2 // Using a properly initialized constant variable. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 const int x = 7; // initialized constant variable 11 12 cout << "The value of constant variable x is: " 13 << x << endl; 14 15 return 0; // indicates successful termination 16 17 } // end main The value of constant variable x is: 7 Proper initialization of const variable.
  • 16. 1 2 // A const object must be initialized. 3 4 int main() 5 { 6 const int x; // Error: x must be initialized 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination 11 12 } // end main d:cpphtp4_examplesch04Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized Uninitialized const results in a syntax error. Attempting to modify the const is another error.
  • 17. 1 2 // Compute the sum of the elements of the array. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 const int arraySize = 10; 11 12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 14 int total = 0; 15 16 // sum contents of array a 17 for ( int i = 0; i < arraySize; i++ ) 18 total += a[ i ]; 19 20 cout << "Total of array element values is " << total << endl; 21 22 return 0; // indicates successful termination 23 24 } // end main Total of array element values is 55
  • 18. 1 2 // Histogram printing program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 int main() 13 { 14 const int arraySize = 10; 15 int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 16 17 cout << "Element" << setw( 13 ) << "Value" 18 << setw( 17 ) << "Histogram" << endl; 19 20 // for each element of array n, output a bar in histogram 21 for ( int i = 0; i < arraySize; i++ ) { 22 cout << setw( 7 ) << i << setw( 13 ) 23 << n[ i ] << setw( 9 ); 24 25 for ( int j = 0; j < n[ i ]; j++ ) // print one bar 26 cout << '*'; Prints asterisks corresponding to size of array element, n[i].
  • 19. 27 28 cout << endl; // start next line of output 29 30 } // end outer for structure 31 32 return 0; // indicates successful termination 33 34 } // end main Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
  • 20. 'break’ statement #include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { // break condition if (i == 3) { break; } cout << i << endl; } return 0; } 1 2
  • 21. ‘continue’ statement #include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { // condition to continue if (i == 3) { continue; } cout << i << endl; } return 0; } 1 2 4 5
  • 22. Nested Loops #include <iostream> using namespace std; int main() { int rows = 5; int columns = 3; for (int i = 1; i <= rows; ++i) { for (int j = 1; j <= columns; ++j) { cout << "* "; } cout << endl; } return 0; } * * * * * * * * * * * * * * *
  • 23. Multiple-Subscripted Arrays  Multiple subscripts – a[ i ][ j ] – Tables with rows and columns – Specify row, then column – “Array of arrays” • a[0] is an array of 4 elements • a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
  • 24. Multiple-Subscripted Arrays  To initialize – Default of 0 – Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 2 3 4 1 0 3 4 Row 0 Row 1
  • 25. Multiple-Subscripted Arrays  Referenced like normal cout << b[ 0 ][ 1 ]; – Outputs 0 – Cannot reference using commas cout << b[ 0, 1 ]; • Syntax error  Function prototypes – Must specify sizes of subscripts • First subscript not necessary, as with single-scripted arrays – void printArray( int [][ 3 ] ); 1 0 3 4
  • 26. 1 2 // Initializing multidimensional arrays. 3 #include <iostream> 4 Using namespace std; 5 6 7 8 9 10 int main() 11 { 12 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; 13 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; 14 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; 15 16 cout << "Values in array1 by row are:" << endl; Note the various initialization styles. The elements in array2 are assigned to the first row and then the second. Note the format of the prototype.
  • 27. 28 32 for ( int i = 0; i < 2; i++ ) { // for each row 33 34 for ( int j = 0; j < 3; j++ ) // output column values 35 cout << array1[ i ][ j ] << ' '; 36 37 cout << endl; // start new line of output 38 39 } // end outer for structure 40 41 Values in array1 by row are: 1 2 3 4 5 6 Values in array2 by row are: 1 2 3 4 5 0 Values in array3 by row are: 1 2 0 4 0 0 For loops are often used to iterate through arrays. Nested loops are helpful with multiple-subscripted arrays.