Chapter5 6
Chapter5 6
5. CONTROL STRUCTURES
(REPETITION)
Second Semester 2023/2024
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
1. while loop
2. for loop
3. do while loop
6
1. while Looping (Repetition) Structure
8
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.
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
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 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 following for loop outputs Hello! and a star (on separate lines)
five times:
for (i = 1; i <= 5; i++)
{ cout << "Hello!" << endl; cout << "*" << endl; }
18
2. for Looping (Repetition) Structure
The following for loop executes five empty statements:
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.
21
2. for Looping (Repetition) Structure
You can count backward using a for loop if the for loop control
expressions are set correctly.
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.
23
2. for Looping (Repetition) Structure
24
2. for Looping (Repetition) Structure
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
27
2. for Looping (Repetition) Structure
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
31
Pretest loop
Because the while and for loops both have entry conditions,
these loops may never activate.
32
Postest loop
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
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
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.
39
continue statement
40
continue statement
41
Nested Control Structures - nested loops
while(expression)
{
while(expression)
{
statement(s);
}
statement(s);
}
43
Nested Control Structures - nested loops
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
- 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.
46
Example #2
47
Example #3
48
Example #4
49
Example #5
50
Example #6
51
Example #7
52
Example #8
53
Example #9
54
Computer Skills – 2 (C++)
CONTROL STRUCTURES
(REPETITION)
Second Semester 2023/2024
Exercises
d. for (i = 12; i >= 9; i--) cout << "*"; cout << endl;
- 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
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
Thus, for large amounts of data, this type of program is not desirable.
Note the following in the previous program:
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
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.
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.
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;
69
C++ Arrays - One-dimensional array.
71
C++ Arrays - One-dimensional array.
Processing One-Dimensional Arrays
The following for loop steps through each element of the array list,
starting at the first element of list:
72
C++ Arrays - One-dimensional array.
Example
//Declaration
double sales[10];
int index;
double largestSale, sum, average;
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).
74
C++ Arrays - One-dimensional 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;
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};
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
81
Partial Initialization of Arrays 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:
83
Partial Initialization of Arrays During Declaration
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.
85
Some Restrictions on Array Processing
Example:
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.
87
Some Restrictions on Array Processing
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).
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.
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.
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.
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
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.
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.
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)
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:
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:
As in the case of sum by row, the following nested for loop finds the
sum of each individual column:
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:
The following C++ code determines the largest element in each column:
Exercises
Second Semester 2023/2024
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?
120
5) Consider the following declaration:
double salary[10];
In this declaration, identify the following:
121