0% found this document useful (0 votes)
15 views27 pages

Us C++ 2021 02

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)
15 views27 pages

Us C++ 2021 02

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/ 27

C++: Control Structures

Presenter: Dr. Ha Viet Uyen Synh.


Review of the last lecture

- The skeleton of a C/C++ program


#include <iostream>

// function main begins program execution


int main()
{

return 0; // indicate that program ended successfully

} // end function main

- Primary data types

- Arithmetic operators
Exercise
Write a program that determines the values of
expressions a, b given x,y,z
How to sold a problem in
computer science?

Level 4
Non-convex Optimization

Level 3
Convex Optimization
MCMs & PDEs

Level 2
Graphs

Level 1
“Exhausted check”
method & “Look-up
Table” method
Agenda
Rules for forming structured
programs
Rules for Forming Structured Programs
- Begin with the "simplest activity diagram“.
- Any action state can be replaced by two action states in
sequence _ Stacking rule .
- Any action state can be replaced by any control statement
(sequence, if, if...else, switch, while, do...while or for) _
Nesting rule.

Rules 2 and 3 can be applied as often as you like and in any


order.
Applying Stacking Rule
Applying Nesting Rule
if Selection Statement
The if selection statement allows us to state that an action
(sequence of statements) should happen only when some
condition is true:
if (condition)
action;
The condition used in an if (and other control structures) is a
Boolean value - either true or false.
In C++:
the value 0 is false
anything else is true

if ( grade >= 60 )
cout << "Passed";
if...else Double-Selection
Statement
The if single-selection statement performs an indicated action only
when the condition is TRUE; otherwise the action is skipped.

The if...else double-selection statement allows the programmer to


specify an action to perform when the condition is true and a
different action to perform when the condition is false.

if ( condition )
action if true
else
action if false
Nested if...else Statements
Nested if...else statements test for multiple cases by
placing if...else selection statements inside other if...else
selection statements.

if ( studentGrade >= 90 ) // 90 and above gets "A"


cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";

if ( studentGrade >= 90 ) // 90 and above gets "A"


cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
while Repetition Statement
The while repetition statement supports repetition - the same
statement (or compound statement) is repeated until the condition
is false.

while (condition)
do something;

// Calculate 3n with 3n<=100


int product = 3;
while ( product <= 100)
product = 3 * product;
Counter-controlled repetition
1 // Fig. 5.1: fig05_01.cpp
2 // Counter-controlled repetition.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int counter = 1; // declare and initialize control variable
10
11 while ( counter <= 10 ) // loop-continuation condition
12 {
13 cout << counter << " ";
14 counter++; // increment control variable by 1
15 } // end while
16
17 cout << endl; // output a newline
18 return 0; // successful termination
19 } // end main

1 2 3 4 5 6 7 8 9 10
for Repetition Statement
The for repetition statement is often used for loops that involve
counting.

You can write any for loop as a while (and any while as a
for).

for (initialization; condition; update)


dosomething;

- initialization is a statement that is executed at the beginning of the


loop (and never again).

- the body of the loop is executed as long as the condition is true.

- the update statement is executed each time the body of the loop
has been executed (and before the condition is checked)
Counter-controlled repetition with the for
statement.
1 // Fig. 5.2: fig05_02.cpp
2 // Counter-controlled repetition with the for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8{
9 // for statement header includes initialization,
10 // loop-continuation condition and increment.
11 for ( int counter = 1; counter <= 10; counter++ )
12 cout << counter << " ";
13
14 cout << endl; // output a newline
15 return 0; // indicate successful termination
16 } // end main

