0% found this document useful (0 votes)
11 views

Chapter07 Array - String - PPT

Uploaded by

jerreltan05
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 views

Chapter07 Array - String - PPT

Uploaded by

jerreltan05
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/ 35

Chapter 7 Array and String

Official (Open), Non‐sensitive

Chapter 7
Array & String

Official (Open), Non‐sensitive

What is an array?
An array stores more than one value of the
same data type under a collective name.

2
Chapter 7 Array and String

Official (Open), Non‐sensitive

Why arrays?
char initial; // A character variable
int number; // An integer variable
double value; // A floating point variable
These variables can each be used to store one value only.

In C, a list of characters can be stored in a char array.


A list of integers can be stored in an int array.
A list of double values can be stored in a double array.

Official (Open), Non‐sensitive

Why arrays?
A list of variables of the same type
int num1, num2, num3, …, num10;
can be replaced by a single array
int num[10];
Accessing individual data in array is easy
and fast by using index and loop.

4
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Declaration
The syntax for declaring an array is:
data_type array_name[size];
e.g.
int marks[10];
data type size

char city[15];

Official (Open), Non‐sensitive

// Declare array variables Array Declaration


int marks[10];
char city[15];

0 1 2 3 4 5 6 7 8 9

marks
int: 4 bytes
40 bytes

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
city
char: 1 byte
15 bytes

Drawings are not


to scale!
6

6
Chapter 7 Array and String

Official (Open), Non‐sensitive

Initializing an Array
#include <iostream>
using namespace std;
int main()
Declaration Initialization
{
int num[4] = {2, 4, 6, 8};
char letter[4] = {'A', 'B', 'C', 'D' };
:
:
}
num 2 4 6 8

letter 'A' 'B' 'C' 'D'


7

Official (Open), Non‐sensitive

Character Array and String


In C, a string of characters (e.g. a name or an
address) can be stored in a character array.
#include <iostream>
using namespace std;
int main() Declaration Initialization
{
char institute[5] = "Poly";
:
:
}

8
Chapter 7 Array and String

Official (Open), Non‐sensitive

Character Array and String


'0' 0011 0000 '\0' 0000 0000
char institute[5] = "Poly"; 'n' 0110 1110
't' 0111 0100
'\n' 0000 1010
'\t' 0000 1001

'P' 'o' 'l' 'y' '\0'

This statement tells the compiler to


– reserve memory for a character array which can store 5
characters.
– the name array is institute.
– store the characters, ꞌPꞌ, ꞌoꞌ, ꞌlꞌ, ꞌyꞌ in the array.
– add the NULL character, '\0', (ASCII 0) at the end of the string.
NULL character is the string terminating character.

Official (Open), Non‐sensitive

What is a C-style String?


char name[5] = "Poly";
'P' 'o' 'l' 'y' '\0'

A C-style string or simply referred to as string, is a


sequence of characters that ends with the null
terminator, ꞌ\0ꞌ.
Character array that stores a string is referred to as a
string.
"Poly" is also referred to as a string.

10

10
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Size for String


We must always reserve enough array elements to hold
a string including its NULL terminating character, ꞌ\0ꞌ
e.g. char date[6] = "1 Jan";
The array size must be at least 6.
The string literal, 1 Jan, has 5 characters. Adding the
NULL character at the end of the string, there are 6
characters in the string.
Ensure: array size ≥ number of characters within the double quotes
+ 1.

11

11

Official (Open), Non‐sensitive

Differences between a String


and a Character
When initializing a string to a character array,
the string literal (text) must be enclosed in
double quotes.
– e.g.
– char institution[15] = "Singapore Poly";

However, when initializing a character variable,


the character must be enclosed in single quotes.
– e.g.
– char initial = 'R';

12

12
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.1.1
An array is used to hold several data items
together as one entity. Can data of
different types be stored in a single array
(Yes / No)?

13

13

Official (Open), Non‐sensitive

Quiz 7.1.2
Which of the following statement(s) about the character '5'
and the string "5" in the C++ language is (are) true?
(a) The character '5' can be assigned or stored in a character variable.
(b) The string "5" can be assigned or stored in a character variable.
(c) The string "5" consists of 2 characters, '5' and '\0'.
(d) The string "5" can be assigned in a character array of size 2.

14

14
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Declaration & Initialization


We can initialize a variable and an array when declaring
them.
But initialization is optional. Data can be assigned to an
array at the later part of a program.

