0% found this document useful (0 votes)
5 views121 pages

Chapter5 6

Chapter5+6

Uploaded by

mohamedsame7105
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)
5 views121 pages

Chapter5 6

Chapter5+6

Uploaded by

mohamedsame7105
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/ 121

Computer Skills – 2 (C++)

5. CONTROL STRUCTURES
(REPETITION)
Second Semester 2023/2024

C++ Programming From Problem Analysis to Program Design


www.tutorialspoint.com
Control Structures
 A computer can process a program in one of the following ways:
1. Sequence.
2. Selectively (branch).
3. Repetitively(loop).
4. Calling a function.

2
Why Is Repetition Needed?

 Suppose you want to add and average 100, 1000, or more numbers.
 Declare many variables and list them again in cin and cout statements.
This takes an exorbitant amount of space and time (impractical). 3
Why Is Repetition Needed?
 Suppose you want to add the following numbers: 5 3 7 9 4
 Consider the following statements

 The second statement initializes sum to 0.


 After statements 3 and 4, Statement 3 stores 5 in num; statement 4
updates the value of sum by adding num to it. After statement 4, the value
of sum is 5.
4
Why Is Repetition Needed?

 Let us repeat statements 3 and 4.


– After statement 3: num = 3
– After statement 4: sum = sum + num = 5 + 3 = 8.
Now, sum contains the sum of the first two numbers.
 And so on for 7, 9, and 4
5
 C++ has three repetition, or looping, structures that let you
repeat statements over and over until certain conditions are met.

1. while loop
2. for loop
3. do while loop

6
1. while Looping (Repetition) Structure

 The general form of the while statement is:

 while is a reserved word.


 The statement can be either a simple or compound statement.
 The expression acts as a decision maker and is usually a logical
expression.
 The statement is called the body of the loop.
 The parentheses around the expression are part of the syntax. 7
1. while Looping (Repetition) Structure

The flow of execution of a while loop.

8
1. while Looping (Repetition) Structure

 The expression provides an entry condition.


 If it initially evaluates to true, the statement executes. The loop
condition—the expression—is then reevaluated. If it again
evaluates to true, the statement executes again. The
statement (body of the loop) continues to execute until the
expression is no longer true.

 A loop that continues to execute endlessly is called an infinite loop.


 To avoid an infinite loop, make sure that the loop’s body contains
statement(s) that assure that the exit condition—the expression in the
while statement—will eventually be false.
9
1. while Looping (Repetition) Structure

10
1. while Looping (Repetition) Structure
 The variable i (in Line 2 from previous example ) in the expression is
called the loop control variable.

 Note the following from previous example:


 Within the loop, i becomes 25 but is not printed because the entry
condition is false.
 If you omit the statement: i = i + 5; from the body of the loop,
you will have an infinite loop, continually printing rows of zeros.

 You must initialize the loop control variable i before you execute the
loop.
 If the statement: i = 0; (in Line 1) is omitted, the complier generate a
syntax error. (system dependent)
11
1. while Looping (Repetition) Structure

semantic error, Why?

12
1. while Looping (Repetition) Structure

 If you put a semicolon at the end of the while loop, (after the logical
expression), then the action of the while loop is empty or null.
13

 The statements within the braces do not form the body of the while loop.
2. for Looping (Repetition) Structure
 The for looping structure is a specialized form of the while loop.
 Its primary purpose is to simplify the writing of counter-controlled
loops.
 The general form of the for statement is:
1 2 4

 The initial statement, loop condition, and update statement (called


for loop control statements) enclosed within the parentheses control
the body (statement) of the for statement.
 for is a reserved word.
14
2. for Looping (Repetition) Structure

The flow of execution of a for loop. 15


2. for Looping (Repetition) Structure

 The for loop executes as follows:


1. The initial statement executes, (executes only once).

2. The loop condition is evaluated. If the loop condition evaluates to true


- Execute the for loop statement.
- Execute the update statement (the third expression in the parentheses).

3. Repeat Step 2 until the loop condition evaluates to false.

 The initial statement usually initializes a variable (called the for loop
control, or for indexed, variable).
16
2. for Looping (Repetition) Structure
 The following for loop prints the first 10 nonnegative integers:
for (i = 0; i < 10; i++)
cout << i << " ";
cout << endl;

 The initial statement, i = 0; , initializes the int variable i to 0.


 Next, the loop condition, i < 10, is evaluated.
 Because 0 < 10 is true, the print statement executes and outputs 0.
 The update statement, i++, then executes, which sets the value of i to 1.
 Once again, the loop condition is evaluated, which is still true, and so on.
 When i becomes 10, the loop condition evaluates to false, the for loop
terminates, and the statement following the for loop executes.
17
2. for Looping (Repetition) Structure
 A for loop can have either a simple or compound statement.

The following for loop outputs Hello! and a star (on separate lines)
five times:
for (i = 1; i <= 5; i++)
{ cout << "Hello!" << endl; cout << "*" << endl; }

 Consider the following for loop:


for (i = 1; i <= 5; i++)
cout << "Hello!" << endl;
cout << "*" << endl;
- This loop outputs Hello! five times and the star only once.

18
2. for Looping (Repetition) Structure
 The following for loop executes five empty statements:

for (i = 0; i < 5; i++); //Line 1


cout << "*" << endl; //Line 2

 The semicolon at the end of the for statement (before the output
statement, Line 1) terminates the for loop.
 The action of this for loop is empty, that is, null.

19
The following are some comments on for loops:
 If the loop condition is initially false, the loop body does not execute.

 The update expression, when executed, changes the value of the loop
control variable (initialized by the initial expression), which eventually
sets the value of the loop condition to false.

 The for loop body executes indefinitely if the loop condition is always
true.

 A semicolon at the end of the for statement (just before the body of the
loop) is a semantic error. In this case, the action of the for loop is
empty.

20
The following are some comments on for loops:
 In the for statement, if the loop condition is omitted, it is assumed to
be true.

 In a for statement, you can omit all three statements—initial


statement, loop condition, and update statement.

 The following is a legal for loop:


for ( ; ; )
cout << "Hello" << endl;

This is an infinite for loop, continuously printing the word Hello.

21
2. for Looping (Repetition) Structure
 You can count backward using a for loop if the for loop control
expressions are set correctly.

 For example, consider the following for loop:


for (i = 10; i >= 1; i--)
cout << " " << i ;
cout << endl;

 In this for loop, the variable i is initialized to 10. After each iteration of
the loop, i is decremented by 1.
22
 The loop continues to execute as long as i >= 1.
2. for Looping (Repetition) Structure

 You can increment (or decrement) the loop control variable by any
fixed number.

 In the following for loop, the variable is initialized to 1; at the end of the
for loop, i is incremented by 2.

 This for loop outputs the first 10 positive odd integers.

for (i = 1; i <= 20; i = i + 2)


cout << " " << i;
cout << endl;

23
2. for Looping (Repetition) Structure

 Suppose that i is an int variable. Consider the following for loop:


for (i = 10; i <= 9; i++)
cout << i << " ";
cout << endl;
 In this for loop, the initial statement sets i to 10. Because initially the
loop condition (i <= 9) is false, nothing happens.

24
2. for Looping (Repetition) Structure

 Consider the following for loop:

for (i = 9; i >= 10; i--)


cout << i << " ";
cout << endl;
 In this for loop, the initial statement sets i to 9. Because initially the
loop condition (i >= 10) is false, nothing happens.

25
2. for Looping (Repetition) Structure
 Consider the following for loop:
for (i = 10; i <= 10; i++) //Line 1
cout << i << " "; //Line 2
cout << endl; //Line 3

 In this for loop, the initial statement sets i to 10.


 The loop condition (i <= 10) evaluates to true, so the output statement
in Line 2 executes, which outputs 10.
 Next, the update statement increments the value of i by 1, so the value
of i becomes 11.
 Now the loop condition evaluates to false and the for loop terminates.
 Note that the output statement in Line 2 executes only once.
26
2. for Looping (Repetition) Structure
 Consider the following for loop:

for (i = 1; i <= 10; i++); //Line 1


cout << i << " "; //Line 2
cout << endl; //Line 3

 This for loop has no effect on the output statement in Line 2.


 The semicolon at the end of the for statement terminates the for
loop; the action of the for loop is thus empty.
 The output statement is all by itself and executes only once.

27
2. for Looping (Repetition) Structure

 Consider the following for loop:


for ( i = 1; ; i++ )
cout << i << " ";
cout << endl;
 In this for loop, because the loop condition is omitted from the for
statement, the loop condition is always true. This is an infinite loop.

28
3. do … while Looping (Repetition) Structure
 The general form of a do. . .while statement is as follows:

 do is a reserved word.
 The statement can be either a simple or compound statement.
 The statement executes first, and then the expression is evaluated.
If the expression evaluates to true, the statement executes again.
 As long as the expression in a do...while statement is true, the
statement executes.
 To avoid an infinite loop, you must, once again, make sure that the
loop body contains a statement that ultimately makes the
29
expression false and assures that it exits properly.
3. do … while Looping (Repetition) Structure

The flow of execution of a do .. while loop


30
3. do … while Looping (Repetition) Structure

31
Pretest loop

 In a while and for loop, the loop condition is evaluated before


executing the body of the loop. Therefore, while and for loops
are called pretest loops.

 Because the while and for loops both have entry conditions,
these loops may never activate.

32
Postest loop

 The loop condition in a do...while loop is evaluated after executing


the body of the loop. Therefore, do...while loops are called
posttest loops.

 The do...while loop, on the other hand, has an exit condition and
therefore always executes the statement at least once.

33
Pretest and Postest loop

34
break statement

 The break statement, when executed in while, for, and


do...while loops, provides an immediate exit from the loop
structure.

Why?
Used for exit early from a loop.
 After the break statement executes, the program continues to
execute with the first statement after the loop structure.

35
break statement

36
break statement

37
continue statement

 When the continue statement is executed in a loop, it skips the


remaining statements in the loop and proceeds with the next
iteration of the loop.

38
continue statement

 In a while and do. . .while structure, the expression (that is, the
loop-continue test) is evaluated immediately after the continue
statement.

 In a for structure, the update statement is executed after the


continue statement, and then the loop condition (that is, the loop-
continue test) executes.

39
continue statement

40
continue statement

41
Nested Control Structures - nested loops

 A loop can be nested inside of another loop.

The syntax for a nested for loop statement is as follows:

for (initial statement; loop condition; update statement)


{
for (initial statement; loop condition; update statement)
{
statement(s);
}
statement(s);
}
42
Nested Control Structures - nested loops

 The syntax for a nested while loop statement in C++ is as


follows:

while(expression)
{
while(expression)
{
statement(s);
}
statement(s);
}

43
Nested Control Structures - nested loops

 The syntax for a nested do...while loop statement in C++ is as


follows:

do
{
statement(s);
do
{
statement(s);
}while(expression);
} while(expression);

44
Nested Control Structures - nested loops
for (i = 5; i >= 1; i--)
* for (i = 1; i <= 5; i++) //Line 1
** { //Line 2
*** for (j = 1; j <= i ; j++) //Line 3
**** cout << "*";
cout << endl;
//Line 4
//Line 5
***** } //Line 6

- The for loop in Line 1 starts with i = 1.

- When i is 1, the inner for loop in Line 3 outputs one star and the
insertion point moves to the next line.

- Then i becomes 2, the inner for loop outputs two stars, and the
output statement in Line 5 moves the insertion point to the next line.

-And so on, until i becomes 6 and the loop stops. 45


Example #1

46
Example #2

47
Example #3

48
Example #4

49
Example #5

50
Example #6

51
Example #7

What does a break statement do in


a loop?

52
Example #8

53
Example #9

54
Computer Skills – 2 (C++)
CONTROL STRUCTURES
(REPETITION)
Second Semester 2023/2024
Exercises

C++ Programming From Problem Analysis to Program Design


www.tutorialspoint.com
1 ) State what output, if any, results from each of the following statements:
a. for (i = 1; i <= 1; i++) cout << "*";
cout << endl;

b. for (i = 2; i >= 1; i++) cout << "*";


cout << endl;

c. for (i = 1; i <= 1; i--) cout << "*"; cout << endl;

d. for (i = 12; i >= 9; i--) cout << "*"; cout << endl;

e. for (i = 0; i <= 5; i++) cout << "*"; cout << endl;

f. for (i = 1; i <= 5; i++) { cout << "*"; i = i + 1; } 56

cout << endl;


