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

CS2311 Lec04 Loop

while checks the condition before executing the loop body, whereas do-while checks the condition after executing the loop body at least once. So do-while is better when you need the loop body to execute at least once.

Uploaded by

Hello HK World
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)
44 views

CS2311 Lec04 Loop

while checks the condition before executing the loop body, whereas do-while checks the condition after executing the loop body at least once. So do-while is better when you need the loop body to execute at least once.

Uploaded by

Hello HK World
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/ 83

CS2311 Computer Programming

LT04: Control Flow - Loop

Computer Science, City University of Hong Kong


Semester A 2022-23
Recap: Lab 3 Q1
• write a program that calculates the result of 'a', 'operator', 'b'

2
Recap: Lab 3 Q1
• write a program that calculates the result of 'a', 'operator', 'b'
a o b
if Cem

xx x x

else
L 11 O Il o I Il o L L Il
if o t 11 0
O 7 11 0

a in valid input c end l


cont
else
coat cc invalid operation 3
Recap: Lab 3 Q2
• write a program that
reads 3 integer
values (> 0) from the
user. The 3 values
are interpreted as
representing the
lengths of the three It 2 2 10 cannot form
sides of a triangle. a triangle
• Check the property
of the triangle

4
Recap: Lab 3 Q2
• write a program that
reads 3 integer
values (> 0) from the else if a b 11 Iso
user. The 3 values be all a c A
Iso Eq
are interpreted as
representing the
lengths of the three
sides of a triangle. else 11 scalene
• Check the property
of the triangle

5
Today's Outline
• Loop
• while
• do-while
• for

• Programming styles for control flow


• Exercises

6
Loop Start
Mit
radar
• When the execution enters a loop, it
executes a block of code repeatedly as check the False
condition Condition
long as a loop condition is met

True
• Beside sequential and branch execution Code
loop is another common control flow
radar check radar det
obj
Navigate the car
End