int main()
{
int num[5] = {9, 0, −5, 7, 8};
double change[4] = {−3.5, 0, −2, 1.05};
char key[4] = {'W', '@', 'a', '1'};
char date[8] = "1st Jan";
:
:
}
15

15

Official (Open), Non‐sensitive

Array Declaration & Initialization


We may declare array with size larger than needed for
the initialization but not smaller.
Declare array with larger size when longer list of data will
be assigned into the array at the later part of the
program.
int main()
{
int num[15] = {9, 0, −5, 7, 8};
double change[6] = {−3.5, 0, 2, 1.05};
char key[30] = {'W', '@', 'a', '1'};
char date[20] = "1st Jan";
:
:
}
16

16
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Declaration & Initialization


double change[6] = {−3.5, 0, −2, 1.05};

−3.5 0 −2 1.05 ? ?

The last 2 elements are not initialized.


They are filled with unknown garbage data.

17

17

Official (Open), Non‐sensitive

Array Declaration & Initialization


We can omit array size when declaring with initialization.
The compiler will calculates the array size from the
initialization.

int main()
{
int num[ ] = {9, 0, −5, 7, 8};
double change[ ] = {−3.5, 0, −2, 1.05};
char key[ ] = {'W', '@', 'a', '1'};
char date[ ] = "1st Jan";
:
:
}
18

18
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Declaration & Initialization


– char msg[ ] = "Hello";
– (The NULL character will be inserted
automatically).
– This is a common way to initialize a string
into a character array.
Or
– char msg[ ]={ 'H', 'e', 'l', 'l', 'o', '\0' };
– (The NULL character '\0' is inserted explicitly)
– This is an uncommon tedious way.

19

19

Official (Open), Non‐sensitive

Array Declaration & Initialization


The declarations
char school[4] = "EEE";
and
char school[ ] = "EEE";
both achieve the same purposes.

20

20
Chapter 7 Array and String

Official (Open), Non‐sensitive

Array Declaration & Initialization


The declarations below without initialization will not
reserve any space for the arrays.
These illegal declarations will give compilation errors.
int n[ ]; ✘
double x[ ]; ✘
char str[ ]; ✘
Without initialization, you must enter array size.
int n[20]; ✔
double x[20]; ✔
char str[50]; ✔

21

21

Official (Open), Non‐sensitive

Accessing Array Elements


Individual elements are accessed using the index or
subscript. When declaring an When accessing
array, this number an array element,
int main() = the size of the this number = the
{ array. index of the
element.
int num[5] = {9, 0, −5, 6, 7};
15
num[0] = 20;
num[4] = num[0] + num[2];
cout << num[4];
Note
: num[0]: base element
: num[4]: last element
}
num 9
20 0 −5 6 7
15

num[0] num[1] num[2] num[3] num[4]

index or
subscript
22

22
Chapter 7 Array and String

Official (Open), Non‐sensitive

Accessing Array Elements


Individual elements are accessed using the index or
subscript.
int main()
{
char code[6] = {'W', '@', 'a', ‘7'};
code[4] = '#';
code[1] = code[2] + 1; b

cout << code[1];


:
:
}

code 'W' 'b'


'@' 'a' '7' '#'
? ?

code[0] code[1] code[2] code[3] code[4] code[5]

23

23

Official (Open), Non‐sensitive

Quiz 7.2.1
Given that
int num[5] = {9, 0, −5, 7, 7}; // 1 1) num
char month[9]; // 2 2) month
char year[ ]; // 3 3) year
double price[5]; // 4 4) price
char key[5] = {'W', '@', 'a', '1' }; // 5 5) key
char Christmas[ ] = "25 Dec"; // 6 6) Christmas
double change[6] = {−3.5, 0, −2, 1.05}; // 7 7) change

Determine which of the following items are arrays.


(a) 1, 4 & 7
(b) 2, 3, 5 & 6
(c) 1, 2, 4, 5, 6 & 7
(d) 1 to 7
24

24
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.2.2
Given that 1) array num
int num[5] = {9, 0, −5, 7, 7}; // 1 2) array month
char month[9]; // 2 3) array year
char year[5] = {'1', '9', '6', '5', '\0'}; // 3 4) array price
double price[5]; // 4 5) array key
char key[5] = {'W', '@', 'a', '1' }; // 5 6) array Christmas
char Christmas[ ] = "25 Dec"; // 6 & 7 7) "25 Dec"
double change[6] = {−3.5, 0, −2, 1.05}; // 8 8) double change

Determine which of the 8 items can be referred to as


strings definitely.
(a) 3&6
(b) 3, 6 & 7
(c) 2, 3, 5 & 6
(d) 1 to 8 25