2) Write a for statement to add all the multiples of 3 between 1 and 100.

3) Given the following program segment:


for (number = 1; number <= 10; number++)
cout << number;

- write a while loop and a do...while loop that have the same output.

57
4) How many times will each of the following loops execute? What is
the output in each case?
A) x = 5; y = 50;
do
x = x + 10;
while (x < y);
cout << x << " " << y << endl;

B) x = 5; y = 80;
do
x = x * 2;
while (x < y);
58

cout << x << " " << y << endl;


C) x = 5; y = 20;
do
x = x + 2;
while (x >= y);
cout << x << " " << y << endl;

D) x = 5; y = 35;
while (x < y)
x = x + 10;
cout << x << " " << y << endl;

59
Computer Skills – 2 (C++)
6. Arrays
Second Semester 2023/2024

C++ Programming From Problem Analysis to Program Design


www.tutorialspoint.com
 Suppose you want to read 100 (or more) numbers and print them in
reverse order, you would have to declare 100 variables and write
many cin and cout statements.
61

 Thus, for large amounts of data, this type of program is not desirable.
 Note the following in the previous program:

1. Five variables must be declared because the numbers are to be


printed in reverse order.

2. All variables are of type int—that is, of the same data type.

3. The way in which these variables are declared indicates that the
variables to store these numbers all have the same name — except
the last character, which is a number.

62
C++ Arrays

 Array: is a collection of a fixed number of components all of the


same data type.

 One-dimensional array.
 Two-dimensional array.

63
C++ Arrays
 One-dimensional array.
 Is an array in which the components are arranged in a list form.

 The general form for declaring a one-dimensional array is:

 intExp: - Is any constant expression that evaluates to a positive integer.


- Specifies the number of components in the array.

64
C++ Arrays - One-dimensional array.
Example:
int num[5];
 Declares an array num of five components.
 Each component is of type int.
 The components are num[0], num[1], num[2], num[3], and num[4].

65
C++ Arrays - One-dimensional array.
 Accessing Array Components

 The general form (syntax) used for accessing an array component is:

 indexExp:
 index, is any expression whose value is a nonnegative integer.
 The index value specifies the position of the component in the array.
 The array index starts at 0.

 In C++, [ ] is an operator called the array subscripting operator.


66
C++ Arrays - One-dimensional array.
Example: int list[10];
 This statement declares an array list of 10 components.
 The components are list[0], list[1], . . ., list[9].

 The assignment statement: list[5] = 34;


 Stores 34 in list[5], which is the sixth component of the array
list.

67
C++ Arrays - One-dimensional array.
 Suppose i is an int variable. Then, the assignment statement:

i = 3;
list[3] = 63; is equivalent to
list[i] = 63;

 If i is 4, then the assignment statement: list[2 * i - 3] = 58;


Stores 58 in list[5] because: 2 * i - 3 evaluates to 5.
The index expression is evaluated first, giving the position of the
component in the array.
68
C++ Arrays - One-dimensional array.

 Consider the following statements:


list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];

69
C++ Arrays - One-dimensional array.

 You can also declare arrays as follows:


const int ARRAY_SIZE = 10;
int list[ARRAY_SIZE];
 That is, you can first declare a named constant and then use the value of
the named constant to declare an array and specify its size.

 When you declare an array, its size must be known.


Example: You cannot do the following:
int arraySize; //Line 1
cout << "Enter the size of the array: "; //Line 2
cin >> arraySize; //Line 3
70
int list[arraySize]; //Line 4; not allowed
C++ Arrays - One-dimensional array.

 Processing One-Dimensional Arrays


 Some of the basic operations performed on a one-dimensional array:
 Initializing.
 Inputting data.
 Outputting data stored in an array.
 Finding the largest and/or smallest element, etc.

71
C++ Arrays - One-dimensional array.
 Processing One-Dimensional Arrays

Example: Suppose that we have the following statements:


int list[100]; //list is an array of size 100
int i;

 The following for loop steps through each element of the array list,
starting at the first element of list:

for (i = 0; i < 100; i++) //Line 1


//process list[i] //Line 2 (cin, cout)

72
C++ Arrays - One-dimensional array.
Example
//Declaration
double sales[10];
int index;
double largestSale, sum, average;