7
Loop (cont'd)
x=0 Initial of
• Print "hello world" 10 times the loop

1. Set x=0;
cout << "hello world\n"
2. cout << "hello world\n"
3. if (x < 10) then add 1 to x and loop x = x+1
back
check the condition
4. Else exit the loop Yes
x < 10?

No
end loop
8
Loop (cont'd)
x=0
• In general, a loop consists of four parts
initialization statements . before the loop
cout << "hello world\n"
body ..executed repeatedly while
the loop condition is true
loop condition . x = x+1

post loop statements (stepping forward to


Yes
exit loop condition) x < 10?

No

9
Types of Loop
• while loop
• do-while loop
• for loop

10
while check expression

• Syntax loop condition


while (expression) body
{
loop statement(s); 11
}
loop body

• Semantics
• If the value of expression is non-zero (true), loop statements will be
executed, otherwise, the loop terminates
• After loop statements are executed, the expression will be tested again

11
int main() {
int x, max;
while max = 0;
cout << "Enter a positive integer. ";
To collect
• An Example:
cout << "Type 0 to quit.\n"; 11 the input
cin >> x;
while (x != 0) { from the
• Ask user to input positive if (x > max) user
integers max = x;
cout << "Enter a positive integer. ";
• Stop when user enters '0' cout << "Type 0 to quit.\n";
cin >> x;
• Print the maximum of }
entered positive integers if (max == 0) {
before quit cout << "You didn't enter any positive integer\n";
} else {
cout << "The maximum integer you entered is ";
cout << max << endl;
}
return 0;
} 17
do-while
• Syntax
do { Difference of while and do
loop statement(s);
while
}
while (expression); Do while Execute the loop body
first Then check the loop expression
• Semantics If the expression is false Then
execute the loop body again
• loop statements are executed first; thus the loop body will be executed
for at least once
• If the value of expression is non-zero (true), the loop repeats; otherwise,
the loop terminates while check the loop expression first
then execute the loop body
18
int main() {
int x, max;
do-while max = 0;

do {
• An Example: cout << "Enter a positive integer. ";
cout << "Type 0 to quit.\n";
• Ask user to input positive cin >> x;
integers if (x > max)
max = x;
• Stop when user enters '0' } while (x != 0);
• Print the maximum of if (max == 0) {
entered positive integers cout << "You didn't enter any positive integer\n";
before quit } else {
cout << "The maximum integer you entered is ";
cout << max << endl;
}

return 0;
} 19
while vs do-while
int x, max;
max = 0;
cout << "Enter a positive integer. ";
cout << "Type 0 to quit.\n";
cin >> x;
while (x != 0) {
if (x > max)
max = x;
cout << "Enter a positive integer. ";
cout << "Type 0 to quit.\n";
cin >> x;
}

• do-while is better suited for loops that require at least one iteration
20
while vs do-while
int x, max; int x, max;
max = 0; max = 0;
cout << "Enter a positive integer. ";
cout << "Type 0 to quit.\n";
Nothing here
cin >> x;
while (x != 0) { do {
if (x > max) cout << "Enter a positive integer. ";
max = x; cout << "Type 0 to quit.\n";
cout << "Enter a positive integer. "; cin >> x;
cout << "Type 0 to quit.\n"; if (x > max)
cin >> x; max = x;
} } while (x != 0);

• do-while is better suited for loops that require at least one iteration
21
while vs do-while
int x, max; int x, max;
max = 0; max = 0;
cout << "Enter a positive integer. ";
cout << "Type 0 to quit.\n";
cin >> x;
while (x != 0) { do {
if (x > max) cout << "Enter a positive integer. ";
max = x; cout << "Type 0 to quit.\n";
cout << "Enter a positive integer. "; cin >> x;
cout << "Type 0 to quit.\n"; if (x > max)
cin >> x; max = x;
} } while (x != 0);

• do-while is better suited for loops that require at least one iteration
22
while vs do-while
initialization initialization

While (...){ check the do{


loop condition
true true

} false }while(…)

false

23
structureof a loop
for: Syntax initial statement
loop condition
initial condition post loop post loop statement
for (expr1; expr2; expr3) {
loop statements; step
} loop body I exp r
2 check expr 2
• Semantics 3 loop statement
4 expr3
Loop statements are repeatedly executed as long as expr2 is non-zero (true).
Otherwise, the loop ends. stop if expr 2 is false
expr1: executed before entering the loop body. Often used for initializing a loop
counter or loop status.
expr3: executed after each iteration of the loop body. Often used to update the
loop counter or loop status.
24
for: Examples
#include <iostream>
using namespace std;
int main() {
int i; from i O
start
for (i=0;i<10;i++) {
if(i%2==0) 11 to check whether i is even
cout << i << endl;
}
return 0;
}
for: Examples
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() { int main() {
int i; I declan outside the loop
for (i=0;i<10;i++) {
body for(int i=0;i<10;i++) {
if(i%2==0) if(i%2==0)
cout << i << endl; cout << i << endl;
} }
return 0; return 0;
} }
#include <iostream>
using namespace std;
// get input from user until a positive integer is entered
int main() {
int x;
cout << "Enter a number: ";
cin >> x;
while (x <= 0) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
cin >> x;
}
return 0;
}
#include <iostream> initialization
using namespace std;
// get input from user until a positive integer is entered loop condition .
int main() {
int x;
body
cout << "Enter a number: "; post loop statements
cin >> x;
while (x <= 0) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
cin >> x;
}
// for-loop equivalent to the above while-loop
for (cin >> x; x <= 0; cin >> x) {

}
return 0;
}
#include <iostream> initialization
using namespace std;
// get input from user until a positive integer is entered loop condition .
int main() {
int x;
body
cout << "Enter a number: "; post loop statements
cin >> x;
while (x <= 0) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
cin >> x;
}
// for-loop equivalent to the above while-loop
for (cin >> x; x <= 0; cin >> x) {
exprl
exprt exprz exprz check expr2
} body
return 0; expr3
}
#include <iostream> initialization
using namespace std;
// get input from user until a positive integer is entered loop condition .
int main() {
int x;
body
cout << "Enter a number: "; post loop statements
cin >> x;
while (x <= 0) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
cin >> x;
}
// for-loop equivalent to the above while-loop
for (cin >> x; x <= 0; cin >> x) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
}
return 0;
}
#include <iostream> initialization
using namespace std;
// get input from user until a positive integer is entered loop condition .
int main() {
int x;
body
cout << "Enter a number: "; post loop statements
cin >> x;
while (x <= 0) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
cin >> x;
}
// for-loop equivalent to the above while-loop
for (cin >> x; x <= 0; cin >> x) {
cout << "Input must be positive." << endl;
cout << "Enter number: ";
}
return 0;
}
for: Examples
• Aside from using int as loop counters, we can also use other integral
types