25

Official (Open), Non‐sensitive

Quiz 7.2.3
int main()
{
int d[ ] = {1, 2, 3, 4, 5};
char code[6] = {'W', '@', 'a', ‘7' };
code[2] = 'x';
code[0] = d[1] + code[2] ;
cout << code[0];
return 0;
}

Determine the output of the program.


(a) W
(b) 2a
(c) b
(d) z
26

26
Chapter 7 Array and String

Official (Open), Non‐sensitive

Accessing String
A string is a sequence of characters ends with '\0'.
Display the entire string with a single cout statement.

int main()
{
char date[ ] = "1 Jan";
date[0] = '2';
cout << date[0] << endl; 2
2 Jan
cout << date;
:
: Note: No [ ] after the
array name, date.
}

date '2'
'1' ' ' 'J' 'a' 'n' '\0'

date[0] date[1] date[2] date[3] date[4] date[5]


27

27

Official (Open), Non‐sensitive

Use cin & cout for string


#include <iostream>
using namespace std; Using cin to input a string to a
character array, brackets [ ] are not
int main() needed.
{
char first[30]; // Hold First Name
char middle[30]; // Holds Middle Name
char last[30]; // Holds Last Name
What is your First Name: Ang
cout << "\nWhat is your First Name: ";
cin >> first; What is your Middle Name: Beng
cout << "\nWhat is your Middle Name: ";
What is your Last Name: Soo
cin >> middle;
cout << "\nWhat is your Last Name: ";
cin >> last;

28

28
Chapter 7 Array and String

Official (Open), Non‐sensitive

Use cin & cout for string


// ----------- Print Initials and name ------------
cout << "\nYour name is “ << first << middle << last << endl;
cout << "\nYour initial is " << first[0] << middle[0] << last[0] << endl;
return 0;
}

What is your First Name: Ang

What is your Middle Name: Beng

What is your Last Name: Soo

Your name is AngBengSoo

Your initial is ABS

29

29

Official (Open), Non‐sensitive

Why NULL character?


int main()
{ cout stops to display when reaching
char msg[ ] = "Hello"; the NULL terminating character, ꞌ\0ꞌ.
char arr[ ] = {'H', 'e', 'l', 'l', 'o'};
cout << msg << endl; Hello
Hello@!#$%^&*()
cout << arr << endl;
:
:
} Without NULL terminating character, ꞌ\0ꞌ,
cout doesn’t know when to stop to display.

msg 'H' 'e' 'l' 'l' 'o' '\0'

Unknown data in
arr 'H' 'e' 'l' 'l' 'o'
memories behind.

30

30
Chapter 7 Array and String

Official (Open), Non‐sensitive

strlen( ) finds string length


#include <iostream>
#include <cstring> cstring must be included if
using namespace std; you use the function strlen().

int main()
{ 5
7
char date[20] = "1 Mar";
cout << strlen(date) << endl;
cout << strlen("1 March") << endl;
:
:
}
The input parameter strlen( ) is a string.
strlen( ) returns the length of the string.

31

31

Official (Open), Non‐sensitive

Incorrect String Assignment


// This is the proper way
#include <iostream>
using namespace std;
int main()
{
char date[6] = "1 Jan"; // Proper C statement
cout << date;
}

#include <iostream>
using namespace std;
int main()
{
char date[6];
date = "1 Jan"; // Wrong statement. Compilation error.
cout << date;
}
32

32
Chapter 7 Array and String

Official (Open), Non‐sensitive

Use strcpy( ) to copy a string


#include <iostream> cstring must be included if you use the function strcpy().
#include <cstring> In Visual Studio, highlight the project, click View |
Property Pages | Configuration | Properties | C/C++ |
using namespace std; Preporocessor | Preprocessor Definitions, key in
_CRT_SECURE_NO_WARNINGS, then click OK
int main()
{ Size ≥ 15 Singapore Poly
char institution[15];
// Copy a string to a character array
strcpy(institution, "Singapore Poly");
cout << institution;
:
:
}
strcpy(str1, str2) is a library function
copies str2 to str1.

33

33

Official (Open), Non‐sensitive

Use strcpy( ) to copy a string


#include <iostream> cstring must be included if you use the function strcpy().
In Visual Studio, highlight the project, click View |
#include <cstring> Property Pages | Configuration | Properties | C/C++ |
using namespace std; Preporocessor | Preprocessor Definitions, key in
_CRT_SECURE_NO_WARNINGS, then click OK
int main()
{ 1st May
char str1[25], str2[15] = "1st May";
// Copy a string to a character array
strcpy(str1, str2);
cout << str1;
:
:
} strcpy(str1, str2) is a library function
copies str2 to str1.

34

34
Chapter 7 Array and String

Official (Open), Non‐sensitive

Use strcpy( ) to copy a string


#include <iostream> cstring must be included if you use the function strcpy().
#include <cstring> In Visual Studio, highlight the project, click View |
using namespace std; Property Pages | Configuration | Properties | C/C++ |
Preporocessor | Preprocessor Definitions, key in
int main() _CRT_SECURE_NO_WARNINGS, then click OK
{
char str1[25], str2[15] = "1st May";
strcpy(str1, str2);
cout << str1;
:
:
When a function accesses the
} whole string, brackets [ ] are not
needed.

35

35

Official (Open), Non‐sensitive

Quiz 7.3.1
Determine the output of the program.
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char eqn[20] = {'1', '+', '1', '=', '2', '\0'};

cout << strlen(eqn);


cout << strlen("1 + 1 = 2");
return 0;
}

