Vous êtes sur la page 1sur 23

International University

Intro to C++ Language_ Part 2

2011, Oct. 18th

HA VIET UYEN SYNH, Ph.D. SCHOOL OF COMPUTER SCIENCE & ENGINEERING INTERNATIONAL UNIVERSITY, VIETNAM NATIONAL UNIVERSITY

International University

Overview

The School of Computer Science and Engineering (SCSE)

International University

Rules for forming structured programs


RulesforFormingStructuredPrograms 1.Beginwiththe"simplestactivitydiagram. 2.Anyactionstatecanbereplacedbytwoactionstatesinsequence_Stackingrule . 3.Anyactionstatecanbereplacedbyanycontrolstatement(sequence,if,if...else,switch, while,do...whileorfor)_Nestingrule. 4.Rules2and3canbeappliedasoftenasyoulikeandinanyorder.

The School of Computer Science and Engineering (SCSE)

International University

Applying Stacking Rule

The School of Computer Science and Engineering (SCSE)

International University

Applying Nesting Rule

The School of Computer Science and Engineering (SCSE)

International University

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";


The School of Computer Science and Engineering (SCSE)
6

International University

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

The School of Computer Science and Engineering (SCSE)

International University

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";

The School of Computer Science and Engineering (SCSE)

International University

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;

The School of Computer Science and Engineering (SCSE)

International University

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

The School of Computer Science and Engineering (SCSE)

10

International University

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)
The School of Computer Science and Engineering (SCSE)
11

International University

Counter-controlled repetition with the for statement.


1//Fig.5.2:fig05_02.cpp 2//Countercontrolledrepetitionwiththeforstatement. 3#include <iostream> 4using std::cout; 5using std::endl; 6 7int main() 8{ 9//forstatementheaderincludesinitialization, 10//loopcontinuationconditionandincrement. 11for (int counter=1;counter<=10;counter++) 12cout <<counter<<""; 13 14cout <<endl;//outputanewline 15return 0;//indicatesuccessfultermination 16}//endmain

1 2 3 4 5 6 7 8 9 10

The School of Computer Science and Engineering (SCSE)

12

International University

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 );
The School of Computer Science and Engineering (SCSE)
13

International University

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

The School of Computer Science and Engineering (SCSE)

14

International University

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

The School of Computer Science and Engineering (SCSE)

15

International University

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 loopcontinuation test evaluates immediately after the continue statement executes. In the for statement, the increment expression executes, then the loopcontinuation test evaluates.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

// Fig. 5.14: fig05_14.cpp // continue statement terminating an iteration #include <iostream> using std::cout; using std::endl; int main() { for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) // if count is 5, continue; // skip remaining code

cout << count << " "; } // end for

17 cout << "\nUsed continue to skip printing 5 " << endl; 18 19 return 0; } // end main

The School of Computer Science and Engineering (SCSE)

16

International University

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.

The School of Computer Science and Engineering (SCSE)

17

International University

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.

The School of Computer Science and Engineering (SCSE)

18

International University

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. Print the value 333.546372 in a field width of 15 characters with precisions of 1, 2 and 3. Print each number on the same line. Left-justify each number in its field. What three values print? Calculate the value of 2.5 raised to the power 3 using function pow. Print the result with a precision of 2 in a field width of 10 positions. 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.

The School of Computer Science and Engineering (SCSE)

19

International University

Exercise 4

Write single C++ statements that do the following:

Input integer variable n with n>0. Calculate 2n Calculate n! Calculate

Calculate

The School of Computer Science and Engineering (SCSE)

20

International University

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.

The School of Computer Science and Engineering (SCSE)

21

International University

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.

The School of Computer Science and Engineering (SCSE)

22

International University

Any question?

23

Vous aimerez peut-être aussi