0% found this document useful (0 votes)
68 views14 pages

The Result of The Assignment #1: C++ Language Control Statement

This document summarizes a presentation on C++ control statements. It introduces if, if-else, switch, while, do-while, for statements. Examples are provided for each control statement to calculate sums, factorials, roots of equations. Exercises are included at the end to write programs using control statements to calculate sums and powers.

Uploaded by

badboy2011
Copyright
© Attribution Non-Commercial (BY-NC)
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)
68 views14 pages

The Result of The Assignment #1: C++ Language Control Statement

This document summarizes a presentation on C++ control statements. It introduces if, if-else, switch, while, do-while, for statements. Examples are provided for each control statement to calculate sums, factorials, roots of equations. Exercises are included at the end to write programs using control statements to calculate sums and powers.

Uploaded by

badboy2011
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 14

C++ Language Part 2: Control Statement

Presenter:HaVietUyen Synh,Ph.D.

The result of the Assignment #1


TrngiTrm VPhmNgc HongSn VVngPh PhmNgc NguynHu NguynTrng TrnhMinh NguynTn PhmTn LAnh HLThanh TrnAnh Anh n Dng Hi Hip Huy Ngha Quang Thnh Tin T Tng V IEIESB10083 IESB09037 IESB09031 ISERG0806 IESB09033 IEIEIU10008 IEIEIU10018 IEIU09006 IESB09035 IEIEIU10009 IEIESB10082 IEIESB10081 IEIU09015 10 10 10 10 10 9 7 10 10 ??(emptyfolder) 9 7 X
2

The School of Computer Science and Engineering (SCSE)

Overview

The School of Computer Science and Engineering (SCSE)

Rules for forming structured programs


RulesforFormingStructuredPrograms Beginwiththe"simplestactivitydiagram. Anyactionstatecanbereplacedbytwoactionstatesinsequence_ Stackingrule . Anyactionstatecanbereplacedbyanycontrolstatement (sequence,if,if...else,switch,while,do...whileorfor)_Nestingrule. Rules2and3canbeappliedasoftenasyoulikeandinanyorder.

The School of Computer Science and Engineering (SCSE)

Applying Stacking Rule

The School of Computer Science and Engineering (SCSE)

Applying Nesting Rule

The School of Computer Science and Engineering (SCSE)

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)

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)

Example
Writeaprogramthatfindstherootofthelinearequationgivenbyax +bwherea,baretheargumentstotheprogram. Inthecase,a!=0 x=b/a Intheothercase,a==0 Ifb==0 xisundetermined Ifb!=0 xisnosolution.

The School of Computer Science and Engineering (SCSE)

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)

Example
Writeaprogramthatfindstherootsofthequadraticequationgiven bya*x^2+b*x+cwherea,bandcaretheargumentstothe program. Delta=b^2 4*a*c IfDelta>0, x1,2 =(b sqrt(Delta))/(2*a) IfDelta==0, x=b/(2*a) IfDelta!=0, xisnosolution

11

The School of Computer Science and Engineering (SCSE)

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)

Counter-controlled repetition
//Fig.5.1:fig05_01.cpp //Countercontrolledrepetition. #include<iostream> usingstd::cout; usingstd::endl; intmain() { intcounter=1;//declareandinitializecontrolvariable while(counter<=10)//loopcontinuationcondition { cout<<counter<<""; counter++;//incrementcontrolvariableby1 }//endwhile cout<<endl;//outputanewline return0;//successfultermination }//endmain 12345678910

The School of Computer Science and Engineering (SCSE)

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)

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

12345678910

The School of Computer Science and Engineering (SCSE)

Example
Writeaprogramthatcalculatesfactorialofn(n!),wherenisthe argumenttotheprogram

16

The School of Computer Science and Engineering (SCSE)

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)

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)

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)

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 // Fig. 5.14: fig05_14.cpp 2 // continue statement terminating an iteration 3 #include <iostream> 4 5 6 7 8 9 10 11 12 13 14 15 16 17 cout << "\nUsed continue to skip printing 5 " << endl; 18 19 return 0; } // end main int main() { for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) // if count is 5, continue; // skip remaining code using std::cout; using std::endl;

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

The School of Computer Science and Engineering (SCSE)

10

Any Questions?

Contact
[email protected]

Exercise 1
WriteC++statementstoaccomplisheachofthefollowingtasks. Declarevariablessumandxtobeoftypeint. Setvariablexto1. Setvariablesumto0. Addvariablextovariablesumandassigntheresulttovariablesum. Print"Thesumis:"followedbythevalueofvariablesum. Calculateandprintthesumoftheintegersfrom1to10.Usethe whilestatementtoloopthroughthecalculationandincrement statements.Theloopshouldterminatewhenthevalueofxbecomes 11.

The School of Computer Science and Engineering (SCSE)

11

Exercise 2
WritesingleC++statementsthatdothefollowing: Inputintegervariablexwithcin and>>. Inputintegervariableywithcin and>>. Setintegervariablei to1. Setintegervariablepowerto1. Multiplyvariablepowerbyxandassigntheresulttopower. Determinewhetheri islessthanorequaltoy. Outputintegervariablepowerwithcout and<<. Calculatexraisedtothepowery.Theprogramshouldhaveawhile repetitionstatement.

The School of Computer Science and Engineering (SCSE)

Exercise 3
WriteaC++statementorasetofC++statementstoaccomplisheach ofthefollowing: Sumtheoddintegersbetween1and99usingaforstatement. Assumetheintegervariablessumandcounthavebeendeclared. Calculatethevalueof2.5raisedtothepower3usingfunctionpow. Whatprints? Printtheintegersfrom1to20usingawhileloopandthecounter variablex.Assumethatthevariablexhasbeendeclared,butnot initialized.Printonly5integersperline.[Hint:Usethecalculationx %5.Whenthevalueofthisis0,printanewlinecharacter; otherwise,printatabcharacter.] Repeat(d)usingaforstatement.

The School of Computer Science and Engineering (SCSE)

12

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)

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)

13

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)

14

You might also like