(a) 52
(b) 59
(c) 62
(d) 65
36

36
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.3.2
Given that the user enters "Bye" for the program below, determine
which statement(s) can be filled in the blank below to display the
word, Bye. You may select more than one statements.

int main()
Select statement(s):
{
(a) strcpy(str, "Bye");
char ch[30];
char str[30] = "Good night"; (b) strcpy(ch, str);
(c) strcpy(str, ch);
cout << "User entry: "; (d) strcpy(ch[ ], str[ ]);
cin >> ch ; (e) strcpy(str[30], ch[30]);
?
______________
cout << str;
return 0;
}

37

37

Official (Open), Non‐sensitive

Access Array with Loop


#include <iostream>
using namespace std;

int main()
{
int marks[5]; //An array to store module scores
int i;
Loop is very useful for
//Enter scores by user accessing array elements.
for (i=0; i<5; i++)
{
cout << "Enter module score: ";
cin >> marks[i];
} Loop is very useful for
accessing array elements.
//Display scores
for (i=0; i<5; i++)
{
cout << "Module " << i+1 << ": " << marks[i] << endl;
}

return 0;
}
38

38
Chapter 7 Array and String

Official (Open), Non‐sensitive

Access Array with Loop


#include <iostream>
using namespace std;

int main() Array Size = 5


{
int marks[5]; //An array to store module scores
int i;
When running through the loop,
//Enter scores by user
i changes from 0, 1, 2, 3 to 4.
for (i=0; i<5; i++)
{
cout << "Enter module score: "; Enter module score: 96 when i = 0
cin >> marks[i]; Enter module score: 47 when i = 1
} Enter module score: 85 when i = 2
Enter module score: 64 when i = 3
: when i = 4
i changes from 0, 1, 2, 3 to 4. Enter module score: 40
:
}

96
? 47
? 85
? 64
? 40
?

marks[0] marks[1] marks[2] marks[3] marks[4]


39

39

Official (Open), Non‐sensitive

Access Array with Loop


:
: When running through the loop,
i changes from 0, 1, 2, 3 to 4.
//Display scores
for (i=0; i<5; i++)
{
cout << "Module " << i+1 << ": " << marks[i] << endl;
}
i+1 changes from i changes from
return 0; 1, 2, 3, 4 to 5. 0, 1, 2, 3 to 4.
}

96 47 85 64 40
marks[0] marks[1] marks[2] marks[3] marks[4]

i+1 marks[i]

Module 1: 96 when i = 0
Module 2: 47 when i = 1
Module 3: 85 when i = 2
Module 4: 64 when i = 3
Module 5: 40 when i = 4
40

40
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.4.1
Fill in the blank. The program segment
below computes the average mark.

sum = 0;
for (i=0; i<5; i++) ?
sum += marks[_];
average = sum/5;

41

41

Official (Open), Non‐sensitive

Quiz 7.4.2
Fill in the blank. The program segment
below computes the number of students
who scores grade A which is 80 marks or
above.
gradeA = 0;
for (i=0; i<5; i++)
{
if (marks[i]__________)
gradeA++;
}

42

42
Chapter 7 Array and String

Official (Open), Non‐sensitive

2-Dimensional Array
Arrays in C can have multiple indexes or subscripts.
A common use of such arrays is to represent tables of
values consisting of information arranged in rows and
columns.
To identify a particular table element, two indexes are
required: The first index identifies the element’s row and
the second index identifies the element’s column.
Referred to as double-index array, double-subscripted
array or 2-dimensional array.