1. Initializing an array: The following loop initializes every component


of the array sales to 0.0.

for (index = 0; index < 10; index++)


sales[index] = 0.0;

73
C++ Arrays - One-dimensional array.

2. Reading data into an array: The following loop inputs the data into
the array sales. (using the keyboard).

for (index = 0; index < 10; index++)


cin >> sales[index];

74
C++ Arrays - One-dimensional array.

3. Printing an array: The following loop outputs the array sales.

for (index = 0; index < 10; index++)


cout << sales[index] << " ";

4. Finding the sum and average of an array:


sum = 0;
for (index = 0; index < 10; index++)
sum = sum + sales[index];
average = sum / 10;
75
C++ Arrays - One-dimensional array.

5. Largest element in the array:

maxIndex = 0;
for (index = 1; index < 10; index++)
if (sales[maxIndex] < sales[index])
maxIndex = index;
largestSale = sales[maxIndex];

76
C++ Arrays - One-dimensional array.
//Program to read five numbers, find their sum, and print the numbers in reverse order.
#include <iostream>
using namespace std;
void main( )
{ int item[5]; //Declare an array item of five components
int sum=0, counter;
cout << "Enter five numbers: ";
for (counter = 0; counter < 5; counter++)
{ cin >> item[counter];
sum = sum + item[counter]; }
cout << "\n The sum of the numbers is: " << sum << endl;
cout << "The numbers in reverse order are: ";
//Print the numbers in reverse order.
for (counter = 4; counter >= 0; counter--) cout << item[counter] << " ";
cout << endl;
} 77
Array Index Out of Bounds
 Consider the following declaration:
double num[10];
int i;

 The component num[ i ] is valid, that is, i is a valid index if i = 0,


1, 2, 3, 4, 5, 6, 7, 8, or 9.

 The index—say, index—of an array is in bounds if:


(index >= 0) and (index <= ARRAY_SIZE -1)

78
Array Index Out of Bounds

 If either (index < 0) or (index > ARRAY_SIZE -1), then we say that
the index is out of bounds.
 Out-of-bounds array index: – An index value that is either less than
0 or greater than the array size minus 1.

Example:
int list[5];
for (i = 0; i <= 5; i++)
list[i] = 0;

79
Array Initialization During Declaration
 Array can be initialized while it is being declared.

Example:
double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};

 The values are placed between curly braces and separated by


commas.
 sales[0] = 12.25, sales[1] = 32.50, sales[2] = 16.90, sales[3] =
23.00,and sales[4] = 45.68.

 But
double sales[5] = {12.25, 32.50, 16.90, 23, 45.68,8.1};
//Syntax error, Why? Too many initializers. 80
Array Initialization During Declaration

double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};

 When initializing arrays as they are declared, it is not necessary to


specify the size of the array.
 The size is determined by the number of initial values in the braces.
However, you must include the brackets following the array name.
double sales[ ] = {12.25, 32.50, 16.90, 23, 45.68};

Declares sales to be an array of 5 components and initializes list[0] to


12.25, list[1] to 32.50, list[2] to 16.90, list[3] to 23, and list[4] to 45.68.

81
Partial Initialization of Arrays During Declaration

 When declare and initialize an array simultaneously, you do not


need to initialize all components of the array.
 This procedure is called partial initialization of an array during
declaration.

Example1:
int list[10] = {0};
 Declares list to be an array of 10 components and initializes all of
the components to 0.

82
Partial Initialization of Arrays During Declaration
Example2:

int list[10] = {8, 5, 12};


 Declares list to be an array of 10 components and initializes list[0] to
8, list[1] to 5, list[2] to 12, and all other components to 0.

83
Partial Initialization of Arrays During Declaration

Example3: int list[ ] = {5, 6, 3};


 Declares list to be an array of three components and initializes
list[0] to 5, list[1] to 6, and list[2] to 3.

Example4: int list[25] = {4, 7};


 Declares list to be an array of 25 components. The first two
components are initialized to 4 and 7, respectively, and all other
components are initialized to 0.

84
Partial Initialization of Arrays During Declaration

 When you partially initialize an array, then all of the elements that
follow the last uninitialized elements must be uninitialized.

Example: int list[10] = {2, 5, 6, , 8}; //illegal

 In this initialization, because the fourth element is uninitialized, all


