程序代写 CS2310 Computer Programming

Computer Science, City University of
Semester B 2021-22
CS2310 Computer Programming

Copyright By PowCoder代写 加微信 powcoder

LT5: Control Flow – Loop Statements

When the execution enters a loop, it executes a block of code repeatedly until the condition is NOT met

Beside sequential and branch execution, loop is another common control flow

while loop

while(condition){

In general , a program loop consists four parts:
Initialization statements
Exit condition
Post loop statements (stepping forward to exit loop condition)

cout << “Hello World\n” If (x>10) then exit the loop
Add 1 to X

Hello World

Another example to use while
#include
using namespace std;

void main() {
int cnt = 0, n;
float max, x;

cout << "The maximum value will be computed.\n"; cout << "How many numbers do you wish to enter? "; while (n <= 0) /* ensure a positive number is entered */ cout << "\nERROR: Positive integer required.\n\n"; cout << "How many numbers do you wish to enter? "; /* To be continued in next page */ Ensure a positive number input? Another example to use while cout << "\nEnter “ << n << “ real numbers: "; cin >> x; /* read 1st number */
/* pick the largest number in while-loop */
while (++cnt < n) { cin >> x; /* read another number */
cout << “The ” << cnt << “-th num is: ” << x << endl; if (max < x) cout << "\nMaximum value: " << max << endl; Repetitive execution based on user’s input do statement General form of do statement (repetition statement) statement(s); while (expression); Semantics: statement is executed first; thus the loop body is run at least once If the value of expression is non-zero (true), the loop repeats; otherwise, the loop terminates While vs Do while Example of do statement int error; /* no Boolean type support */ cout << “Input a positive integer: “; if (error = (n <= 0)) cout << “\nError: negative input!\n”; } while (error); For-loop statement for(expr1; expr2; expr3) loop statements; while(expr2) loop statements; The loop statements is executed as long as expr2 is true. When expr2 becomes false, the loop ends (e.g., i<10). expr1: Executed before entering the loop. Often used for variable initialization (e.g., int i=0). expr3: For each iteration, expr3 is executed after executing the loop body. Often used to update the counter variables (e.g., i++). Examples of for #include
using namespace std;

void main()
for(i=0;i<10;i++) cout << i << endl; #include
using namespace std;

void main()
for(int i=0;i<10;i++) if(i%2==0) cout << i << endl; for Loop: Syntax Error for (int k = 1; k <= 8; k++) cout << "log(" << k << ") = " << log(double(k)) << endl; cout << k << endl; // SYNTAX ERROR // Variable k can be declared before the for-loop for (k = 1; k <= 8; k++) cout << "sqrt(" << k << ") = " << sqrt(k) << endl; cout << k << endl; The variable k is declared within the for-loop statement. It is not visible/accessible outside the for-loop. #include
using namespace std;

int main(){

cout << "Enter a number: "; // for-loop; for (cin >> x; x <= 0; cin >> x)
cout << "Input must be positive." << endl; cout << "Enter number: "; // the while-loop equivalent to the above for-loop: cout << "Enter a number: "; while (x <= 0) cout << "Input must be positive." << endl; cout << "Enter number: "; cout << "The squre of " << x << " is " << x*x << endl; Enter a number: -3 Input must be positive. Enter number: 2 Enter a number: -3 Input must be positive. Enter number: 2 The squre of 2 is 4 For-loop statement expr1 and expr3 can contain multiple statements. Each statement is separated by a comma ',' for(i=0, j=0; i<10; i++, j++) expr1: i=0, j=0 expr2: i<10 expr3: i++, j++ Comma operator (,) It has the lowest precedence of all operators in C++ and is evaluated from left to right General form is expra, exprb The comma expression as a whole has the value and type of its right operand Sometimes used in for statements to allow multiple initializations and multiple processing of indices The comma operator is rarely used Not all commas in a C++ program are comma operators Common errors Mix up assignment = with equality operator == Mix up the comma operator with the semi-colon Unaware of extra semi-colons, e.g., for (j=1; j<=10; j++) is not the same as for (j=1; j<=10; j++); Common errors (cont’d) Fail to ensure that the termination condition of a loop is reachable  infinite loop Misuse of relational operators if (2 < k < 7) cout >> “true”;
cout >> “false”;

Use (2 < k && k < 7) for the correct answer Nested for-loop #include
using namespace std;
void main(){
for (i=0;i<3; i++){ cout << "Outer for:\n"; for (j=0;j<2; j++){ cout << "Inner for:"; cout << "i=“ << i << ", j=" << j << endl; cout << endl; Outer for: Inner for:i=0, j=0 Inner for:i=0, j=1 Outer for: Inner for:i=1, j=0 Inner for:i=1, j=1 Outer for: Inner for:i=2, j=0 Inner for:i=2, j=1 The outer loop is executed 3 times. For each iteration of the outer loop, the inner loop is executed 2 times Write a program to generate a multiplication of n rows and m column (where n and m is input by the user). Assume n>1 and m<=9 E.g. when n=4, m=3, the following table is generated 1 2 3 2 4 6 4 8 12 void 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++){ cout << i*j << “\t”; cout << endl; Use the Loop Counters in Nested Loop Cleverly for (int row = 1; row <= length; row++) // print (row-1) spaces for (int col = 1; col <= row - 1; col++) cout << " "; cout << "x" << endl; // print x on diagonal Enter diagonal length: 5 break statement the break statement causes an exit from the innermost enclosing loop or switch statement (discussed already) while (1) { if (n < 0) cout << n << endl; /* If break is run, jumps to here */ 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 Example of continue statement while (cnt < 10) { if (x > -0.01 && x < 0.01) continue; /* discard small values */ Continue, break Example: output the following matrix Example: output the following matrix first element first column Further remarks Use a relational expression, if possible, rather than an equality expression to control a loop or a selection statement, e.g., Don’t use while (j!=4) { Use while (j<4) { variable j, increasing from 0 to 3 Further remarks Don’t use a variable of any floating point data type to control a loop because real numbers are represented in their approximate values internally Infinite loop can be made Programming style Indent code in a consistent fashion to indicate the flow of control (use the tab key) Note the multiple levels of indentation Indentation void main() for(i = 0; i < 100; i++) cout << i; 1st level (1 tab) 2nd level (2 tabs) 3rd level (3 tabs) 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 In C++, repeating task could be expressed with while(…){…} do {…}while(…); for (…;…;…){…} A complete looping structure may consist of Loop initialization statements Exit condition Post Loop statements initialization While (...){ initialization initialization initialization While (...){ /docProps/thumbnail.jpeg 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com