43

43

Official (Open), Non‐sensitive

2-Dimensional Array Declaration


Syntax
data_type array_name [row_size] [column_size];

E.g. char alph[2][3]; // Declare an array to store 2 rows & 3 columns


// of characters. The name of the array is alph.

row index of an column index of an


individual element individual element

alph[0][0] alph[0][1] alph[0][2]

Column 0 Column 1 Column 2


Row 0 ? ? ?
Row 1 ? ? ?

alph[1][0] alph[1][1] alph[1][2]

alph
44

44
Chapter 7 Array and String

Official (Open), Non‐sensitive

2-Dimensional Array Initialization


As with single-index array, we can assign values to double-index array
when declaring it.

#include <iostream>
using namespace std;

int main()
{
char alph[2][3] = { {'A', 'B', 'C'}, {'X', 'Y', 'Z'} };
char alph[2][3] = {'A', 'B', 'C', 'X', 'Y', 'Z'};
:
:
}
Column 0 Column 1 Column 2
Row 0 'A' 'B' 'C'
Row 1 'X' 'Y' 'Z'

alph
45

45

Official (Open), Non‐sensitive

2-Dimensional Array Initialization


#include <iostream>
using namespace std;
int main()
{
int marks[3][2] = { {3, 0}, {-2, 20}, {10, 7} };
// or int marks[3][2] = {3, 0, -2, 20, 10, 7};
:
:
}
Column 0 Column 1
Row 0 3 0
Row 1 -2 20
Row 2 10 7

marks

46

46
Chapter 7 Array and String

Official (Open), Non‐sensitive

2-Dimensional Array Assignment


#include <iostream>
using namespace std;

int main()
{
char alph[2][3];
alph[0][1] = 'A'
'A';
alph[1][0] = 'C'
'C';
alph[0][0] = '%'
'%';
alph[1][2] = '4'
'4';
:
:
}
Column 0 Column 1 Column 2
Row 0 ? ? ?
Row 1 ? ? ?

alph
47

47

Official (Open), Non‐sensitive

Assessing 2-Dimensional Array


#include <iostream>
using namespace std; We normally use nested loops
to access elements in multiple-
int main() scripted arrays.
{
// 5 students, 3 subjects
int marks[5][3]; Use outer loop to cycle through
int i, j; all the students. (Row)

// Getting the marks


for (i=0; i < 5; i++) Use inner loop to cycle
{ through all the subject for
for (j=0; j<3; j++) each student. (Column)
{
cout << "Enter marks for student " << i+1;
cout << ", subject " << j+1 << ": ";
cin >> marks[i][j];
}
}
48

48
Chapter 7 Array and String

Official (Open), Non‐sensitive

Assessing 2-Dimensional Array


// Display the marks
cout << "\n\t\t\tSubject 1\tSubject 2\tSubject 3"<< endl;
for (i=0; i < 5; i++)
{
cout << "Marks for student " << i+1;
cout << "\t";
for (j=0; j<3; j++)
{
cout << " " << marks[i][j] << "\t\t";
}
cout << "\n";
} Nested loop is again use
return 0; to process the marks in
} each element of the 2
dimensional array.

49

49

Official (Open), Non‐sensitive

Assessing 2-Dimensional Array

50

50
Chapter 7 Array and String

Official (Open), Non‐sensitive