initial statement post loop statement


for (char ch='a'; ch<='z'; ch++)
{ condition
cout << ch << endl;
}
we can use different
type for the loop
counter

32
for: Syntax (cont'd)
for (expr1; expr2; expr3) {
loop statements;
}

• expr1 and expr3 can contain multiple statements. Each statement is


separated by a comma ','
• Example
for (int i=0, j=0; i<10; i++, j++)

33
for: Examples (cont'd) 27 Str 237 Str 24
Str OT Str El Str
• Palindrome string: a string is char str[5]; declare an array of
bool is_palindrome; char type
palindrome if the reverse of that
cout << "Input 5 letters: ";
string is the same as the original
for (int i=0; i<5; i++) {
(e.g., abcba)
cin >> str[i];
• Check if a string consisting of 5 }
characters is palindrome or not is_palindrome = true;
for (int i=0, j=4; i<5; i++, j--) {
Palindrome string is_palindrome &= str[i]==str[j];
Not palindrome
}A ab ca b
string A reverse of
string cout << "It's";
e
g string A abeba cout << (is_palindrome ? " ":" NOT ");
reverse of string A cout << "palindrome\n";
abeba
for: Examples (cont'd)
• Palindrome string: a string is char str[5];
bool is_palindrome;
palindrome if the reverse of that
cout << "Input 5 letters: ";
string is the same as the original
for (int i=0; i<5; i++) {
(e.g., abcba)
cin >> str[i];
• Check if a string consisting of 5 }
characters is palindrome or not is_palindrome = true;
i j
W for (int i=0, j=4; i<5; i++, j--) {
is_palindrome &= str[i]==str[j];
a b e b a } true if
Str E O I EZ 23 4 Str 24
cout <<IoT"It's";
Str Str II Str E3
cout << 22 Str E 2 ? " ":" NOT ");
Str (is_palindrome
cout << "palindrome\n";
for: Examples (cont'd)
• Palindrome string: a string is char str[5];
bool is_palindrome;
palindrome if the reverse of that
cout << "Input 5 letters: ";
string is the same as the original
for (int i=0; i<5; i++) {
(e.g., abcba)
cin >> str[i];
• Check if a string consisting of 5 }
characters is palindrome or not is_palindrome = true;

83234
for (int i=0, j=4; i<5; i++, j--) {
i is_palindrome &= str[i]==str[j];

1111
}
cout << "It's";
j 4 3 21 0 cout << (is_palindrome ? " ":" NOT ");
cout << "palindrome\n";
a b e b a
for: Nested Loop
int i, j;
outer Loop
for (i=0; i<3; i++) {
cout << "Outer for: \n"; Thner loop
for (j=0; j<2; j++) {
cout << "Inner for: ";
cout << "i=" << i << ", j=" << j << endl;
} // end of inner loop
cout << endl;
} // end of outer loop

• Thethis
outer loop is executed
two 3level
times. In each iteration
nested of the outer loop,
loop
is
the inner loop is executed 2 times
for: Nested Loop
int i, j; Outer for:
for (i=0; i<3; i++) { Inner for:i=0, j=0
cout << "Outer for: \n"; Inner for:i=0, j=1
for (j=0; j<2; j++) {
Outer for:
cout << "Inner for: "; Inner for:i=1, j=0
cout << "i=" << i << ", j=" << j << endl; Inner for:i=1, j=1
} // end of inner loop
cout << endl; Outer for:
Inner for:i=2, j=0
} // end of outer loop
Inner for:i=2, j=1

• The outer loop is executed 3 times. In each iteration of the outer loop,
the inner loop is executed 2 times
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• E.g., when n = 5, the following matrix is generated

1 Koo Xo Xoz Xon


X 10 X 11 X iz Xin
2
3
no Xn Xnz Xun
4
5

39
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9
Col k
• Solution co tsk I

int n; K column
1
cin >> n; K 1column

for (int row=1; row<=n; row++) { 2


for (int col=1; col<=row-1; col++) 3
cout << " "; 4 coutcrowscendl
cout << row << endl; here
5
}

conte here 40
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• Solution
int n;
1 // row-1=0
cin >> n;
for (int row=1; row<=n; row++) { 2
for (int col=1; col<=row-1; col++) 3
cout << " "; not executed 4
cout << row << endl;
5
}

41
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• Solution
int n;
1
cin >> n;
for (int row=1; row<=n; row++) { 2 // row-1=1
Col 2 2 I col++)
for (int col=1; col<=row-1; 3
cout << " "; executed 1 time 4
cout << row << endl;
5
}

42
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• Solution
int n;
1
cin >> n;
for (int row=1; row<=n; row++) { 2
Col 3 Icol++)
for (int col=1; col<=row-1; 3 // row-1=2
cout << " "; executed 2 times 4
cout << row << endl;
5
}
print the row number
43
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• Solution
int n;
1
cin >> n;
for (int row=1; row<=n; row++) { 2
for (int col=1; col<=row-1; col++) 3
cout << " "; 4 // row-1=3
cout << row << endl;
5
}

44
for: Nested Loop (Example)
• Write a program to generate a n x n diagonal matrix (n is input by the
user), where the element at the i-th row is i. Assume n > 1 and n <= 9

• Solution
int n;
1
cin >> n;
for (int row=1; row<=n; row++) { 2
for (int col=1; col<=row-1; col++) 3
cout << " "; 4
cout << row << endl;
5 // row-1=4
}

45
for: Common Errors
• Scope of loop counter declaration

for (int k=1; k<=8; k++)


cout << "log(" << k << ") = " << log(1.0*k) << endl;
cout << k << endl; // SYNTAX ERROR
not defined
// Variable k can be declared before the for-loop
int k=0;
for (k=1; k<=8; k++)
cout << "sqrt(" << k << ") = " << sqrt(k) << endl;
cout << k << endl;

46
for: Common Errors The variable k is declared within the
for-loop. It is not visible/accessible
outside the for-loop.
• Scope of loop counter declaration

for (int k=1; k<=8; k++)


cout << "log(" << k << ") = " << log(1.0*k) << endl;
cout << k << endl; // SYNTAX ERROR

// Variable k can be declared before the for-loop


int k=0;
for (k=1; k<=8; k++)
cout << "sqrt(" << k << ") = " << sqrt(k) << endl;
cout << k << endl;

47
for: Common Errors (cont'd)
• Unaware of extra semi-colons, e.g.
int sum = 0;
for (j=1; j<=10; j++)
sum += j;
1 2 34 8 9 10
Is NOT the same as
int sum = 0;
for (j=1; j<=10; j++) ;
sum += j;
sum O
sum sum tj
48
for: Common Errors (cont'd)
• Unreachable loop termination condition => unintended infinite loop
• Example I
infinite loop
for (char i=0; i<256; ++i)
{
cout << "i= " << i << endl;
}

It infinite loop
is because size of character is always
smaller than 256

49
for: Common Errors (cont'd)
• Unreachable loop termination condition => unintended infinite loop
• Example II
infinite loop
for (unsigned int i=100; i>=0; --i)
{
cout << "i= " << i << endl;
}

since i is unsigned integer


i will never smaller than zero
Tht O 0 0000 000000000000 0
Unsigned 4294967295 interpret 50as the
unsigned int c l Ox FFFFFFFFFFFFFFFF value
for: Common Errors (cont'd)
• Unreachable loop termination condition => unintended infinite loop
• Example III
int iter=0;
I
for (float i=0.0; i!=0.000001; i+=0.0000001)
cout << "This is the " << ++iter << " iteration\n";

float type It can


only evaluate 6

07 digits after decimal point


O 1.00000012 e
2.00000012 e 7 e 6
1.0000011

51
for: Common Errors (cont'd)
• Unreachable loop termination condition => unintended infinite loop
• Example III
int iter=0; 5 6
for (float i=0.0; i!=0.000001; i+=0.0000001)
cout << "This is the " << ++iter << " iteration\n";

int iter=0;
for (float i=0.0; i<0.000001; i+=0.0000001)
cout << "This is the " << ++iter << " iteration\n";

52
for: Common Errors (cont'd)
• Unreachable loop termination condition => unintended infinite loop
• Example III float type precision 6 digits after decimal • To control a loop, use a
relational expression if
int iter=0;
possible, rather than
for (float i=0.0; i!=0.000001; i+=0.0000001) an equality expression
cout << "This is the " << ++iter << " iteration\n";
• Don’t use a variable of
any floating point data
int iter=0; better to use relation
type to control a loop
for (float i=0.0; i<0.000001; i+=0.0000001) because real numbers
cout << "This is the " << ++iter << " iteration\n"; are represented in
their approximate

infinite because exceeded the


values internally

precision of float 53
break Statement
• The break statement causes an exit from the innermost enclosing loop or
switch statement

while (1) { while 1


cin >> n; while 1
if (n < 0)
break;
cout << n << endl;
}
// if break is run, jumps to here

54
continue Statement
continue statement causes the current iteration of a loop to stop and the
next iteration to begin immediately
It can be applied in a while, do-while or for statement
cnt=0; check if cut 10
while (cnt<10) {
cin >> x; want user to input 10
if (x > -0.01 && x < 0.01) numbers
continue; // discard small values
++cnt;
whose
sum += x;
values are
}
absolute greater
than 0.01
55
continue, break
while false

true
continue jump
start another
loop cycle Out
break

jump out

56
goto Statement Use to go to the specified line

• goto statement transfers control to int main() {


int num;
another statement specified by a label cin >> num;
if (num%2 == 0)
• goto statement is considered a harmful
goto even;
construct and a bad programming else
practice goto odd;
• It makes the logic of the program even:
complex and tangled cout << num << " is even\n";
return 0;
• It can be replaced with the use of break odd:
and continue cout << num << " is odd\n";
return 0;
Try not to always }
use go to statement 57
Short-Circuit Evaluation with goto
if (a || b || c)
a check
statement1;
statement2;
a is
T true
is equivalent to … on
if (a) goto True;
Il Il c
ifa (b) gotob True;
false
if (c) goto True;
goto Done; // a||b||c == false
True:
statement1; statement 1 statement 2
Done:
statement2;
Short-Circuit Evaluation with goto
if (a || b || c) true
as is a a is
statement1;
F false
statement2;
T
b
is equivalent to … check
if (a) goto True; b'is
if (b) goto True; true or
if (c) goto True; false
goto Done; // a||b||c == false
True:
statement1; statement 1 statement 2
Done:
statement2;
Short-Circuit Evaluation with goto
if (a || b || c)
a
statement1;
F
statement2; true
T is
b b b is false
is equivalent to … T
F
if (a) goto True;
if (b) goto True; c check c'is
if (c) goto True; true or
goto Done; // a||b||c == false false
True:
statement1; statement 1 statement 2
Done:
statement2;
Short-Circuit Evaluation with goto
if (a || b || c)
a
statement1;
F
statement2;
T
b
is equivalent to … T
F
if (a) goto True;
if (b) goto True; c
if (c) goto True;
T F c is false
goto Done; // a||b||c == false
c'is true
True:
statement1; statement 1 statement 2
Done:
statement2;
Short-Circuit Evaluation with goto
if (a || b || c)
a
statement1;
F
statement2;
T
b
is equivalent to … T
F
if (a) goto S1;
if (b) goto S1; c
if (c) goto S1;
goto S2; // a||b||c == false T F
S1:
statement1; statement 1 statement 2
S2:
statement2;
Short-Circuit Evaluation with goto
if (a && b && c)
statement1;
statement2;
is equivalent to ?
Today's Outline
• Loop
• while
• do-while
• for

• Programming styles for control flow


• Exercises

67
of control
Indentation To indicate the flow

int main() { • Indent code in a consistent fashion to


int i; indicate the flow of control (use the
for (i=0; i<100; i++) { tab key)
if (i>3)
• Note the multiple levels of indentation
cout << i;
}
return 0;
}
1st level (1 tab)
2nd level (2 tabs)
3rd level (3 tabs)
68
Formatting Programs
• Indent the code properly as you write the program to reflect the structure of the
program.
• Improve readability and increase the ease for debugging the program
• In assignment, marks will be allocated for indentation.

• To indent in visual studio, you may press the tab button

• You may select multiple lines of statements and press tab to indent all of them

• To move back one level to the left, press shift+tab

69
if Condition Style Example of bad spell
if(condition) { // Bad-space missing after if

if ( condition ) { // Bad-space between the parentheses


and the condition

if (condition){ // Bad–space missing before {

if(condition){ // Doubly bad

if (int a = f();a == 10) { // Bad – space missing after the


semicolon

if (conditionA && conditionB) { // GOOD

70
Today's Outline
• Loop
• while
• do-while
• for

• Programming styles for control flow


• Exercises

71
Exercises: Data Types 1
• What will be printed and why?
#include <iostream>
using namespace std;
int main() {
char vChar1 = 'A';
char vChar2 = '0';
cout << vChar1 << " " << vChar2 << endl;
cout << ++vChar1 << endl;
return 0;
}
Output
72
Exercises: Data Types 2
• For integral operands, division operator int m = 3, n = 2;
yields algebraic quotient with any fractional double k;
part discarded (i.e., round towards zero) k = m / n; 11 1 tht
• If quotient a/b is representable in type of k = m / double(n); 111.5 dou
result, (a/b)*b+a%b is equal to a k = double(m) / n;111.5 dou
• So, assuming b is not zero and no overflow, k = double(m/n); 111 the
a%b equals a-(a/b)*b k = m / 2; 11 1 int
• What's the value of k at each step? k = m / 2.0; 11 1.5 doub
Tht float

73
Exercises: I/O
• write a program ConvertTemperature.cpp Expected Output:
a) read a temperature in Celsius (data type: Enter Temperature in
int) and display it in Fahrenheit (data type: Centigrade:
double). Round the result to 2 decimal places. 30
• Hint: Fahrenheit = 9/5*Celsius + 32 Temperature in Fahrenheit
is:
b) convert calculated Fahrenheit (data type: 86.00
double) into Kelvin (data type: double). Round Temperature in Kelvin is:
the result to 2 decimal places. 303.15
• Hint: Kelvin = (Fahrenheit+459.67) * 5/9

74
Exercises: I/O
int Celsius;
double Fahrenheit, Kelvin;
cout << "Enter Temperature in Centigrade:\n";
cin >> Celsius;
cout <<"Temperature in Fahrenheit is:\n";
Fahrenheit = 9.0 / 5 * Celsius + 32;
cout << fixed << setprecision(2);
cout << Fahrenheit << "\n";
cout << "Temperature in Kelvin is:\n";
Kelvin = (Fahrenheit + 459.67) * 5 / 9.0;
cout << Kelvin << "\n";

75
Exercises: Loop 1
• write a program to generate a matrix of n rows and m column (n and m is
input by the user), where the element at the i-th row and j-th colum is the
multiplication of i and j. Assume n > 1 and m <= 9

• E.g., when n = 4, m = 3, the following matrix is generated

1 2 3
2 4 6
3 6 9
4 8 12

78
Exercises: Loop 1
int main() {
int n, m; // n: rows, m: columns
cin >> n >> m;
for (int i=1; i<=n; i++) {
for (int j=1; j<=m; j++) {
// for the element at the i-th row and j-th column
cout << i*j << "\t";
}
cout << endl;
}
return 0;
}
79
Exercises: Loop 2
• write a program to produce a nxn Example 1 Example 2
Enter the number of rows: 5 Enter the number of rows: 8
matrix (n is input by user) with 0's 0 1 2 3 4 0 1 2 3 4 5 6 7
down the main diagonal, 1's in the 1 0 1 2 3 1 0 1 2 3 4 5 6
2 1 0 1 2 2 1 0 1 2 3 4 5
entries just above and below the 3 2 1 0 1 3 2 1 0 1 2 3 4
main diagonal, 2's above and below 4 3 2 1 0 4 3 2 1 0 1 2 3
5 4 3 2 1 0 1 2
that, etc. 6 5 4 3 2 1 0 1
7 6 5 4 3 2 1 0
• hint: consider using nested for-loop, Example 3 Example 4
with the outer loop responsible for Enter the number of rows: 0 Enter the number of rows: 3
row and the inner loop for each Please enter positive 0 1 2
integer. 1 0 1
column 2 1 0

80
Exercises: Loop 2
int n;
cout << "Enter the number of rows: ";
cin >> n;
if (n <= 0) {
cout << "Please enter positive integer.\n";
} else {
for (int row=0; row<n; row++) {
for (int col=0; col<n; col++)
cout << abs(col-row) << " ";
cout << endl;
}
}

81
Exercises: Loop 3
• Monte Carlo estimation of Pi R
• circle_area = Pi*R*R/4
• square_area = R*R
• Pi = 4*circle_area/square_area R
• How to estimate circle_area/square_area?
Exercises: Loop 3
• Monte Carlo estimation of Pi R
• circle_area = Pi*R*R/4
• square_area = R*R
• Pi = 4*circle_area/square_area R
• How to estimate circle_area/square_area?
• Randomly throw N points to the square
• Let M be the number of points falling to the yellow area
M
• circle_area/square_area ≈
N
Exercises: Loop 3
// Assume R=1 R
int M=0;
for (int n=0; n<N; n++) {
// Randomly throw a point
double x = (double)rand()/RAND_MAX; R
double y = (double)rand()/RAND_MAX;
if (x*x+y*y < 1.0)
M++; // Increment M if (x, y) is within the yellow area
if (n!=0 && n%1000==0)
cout << n << " " << 4.0*M/n << endl;
}

84
Exercises: Loop 3
// Assume R=1 R
int M=0, N=10000;
for (int n=0; n<N; n++) {
// Randomly throw a point
double x = (double)rand()/RAND_MAX; R
double y = (double)rand()/RAND_MAX;
if (x*x+y*y < 1.0)
M++; // Increment M if (x, y) is within the yellow area
double est = 4.0*M/n;
cout << n << " " << est << endl;
}

85
Exercises: Loop 3
• Each round we throw 10000 pts
• Then observe if the estimated value
of Pi has changed significantly
• If true, the estimation is not stable
=> continue throwing pts
• If false, the estimation is now
stable, stop
double precision = 1e-7;

Exercises: Loop 3 double prev_est = 0, curr_est;


int M=0, N=0;
while (true) {
• Each round we throw 10000 pts
• Then observe if the estimated value for (int n=0; n<10000; n++) {
of Pi has changed significantly double x = (double)rand()/RAND_MAX;
double y = (double)rand()/RAND_MAX;
• If true, the estimation is not stable if (x*x+y*y < 1.0)
=> continue throwing pts M++;
N++;
• If false, the estimation is now } // end of for
stable, stop curr_est = 4.0*M/N;
cout << curr_est << endl;
if (abs(curr_est-prev_est) < precision)
break;
prev_est = curr_est;
} // end of while
double precision = 1e-7;

Exercises: Loop 3 double prev_est=0, curr_est=0;


int M=0, N=0;
while (true) {
• Each round we throw 10000 pts
prev_est = curr_est;
• Then observe if the estimated value for (int n=0; n<10000; n++) {
of Pi has changed significantly double x = (double)rand()/RAND_MAX;
double y = (double)rand()/RAND_MAX;
• If true, the estimation is not stable if (x*x+y*y < 1.0)
=> continue throwing pts M++;
N++;
• If false, the estimation is now } // end of for
stable, stop curr_est = 4.0*M/N;
} // end of while
cout << curr_est << endl;
if (abs(curr_est-prev_est) < precision)
break;
double precision = 1e-7;

Exercises: Loop 3 double prev_est=0, curr_est=0;


int M=0, N=0;
while (true) {
• Each round we throw 10000 pts
prev_est = curr_est;
• Then observe if the estimated value for (int n=0; n<10000; n++) {
of Pi has changed significantly double x = (double)rand()/RAND_MAX;
double y = (double)rand()/RAND_MAX;
• If true, the estimation is not stable if (x*x+y*y < 1.0)
=> continue throwing pts M++;
N++;
• If false, the estimation is now } // end of for
stable, stop curr_est = 4.0*M/N;
cout << curr_est << endl;
} // end of while
cout << curr_est << endl;
if (abs(curr_est-prev_est) < precision)
break;
double precision = 1e-10;

Exercises: Loop 3 double prev_est=0, curr_est=0;


int M=0, N=0;
while (true) {
• Each round we throw 10000 pts
prev_est = curr_est;
• Then observe if the estimated value for (int n=0; n<10000; n++) {
of Pi has changed significantly double x = (double)rand()/RAND_MAX;
double y = (double)rand()/RAND_MAX;
• If true, the estimation is not stable if (x*x+y*y < 1.0)
=> continue throwing pts M++;
N++;
• If false, the estimation is now } // end of for
stable, stop curr_est = 4.0*M/N;
cout << curr_est << endl;
if (abs(curr_est-prev_est) < precision)
break;
} // end of while
double precision = 1e-10;

Exercises: Loop 3 double prev_est=0, curr_est=0;


int M=0, N=0;
while (true) do {
• Each round we throw 10000 pts
prev_est = curr_est;
• Then observe if the estimated value for (int n=0; n<10000; n++) {
of Pi has changed significantly double x = (double)rand()/RAND_MAX;
double y = (double)rand()/RAND_MAX;
• If true, the estimation is not stable if (x*x+y*y < 1.0)
=> continue throwing pts M++;
N++;
• If false, the estimation is now } // end of for
stable, stop curr_est = 4.0*M/N;
cout << curr_est << endl;
if (abs(curr_est-prev_est) < precision)
break;
} while (abs(curr_est-prev_est)<precision);
Exercises: Conditional + Loop
• Guess an integer number in user's mind. Assume the number is positive and
not greater than 100 (i.e., 0 < num <= 100)
• In each round, the program asks the user a question and the user answers with
'T' (true) or 'F' (false), until the program guesses the correct number
• Try to guess the number with as few rounds as possible
• Example:
Is it 99? N
Is it 98? N

Is it 16? Y
92

You might also like