elements that follow the fourth element must be left uninitialized.
Therefore, the previous example will result in a syntax error.

85
Some Restrictions on Array Processing
 Example:

int List1[5] = {0, 4, 8, 12, 16}; //Line 1


int List2[5]; //Line 2

 The statement in Line 1 declares and initializes the array List1, and
the statement in Line 2 declares the array List2.
 Note that these arrays are of the same type and have the same
number of components.

86
Some Restrictions on Array Processing

 Suppose that you want to copy the elements of List1 into the
corresponding elements of List2.

 The following statement is illegal:


List2 = List1; //illegal - aggregate operation
This statement will generate a syntax error.

 An aggregate operation on an array is any operation that


manipulates the entire array as a single unit.

87
Some Restrictions on Array Processing

 To copy one array into another array, you must copy it


component—that is, one component at a time.

Example:
for (int index = 0; index < 5; index ++)
List2[index] = List1[index];

88
C++ Arrays - One-dimensional array - Example
double sum=0, ave, maxMark, mark[4], minMark; int index;
cout << "Please enter four marks: \n";
for(int i=0; i<4 ; i++) { cin >> mark[i]; sum += mark[i]; }
ave = sum/4;
int maxIndex=0;
for(index=1; index<4; index++)
if(mark[maxIndex]<mark[index])
maxIndex=index;
maxMark = mark[maxIndex];
int minIndex=0;
for(index=1; index<4; index++)
if(mark[minIndex]>mark[index])
minIndex=index;
minMark = mark[minIndex];
cout << "Average Marks is:" << ave << '\n';
cout << "Max Mark is:" << maxMark << '\n';
89
cout << "Min Mark is:" << minMark << '\n'; }
Two dimensional Arrays
 Two-dimensional array: A collection of a fixed number of
components arranged in rows and columns (that is, in two
dimensions), wherein all components are of the same type.
(provide data in a table form).

 The syntax for declaring a two-dimensional array is:

 Wherein intExp1 and intExp2 are constant expressions yielding


positive integer values.
 The two expressions, intExp1 and intExp2, specify the
number of rows and the number of columns, respectively, in
the array. 90
Two dimensional Arrays
double sales[10][5];

91
Two dimensional Arrays
 Accessing Array Components:
 To access the components of a two-dimensional array, you need
a pair of indices: one for the row position and one for the column
position.

 The syntax to access a component of a two-dimensional array is:

 wherein indexExp1 and indexExp2 are expressions yielding


nonnegative integer values.

 indexExp1 specifies the row position


92

 indexExp2 specifies the column position.


Two dimensional Arrays
 The statement: sales[5][3] = 25.75;
Stores 25.75 into row number 5 and column number 3 (that is, the
sixth row and the fourth column) of the array sales.

 Suppose that: int i = 5; int j = 3;


Then sales[5][3] = 25.75; is equivalent to sales[i][j] = 25.75;
So the indices can also be variables.
93
Two-Dimensional Array Initialization During Declaration
 Consider the following statement:
int board[4][3] = { {2, 3, 1}, {15, 25, 13}, {20, 4, 7}, {11, 18, 14} };

 This statement declares board to be a two-dimensional array of


four rows and three columns.

94
Two-Dimensional Array Initialization During Declaration
 To initialize a two-dimensional array when it is declared:
1. The elements of each row are enclosed within curly braces and
separated by commas.

2. All rows are enclosed within curly braces.

3. For number arrays, if all components of a row are not specified,


the unspecified components are initialized to 0.
-In this case, at least one of the values must be given to
initialize all the components of a row.

95
Two dimensional Arrays

Example1:
#include <iostream>
using namespace std;
void main( )
{
int row,col;
int matrix[3][2]={{1,2},{3,4}};
for(row=0; row<3;row++)
{ for(col=0; col<2; col++)
cout<<matrix[row][col]<<"\t"; cout<<endl;
}
}
96
Two dimensional Arrays
Example2:
#include <iostream>
using namespace std;
void main( )
{ int row,col;
int matrix[3][2]={{1,2},{3},{5,6}};
for(row=0; row<3;row++)
{
for(col=0; col<2; col++)
cout<<matrix[row][col]<<"\t";
cout<<endl;
}
}
97
Two dimensional Arrays
Example3:
#include <iostream>
using namespace std;
void main( )
{
int row,col;
int matrix[3][2]={1};
for(row=0; row<3;row++)
{ for(col=0; col<2; col++)
cout<<matrix[row][col]<<"\t"; cout<<endl;
}
}