Write to 2-Dimensional Array i i<5 Proc Cal
inner i++
j j<3 Proc Write to Cal
cout marks[i][j] j++
Proc: j loop & cin
#include <iostream> Process 0 T Yes j=0
using namespace std;
0 i=0 0 T Yes 10
int main() 1
{ 0 1 T Yes 20
// 5 students, 3 subjects
2
int marks[5][3];
int i, j; 0 2 T Yes 30
3
// Getting the marks 0 3 F No
for (i=0; i < 5; i++)
{ 1
for (j=0; j<3; j++) 1 T Yes j=0
{ 1 0 T Yes 90
cout << "Enter marks for student " << i+1;
1
cout << ", subject " << j+1 << ": ";
cin >> marks[i][j]; 1 1 T Yes 50
} 2
} 1 2 T Yes 40
Enter marks for student 1, subject 1: 10 3
Enter marks for student 1, subject 2: 20
Enter marks for student 1, subject 3: 30 1 3 F No
Enter marks for student 2, subject 1: 90 2
Enter marks for student 2, subject 2: 50
Enter marks for student 2, subject 3: 40 2 T Yes j=0
Enter marks for student 3, subject 1: 60 2 0 T Yes 60
51

51

Official (Open), Non‐sensitive


Write to 2-Dimensional Array i i<5 Proc Cal
inner i++
j j<3 Proc Write to Cal
cout marks[i][j] j++
j loop & cin
#include <iostream>
2 T Yes j=0
using namespace std;
2 0 T Yes 60
int main() 1
{ 2 1 T Yes 70
// 5 students, 3 subjects
2
int marks[5][3];
int i, j; 2 2 T Yes 25
3
// Getting the marks 2 3 F No
for (i=0; i < 5; i++)
{ 3
for (j=0; j<3; j++) 3 T Yes j=0
{ 3 0 T Yes 95
cout << "Enter marks for student " << i+1;
1
cout << ", subject " << j+1 << ": ";
cin >> marks[i][j]; 3 1 T Yes 15
} 2
} 3 2 T Yes 63
Enter marks for student 2, subject 1: 60 3
Enter marks for student 2, subject 2: 70
Enter marks for student 2, subject 3: 25 3 3 F No
Enter marks for student 3, subject 1: 95 4
Enter marks for student 3, subject 2: 15
Enter marks for student 3, subject 3: 63 4 T Yes j=0
Enter marks for student 4, subject 1: 17 4 0 T Yes 17
52

52
Chapter 7 Array and String

Official (Open), Non‐sensitive


Write to 2-Dimensional Array
#include <iostream>
using namespace std;

int main() i i<5 Proc Cal j j<3 Proc Write to Cal


{ inner i++ cout marks[i][j] j++
// 5 students, 3 subjects j loop & cin
int marks[5][3]; 4 T Yes j=0
int i, j;
4 0 T Yes 17
// Getting the marks 1
for (i=0; i < 5; i++) 4 1 T Yes 55
{
2
for (j=0; j<3; j++)
{ 4 2 T Yes 90
cout << "Enter marks for student " << i+1; 3
cout << ", subject " << j+1 << ": "; 4 3 F No
cin >> marks[i][j];
5
}
} 5 F No

Enter marks for student 5, subject 1: 17 Exit


Enter marks for student 5, subject 2: 55 i loop
Enter marks for student 5, subject 3: 90

53

53

Official (Open), Non‐sensitive


Read 2-Dimensional Array i i<5 Proc Cal
inner i++
j j<3 Proc Write to Cal
cout marks[i][j] j++
j loop
#include <iostream>
0 T Yes j=0
using namespace std;
0 i=0 0 T Yes 10
int main()
1
{
// Getting the marks 0 1 T Yes 20
⋮ 2
// Display the marks 0 2 T Yes 30
cout << "\n\t\t\tSubject 1\tSubject 2\tSubject 3"<< endl;
3
for (i=0; i < 5; i++)
{ 0 3 F No
cout << "Marks for student " << i+1;
1
cout << "\t";
for (j=0; j<3; j++) 1 T Yes j=0
{
1 0 T Yes 90
cout << " " << marks[i][j] << "\t\t";
} 1
cout << "\n";
1 1 T Yes 50
}
return 0; 2
}
1 2 T Yes 40
Subject 1 Subject 2 Subject 3 3
Marks for student 1 10 20 30
Marks for student 2 90 50 40 1 3 F No
Marks for student 3 60 2
2 T Yes j=0
2 0 T Yes 60
54

54
Chapter 7 Array and String

Official (Open), Non‐sensitive


Read 2-Dimensional Array i i<5 Proc Cal
inner i++
j j<3 Proc Write to Cal
cout marks[i][j] j++
j loop & cin
#include <iostream>
2 T Yes j=0
using namespace std;
2 0 T Yes 60
int main()
1
{
// Getting the marks 2 1 T Yes 70
⋮ 2
// Display the marks 2 2 T Yes 25
cout << "\n\t\t\tSubject 1\tSubject 2\tSubject 3"<< endl;
3
for (i=0; i < 5; i++)
{ 2 3 F No
cout << "Marks for student " << i+1;
3
cout << "\t";
for (j=0; j<3; j++) 3 T Yes j=0
{
3 0 T Yes 95
cout << " " << marks[i][j] << "\t\t";
} 1
cout << "\n";
3 1 T Yes 15
}
return 0; 2
}
3 2 T Yes 63
Subject 1 Subject 2 Subject 3 3
Marks for student 1 10 20 30
Marks for student 2 90 50 40 3 3 F No
Marks for student 3 60 70 25 4
Marks for student 4 95 15 63
4 T Yes j=0
4 0 T Yes 17
55

55

Official (Open), Non‐sensitive


Read 2-Dimensional Array
#include <iostream>
using namespace std;

int main()
{ i i<5 Proc Cal j j<3 Proc Write to Cal
// Getting the marks inner i++ cout marks[i][j] j++
j loop & cin

// Display the marks 4 T Yes j=0
cout << "\n\t\t\tSubject 1\tSubject 2\tSubject 3"<< endl; 4 0 T Yes 17
for (i=0; i < 5; i++) 1
{
cout << "Marks for student " << i+1; 4 1 T Yes 55
cout << "\t"; 2
for (j=0; j<3; j++)
{ 4 2 T Yes 90
cout << " " << marks[i][j] << "\t\t"; 3
}
cout << "\n"; 4 3 F No
} 5
return 0;
} 5 F No

Subject 1 Subject 2 Subject 3 Exit


Marks for student 1 10 20 30 i loops
Marks for student 2 90 50 40
Marks for student 3 60 70 25
Marks for student 4 95 15 63
Marks for student 5 17 55 90

56

56
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.5.1
Determine the output of the program.
#include <iostream>
using namespace std;

int main()
{
int table[4][3] = {9, 0, 6, 3, 1, 8, 5, 3, 9, 2, 4, 7};
table[2][0] = table[0][0];
cout << table[2][0] - table[3][1] << endl;
return 0;
}

(a) 1
(b) 5
(c) 6
(d) 7
57

57

Official (Open), Non‐sensitive

Quiz 7.5.2
Fill in the missing statement.
#include <iostream> cout<<"\nMatrix B =\n";
using namespace std; for (i=0; i<4; i++)
{
int main() for (j=0; j<2; j++)
{ cout<<matrix_B[i][j]<<"\t";
int matrix_A[2][4] = {11, 13, 17,
0, -19, -17, -13, -11}; cout<<endl;
}
int matrix_B[4][2], i, j; return 0;
}
cout<<"Matrix A =\n"; Output Window of the Program
for (i=0; i<2; i++)
{ Matrix A =
for (j=0; j<4; j++)
cout<<matrix_A[i][j]<<"\t"; 11 13 17 0
cout<<endl; -19 -17 -13 -11
}
Matrix B =
//Matrix B = Transpose of Matrix A 11 -19
for (i=0; i<4; i++) 13 -17
for (j=0; j<2; j++) 17 -13
? 0 -11

Process returned 0 (0x0)


execution time : 0.127 s
Press any key to continue.
58

58
Chapter 7 Array and String

Official (Open), Non‐sensitive

Passing Array by Reference


We don’t pass arrays to functions by value
and make local copies but pass by
reference.
Making local copies takes up time and
memories.

59

59

Official (Open), Non‐sensitive


#include <iostream>
using namespace std;
void add5marks(int marks[], int s);
int main()
{
int i, marks[7];
7 students in the group.
//Mark entry
for (i=0; i<7; i++)
{
cout << "Enter next student: ";
cin >> marks[i];
} Passing array, marks, from main( )
to add5marks( ) by reference.
//Add 5 marks
add5marks(marks, 7);
//Display results Passing integer 7 from main( ) to
add5marks( ) by value.
for (i=0; i<7; i++)
cout << "Student " << i+1 << ": " << marks[i] << "\n";

return 0; 5 marks has already been added


} for each student by add5marks( ).
60

60
Chapter 7 Array and String

Official (Open), Non‐sensitive

Need not to return updated In the main function,


marks from add5marks( ) to add5marks is called by
main( ). add5marks(marks, 7);

//This function adds 5 to each array element.

void add5marks(int marks[], int s)


{ Address of the 1st element of array, s is a local variable
int i; marks, is passed from main( ). copies the student
group size of 7 from
for(i=0; i<s; i++) main( ).

return marks;
marks[i] = marks[i] + 5;
With the reference address,
return; memory of the array declared in
main( ) is accessed and updated.
} Need not to return
updated marks from
add5marks( ) to main( ).

61

61

Official (Open), Non‐sensitive

Passing Array by Reference


Passing by reference: The address of the 1st element of the array, is
passed from main( ) to add5marks( ).
add5marks(marks, 7);
No local copy of the array is created in add5marks( ).
Based on the address, add5marks( ) locates the memory of the
array and adds 5 to each element.
marks[i] = marks[i] + 5;
∵ There is only one copy of the array in the whole program.
∴ Any changes in the array will be effective for all functions in the
program.
∴ Need not to return the updated array from add5marks( ) to main( ).
Advantage: Reduce required memory size and time for copying
entire array.

62

62
Chapter 7 Array and String

Official (Open), Non‐sensitive

Passing Array by Reference


Pay attention on these 3 lines. See their relationship and differences.
#include <iostream>
Function Prototype

using namespace std; Alternate way to write prototype:


void add5marks(int[], int);
//Prototype
void add5marks(int marks[], int s);
int main()
{ This statement calls the
int i, marks[7]; function add5marks( )
:
:
add5marks(marks, 7); //Call or activate another
No void
: //function
:
return 0; No int and [ ]
Function Definition

} Just array name

void add5marks(int marks[], int s)


{
:
:
return;
} 63

63

Official (Open), Non‐sensitive

Passing Array by Reference


Previous e.g., an array is passed to
add5marks( ) by reference,
but add5marks( ) doesn't return a value.
See another example:
Pass an array to a function by reference,
but this function returns a value.

64

64
Chapter 7 Array and String

Official (Open), Non‐sensitive


The following program passes an array by reference to a function.
The function returns the average of the array to main( ).
#include <iostream>
Function Prototype

using namespace std;


//Prototype
double avMark(int marks[], int s);
int main()
{
int i, marks[7]; • This statement calls the function AvMark( ).
double ave; • The returned value is assigned to variable, ave.
:
:
ave = avMark(marks, 7); //Call or activate another
: //function
:
return 0;
Function Definition

double avMark(int marks[], int s)


{
:
: • The function calculates the average score and
return average; • return the value to main( ).
} 65

65

Official (Open), Non‐sensitive

The complete program (slide 1 of 2):


#include <iostream>
using namespace std;
//Prototype
double avMark(int marks[], int s);
int main()
int i, marks[7];
double ave;
for (i=0; i<7; i++)
{
cout << "Enter score of student " << i+1 << ": ";
cin >> marks[i];
}
ave = avMark(marks, 7);
cout << "\nThe average score is " << ave <<endl;

return 0;
}

66

66
Chapter 7 Array and String

Official (Open), Non‐sensitive


The complete program (slide 2 of 2):
double avMark(int marks[], int s)
{
double sum, average;
int i;
for (sum=0, i=0; i<s; i++)
sum += marks[i];
average = sum/s;

return average;
}

67

67

Official (Open), Non‐sensitive

Quiz 7.6.1
Fill in the prototype for EnterMark ( )
#include <iostream> void enterMark(int marks[], int s)
using namespace std; {
int i;
//Prototype
? for (i=0; i<s; i++){
double avMark(int marks[], int s); cout << "Enter mark of student "
<< i+1 << ": ";
int main() cin >> marks[i];
{ }
int marks[7];
double ave; return;
}
enterMark(marks, 7);
ave = avMark(marks, 7); double avMark(int marks[], int s)
{
cout << "\nAverage mark = " double sum, ave;
<< ave << endl; int i;
return 0;
} for (sum=0, i=0; i<s; i++)
sum += marks[i];

ave = sum/s;
return ave;
}
68

68
Chapter 7 Array and String

Official (Open), Non‐sensitive

Quiz 7.6.2
Fill in the missing statement.
#include <iostream> void enterMark(int marks[], int s)
using namespace std; {
int i;
//Prototype
void enterMark(int marks[], int s); for (i=0; i<s; i++){
int findMax(int marks[], int s); cout << "Enter mark of student "
int main() << i+1 << ": ";
{ cin >> marks[i];
int marks[7], maxMark; }
enterMark(marks, 7); return;
}
?
int findMax(int marks[], int s)
cout << "\nHighest mark = "
<< maxMark << endl; {
int i, curMax;
return 0;
} curMax = marks[0];
for (i=1; i<s; i++){
if (curMax < marks[i])
curMax = marks[i];
}
return curMax;
}

69

69

Official (Open), Non‐sensitive

Quiz 7.6.3
Fill in the missing statement.
#include <iostream> void enterMark(int marks[], int s)
using namespace std; {
int i;
//Prototype
void enterMark(int marks[], int); for (i=0; i<s; i++){
double passRate(int marks[], int); cout << "Enter mark of student "
int main() << i+1 << ": ";
{ cin >> marks[i];
int marks[7]; }
return;
enterMark(marks, 7); }
cout << "\nPassing Rate = "
<< passRate(marks, 7) ?
<< "%\n"; {
int i;
return 0;
} double numPass;

for (numPass=0, i=0; i<s; i++)


if (marks[i] >= 50)
numPass++;n
return numPass/s*100;
}

70

70

You might also like