1 2 3 4 5 6 7 8 9 10
do...while Repetition Statement
The do...while repetition statement is similar to the while statement.
In the while statement, the loop-continuation condition test occurs
at the beginning of the loop before the body of the loop executes.
The do...while statement tests the loop-continuation condition after
the loop body executes; therefore, the loop body always executes
at least once.
When a do...while terminates, execution continues with the
statement after the while clause. Note that it is not necessary to
use braces in the do...while statement if there is only one
statement in the body; however, most programmers include the
braces to avoid confusion between the while and do...while
statements
do
somestuff;
while ( condition );
switch Multiple-Selection
Statement
switch multiple-selection statement to perform many different
actions based on the possible values of a variable or expression.
Each action is associated with the value of a constant integral
expression
break Statement
The break statement, when executed in a while, for, do...while or
switch statement, causes immediate exit from that statement.
Program execution continues with the next statement.
Common uses of the break statement are to escape early from a
loop or to skip the remainder of a switch statement
1 // Fig. 5.13: fig05_13.cpp
2 // break statement exiting a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8{
9 int count; // control variable also used after loop terminates
10
11 for ( count = 1; count <= 10; count++ ) // loop 10 times
12 {
13 if ( count == 5 )
14 break; // break loop only if x is 5
15
16 cout << count << " ";
17 } // end for
18
19 cout << "\nBroke out of loop at count = " << count << endl;
20 return 0; // indicate successful termination
21 } // end main
continue Statement
The continue statement, when executed in a while, for or do...while
statement, skips the remaining statements in the body of that statement and
proceeds with the next iteration of the loop.
In while and do...while statements, the loop-continuation test evaluates
immediately after the continue statement executes.
In the for statement, the increment expression executes, then the loop-
continuation test evaluates.
1 // Fig. 5.14: fig05_14.cpp
2 // continue statement terminating an iteration
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 for ( int count = 1; count <= 10; count++ )
10 {
11 if ( count == 5 ) // if count is 5,
12 continue; // skip remaining code
13
14 cout << count << " ";
15 } // end for
16
17 cout<<"\nUsed continue to skip printing 5"<<endl;
18 return 0;
19 } // end main
Exercise 1
Write C++ statements to accomplish each of the following tasks.

Declare variables sum and x to be of type int.

Set variable x to 1.

Set variable sum to 0.

Add variable x to variable sum and assign the result to variable sum.

Print "The sum is: " followed by the value of variable sum.

Calculate and print the sum of the integers from 1 to 10. Use the while
statement to loop through the calculation and increment statements.
The loop should terminate when the value of x becomes 11.
Exercise 2
Write single C++ statements that do the following:

Input integer variable x with cin and >>.


Input integer variable y with cin and >>.

Set integer variable i to 1.


Set integer variable power to 1.

Multiply variable power by x and assign the result to power.

Determine whether i is less than or equal to y.

Output integer variable power with cout and <<.

Calculate x raised to the y power. The program should have


a while repetition statement.
Exercise 3
Write a C++ statement or a set of C++ statements to accomplish each
of the following:

Sum the odd integers between 1 and 99 using a for statement.

Assume the integer variables sum and count have been declared.

Calculate the value of 2.5 raised to the power 3 using function pow.
What prints?

Print the integers from 1 to 20 using a while loop and the counter
variable x. Assume that the variable x has been declared, but not
initialized. Print only 5 integers per line. [Hint: Use the calculation x %
5. When the value of this is 0, print a newline character; otherwise,
print a tab character.]

Repeat (d) using a for statement.


Exercise 4
Write single C++ statements that do the following:
Input integer variable n with n>0.
Calculate 2n
Calculate n!
Calculate

Calculate
Exercise 5
Write a C++ program to accomplish the following:

Input integer variable n with n>0.

How many digits are there in the variable n?

Calculate the sum of all digits which there are in


variable n.
Exercise 6
Write single C++ statements that do the following:

Input integer variable n with n>0.

Check whether n is a prime number.

Calculate the first n prime numbers.


Any Questions?

[email protected]
Quiz #2
1. Calculate the values of the following expressions
given a natural number n
n
k!
1 1 1
k =1
+ + .... +
2 3 k

2. Write a program that calculates the value of the


expression G
n
G =  ak bk
k =1

a = b =1
1 1

1 1 
a =  b k −1
+ a k −1

k
2 2 
= 2 a k −1 + bk −1
2
b k

You might also like