98
Two dimensional Arrays
Example4:

#include <iostream>
using namespace std;
void main( )
{
int row, col;
int matrix[3][2]={ {1,2}, ,{5,6} } ; //Syntax error
for(row=0; row<3;row++)
{
for(col=0; col<2; col++)
cout<<matrix[row][col]<<"\t"; cout<<endl;
}
99
}
PROCESSING TWO-DIMENSIONAL ARRAYS
A two-dimensional array can be processed in three ways:
1. Process the entire array.
2. Process a particular row of the array, called row processing.
3. Process a particular column of the array, called column
processing.

 Initializing and printing the array are examples of processing the


entire two-dimensional array.

 Finding the largest element in a row (column) or finding the sum of


a row (column) are examples of row (column) processing.

100
PROCESSING TWO-DIMENSIONAL ARRAYS
Example
const int NUMBER_OF_ROWS = 7; //This can be set to any number.
const int NUMBER_OF_COLUMNS = 6; //This can be set to any number.
int matrix[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int row; int col; int sum; int largest; int temp;

101
PROCESSING TWO-DIMENSIONAL ARRAYS

 Because the components of a two-dimensional array are of the


same type, the components of any row or column are of the same
type.

 This means that each row and each column of a two-


dimensional array is a one-dimensional array.

 Therefore, when processing a particular row or column of a two -


dimensional array, we use algorithms similar to those that
process one-dimensional arrays.
102
PROCESSING TWO-DIMENSIONAL ARRAYS
 Suppose that we want to process row number 5 of matrix (that is,
the sixth row of matrix).
 The components of row number 5 of matrix are: matrix[5][0],
matrix[5][1], matrix[5][2], matrix[5][3], matrix[5][4], matrix[5][5].

 We see that in these components, the first index (the row position)
is fixed at 5.
 The second index (the column position) ranges from 0 to 5.

 we can use the following for loop to process row number 5:


for (col = 0; col < NUMBER_OF_COLUMNS; col++)
process matrix[5][col] //row = 5; 103
PROCESSING TWO-DIMENSIONAL ARRAYS
 Similarly, suppose that we want to process column number 2 of
matrix, (that is, the third column of matrix).
 The components of this column are: matrix[0][2], matrix[1][2],
matrix[2][2], matrix[3][2], matrix[4][2], matrix[5][2], matrix[6][2].

 Here, the second index (that is, the column position) is fixed at 2.
 The first index (that is, the row position) ranges from 0 to 6.

 we can use the following for loop to process column 2 of matrix:


for (row = 0; row < NUMBER_OF_ROWS; row++)
process matrix[row][2] //col = 2; 104
PROCESSING TWO-DIMENSIONAL ARRAYS
 Initialization

 Suppose that you want to initialize row number 4, that is, the fifth
row, to 0.
 The following for loop does this:
row = 4;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 0;

105
PROCESSING TWO-DIMENSIONAL ARRAYS
 Initialization

 If you want to initialize the entire matrix to 0, you can also put the
first index, that is, the row position, in a loop.
 By using the following nested for loops, we can initialize each
component of matrix to 0:
for (row = 0; row < NUMBER_OF_ROWS; row++)
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 0;

106
PROCESSING TWO-DIMENSIONAL ARRAYS
 Print (Output)

 By using a nested for loop, you can output the components of


matrix.
 The following nested for loops print the components of matrix,
one row per line:

for (row = 0; row < NUMBER_OF_ROWS; row++)


{
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
cout << matrix[row][col] << " ";
cout << endl;
} 107
PROCESSING TWO-DIMENSIONAL ARRAYS
 Input

 The following for loop inputs the data into row number 4, that is, the
fifth row of matrix:

row = 4;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
cin >> matrix[row][col];

108
PROCESSING TWO-DIMENSIONAL ARRAYS
 Input

 As before, by putting the row number in a loop, you can input data
into each component of matrix.

 The following for loop inputs data into each component of matrix:

for (row = 0; row < NUMBER_OF_ROWS; row++)


for (col = 0; col < NUMBER_OF_COLUMNS; col++)
cin >> matrix[row][col];

109
PROCESSING TWO-DIMENSIONAL ARRAYS

 Sum by Row

 The following for loop finds the sum of row number 4 of matrix; that
is, it adds the components of row number 4.

sum = 0;
row = 4;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
sum = sum + matrix[row][col];

110
PROCESSING TWO-DIMENSIONAL ARRAYS
 Sum by Row

 Once again, by putting the row number in a loop, we can find the
sum of each row separately.

 Following is the C++ code to find the sum of each individual row:

//Sum of each individual row


for (row = 0; row < NUMBER_OF_ROWS; row++)
{
sum = 0;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
sum = sum + matrix[row][col];
cout << "Sum of row " << row + 1 << " = " << sum << endl;
111
}
PROCESSING TWO-DIMENSIONAL ARRAYS
 Sum by Column

 As in the case of sum by row, the following nested for loop finds the
sum of each individual column:

//Sum of each individual column


for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{
sum = 0;
for (row = 0; row < NUMBER_OF_ROWS; row++)
sum = sum + matrix[row][col];
cout << "Sum of column " << col + 1 << " = " << sum << endl;
}
112
PROCESSING TWO-DIMENSIONAL ARRAYS
 Largest Element in Each Row and Each Column:

 The following for loop determines the largest element in row


number 4:

row = 4;
//Assume that the first element of the row is the largest.
largest = matrix[row][0];
for (col = 1; col < NUMBER_OF_COLUMNS; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];

113
PROCESSING TWO-DIMENSIONAL ARRAYS

The following C++ code determines the largest element in each row:

//Largest element in each row


for (row = 0; row < NUMBER_OF_ROWS; row++)
{ //Assume that the first element of the row is the largest.
largest = matrix[row][0];
for (col = 1; col < NUMBER_OF_COLUMNS; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element in row " <<row+1 << "=" ;
cout << largest << endl;
} 114
PROCESSING TWO-DIMENSIONAL ARRAYS

The following C++ code determines the largest element in each column:

//Largest element in each column


for (col = 0; col < NUMBER_OF_COLUMNS; col++)
{ //Assume that the first element of the column is the largest.
largest = matrix[0][col];
for (row = 1; row < NUMBER_OF_ROWS; row++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element in column " <<col+1<< "=" ;
cout << largest << endl;
} 115
Computer Skills – 2 (C++)

Exercises
Second Semester 2023/2024

C++ Programming From Problem Analysis to Program Design


www.tutorialspoint.com
1) What is the output of the following C++ statements?
int row,col;
int matrix[3][2]={{2,6},{7,9},{5,4}};
int sumOfeven=0, sumOfodd=0;
for(row=0; row<3;row++)
for(col=0; col<2; col++)
if (matrix[row][col]%2 == 0)
sumOfeven=sumOfeven+matrix[row][col];
else
sumOfodd=sumOfodd+matrix[row][col];
cout<< "Sum of even numbers = "<<sumOfeven<<endl;
cout<< "Sum of odd numbers = "<<sumOfodd<<endl;
117
2) What is the output of the following C++ statements?

int row,col;
int matrix[3][3];
for(row=0; row<3;row++)
for(col=0; col<3; col++)
if (row == col)
matrix[row][col] = 1;
else
matrix[row][col] = 0;
for(row=0; row<3;row++)
{
for(col=0; col<3; col++)
cout<<matrix[row][col]<<" ";
cout<<endl;
} 118
3) Identify error(s), if any, in the following array declarations.
a. int list[10];
b. constint size = 100;
double list[SIZE];
c. int numList[0..9];
d. scores[50] double;
e. int test[-10];
f. double sales[40.5];

119
4) What is the output of the following code?

int list[ ] ={6, 8, 2, 14, 13};


for (int i = 0; i < 4; i++) list[i] = list[i] - list[i + 1];
for (int i = 0; i < 5; i++) cout << i << " " << list[i] << endl;

120
5) Consider the following declaration:
double salary[10];
In this declaration, identify the following:

a. The array name.


b. The array size.
c. The data type of each array component.
d. The range of values for the index of the array.

121

You might also like