Control Statements Control Statements A Define the way

  • Slides: 37
Download presentation
Control Statements

Control Statements

Control Statements A Define the way of flow in which the program statements should

Control Statements A Define the way of flow in which the program statements should take place. A Implement decisions and repetitions. There are four types of controls in C: A q Bi-directional control (if…else) q q Multidirectional conditional control (switch) Loop controls ð for … loop ð while … loop ð do … while loop Unconditional control (goto) q

If … else Statement A Use, when there are two possibilities (alternatives) could happen.

If … else Statement A Use, when there are two possibilities (alternatives) could happen. q q A E. g. 1 Did the user enter a zero or not? ð Program should take different actions in the zero case and non-zero case. E. g. 2 = b 2 – 4 ac of a quadratic equation is non-negative or negative. ð Program should give real-valued solns for non-negative values of and ð complex-valued solns for negative values of . The if comes in two forms: q q if … else

If Statement A A if statement tests a particular condition q if the condition

If Statement A A if statement tests a particular condition q if the condition evaluates as true (or nonzero) an action or set of actions is executed q Otherwise, the action(s) are ignored. Syntax of the ‘if’ statement q //Single Statement q if ( test_expression ) Indent one tab //Multiple Statements if ( test_expression ) { statement_1; statement_2; Indent one tab Note: The test_expression must be enclosed within parentheses. … }

Flow Chart – if … Start Test Expn True Body of if End False

Flow Chart – if … Start Test Expn True Body of if End False End

If … else Statement A if … else statement allows either-or condition by using

If … else Statement A if … else statement allows either-or condition by using an ‘else’ clause q q A if the condition evaluates as true (or non-zero) action(s) in if clause is/are executed Otherwise, the action(s) in else clause is/are executed Syntax of the ‘if … else’ statement q //Single Statement q if (test_expression) //Multiple Statements if (test_expression) { statement(s); statement_1; Indent one tab } else statement_2; else { statement(s); Indent one tab }

Flow Chart – if … else Start Test Expn True Body of if End

Flow Chart – if … else Start Test Expn True Body of if End False Body of else End

Examples 1) //Single Statement if (x<0) printf(“Error: Negative number”); 2) //Single Statement if (mark

Examples 1) //Single Statement if (x<0) printf(“Error: Negative number”); 2) //Single Statement if (mark < 40) printf(“Very Bad: You failed the examination”); else printf(“Congratulations: You passed the examination”); 3) //Multiple Statements if (op = = ‘e’ || op = = ‘E’) { printf(“Bye: Use My. Prog again”); exit(0); }

Examples … 4) //Multiple Statements if (delta >= 0) { printf( “Equation has real

Examples … 4) //Multiple Statements if (delta >= 0) { printf( “Equation has real rootsn”); printf (“Root 1 = %fn”, -b + sqrt( delta ) / ( 2 * a )); printf (“Root 2 = %fn”, -b - sqrt( delta ) / ( 2 * a )); } else { // delta is negative printf(“Equation has imaginary rootsn”); printf(“Root 1 = ( %f, %f)n, -b, sqrt( - delta ) / ( 2 * a )); printf(“Root 2 = ( %f, %f)n, -b, -sqrt( - delta ) / ( 2 * a )); }

More on “if … else” A “if … else” statement can be nested within

More on “if … else” A “if … else” statement can be nested within an another “if …else”. E. g. if ( op = = ‘e’ || op = = ‘E’ ) { printf(“Do you want to exit? (1 - Yes/0 – N 0)”); scanf(“%d”, do. Exit); //do. Exit is an ‘int’ variable if ( do. Exit = = 1 ) { cout << “Bye: Use My. Prog again”; exit(0); Nested within an “if …” statement } } A Watch out the indentation in the inner “if. . . ” statement.

More on “if … else” … A Matching the else clause if ( a

More on “if … else” … A Matching the else clause if ( a = = b ) if ( b = = c ) printf(“a, b and c are the same”); else printf( “a and b are different”); A If a = b = 3 and c = 2, what is the output? q q q A A Output: a and b are different But a and b are same. Hmmm ! Then, What’s wrong with the code? The “else” clause is matched with the inner “if”. How would we correct it?

More on “if … else” … A Matching the else clause … q //Correct

More on “if … else” … A Matching the else clause … q //Correct Version if ( a = = b ) { if ( b = = c ) printf( “a, b and c are the same”); } else printf( “a and b are different”); A Now “else” clause is matched with the outer “if”. A Use braces { } to match the else clause correctly. Note: In cases like this, braces are compulsory even we have a single statement. A

“If … else” Ladder A A Computer programs, like life, may present more than

“If … else” Ladder A A Computer programs, like life, may present more than two selections. Can extend “if …else” to meet that need. //Compute student’s grade //Revise format if ( mark >= 70 ) grade = ‘A’; else if ( mark >= 55 ) grade = ‘B’; else if ( mark >= 40 ) grade = ‘C’; else grade = “F’;

The Switch Statement A A Can use in C to select one of several

The Switch Statement A A Can use in C to select one of several alternatives. E. g. Screen menu that asks the user to select one of following four choices. v v v A 1: Add 2. Subtract 3: Multiply 4. Division 5. Exit Useful when the selection is based on q q a value of a single variable (controlling variable) a value of a simple expression (controlling expression).

The Switch Statement … A General form: switch ( controlling variable/expression ) { case

The Switch Statement … A General form: switch ( controlling variable/expression ) { case const_1: statement(s); break; case const_2: statement(s); break; … case const_n statement(s); break; default: statement(s); } “break” statement is not necessary after default statements

The Switch Statement … A Switch statement works as follows: q If the control

The Switch Statement … A Switch statement works as follows: q If the control variable/expression evaluated as v v A const_1 statements under the case const_1 executed. const_2 statements under the case const_2 executed. const_n statements under the case const_n executed. other value statements under the default executed. “break” statement in each case causes exit from the switch statement.

Flow Chat - Switch Statement Start Control Variable const_1 Body of case const_1 const_2

Flow Chat - Switch Statement Start Control Variable const_1 Body of case const_1 const_2 Body of case const_2 const_n … End Body of case const_n Other Value Body of default

The Switch Statement … A The value of this controlling variable or expression may

The Switch Statement … A The value of this controlling variable or expression may be of type v v A The “default” statement is optional. q A int or char or long But not double or float. If you omit it and there is no match, the program jumps to the next statement following the switch. What would happen if one of the “break” statements omit? q q When the program jumps to the particular case statement, it executes statements under it. Then it sequentially executes the following case statements until it reaches to a break statement.

Switch and if … else A Both the “switch” and “if … else” statements

Switch and if … else A Both the “switch” and “if … else” statements select a one from list of alternatives. A “if … else” can handle ranges. But switch isn’t designed to handle ranges. q q A Each “switch case” label must be single valued. The “case label value” must be a constant. When … “switch” statement? q q If all the alternatives can be identified with integer constants. Hmmm ! We can use “if … else” with integer constants. Why then a switch statement? ð More efficient in terms of code size and execution speed.

The Switch Statement … A Rule of thumb ð A Use switch statement if

The Switch Statement … A Rule of thumb ð A Use switch statement if you have three or more alternatives. E. g. 1 See the Indentation switch ( op ) { case 1: //Add result = num 1 + num 2; break; case 2: //Subtract result = num 1 – num 2; break; case 3: //Multiply result = num 1 * num 2; break; case 4: // Division if ( num 2 != 0 ) result = num 1 / num 2; break; case 5: // Exit exit(0); default: cout << “Invalid keyn”; }

The Switch Statement … A E. g. 2 switch (op) { case ‘a’: case

The Switch Statement … A E. g. 2 switch (op) { case ‘a’: case ‘A’: result = num 1 + num 2; break; case ‘s’: case ‘S’: result = num 1 – num 2; break; case ‘m’: case ‘M’: result = num 1 * num 2; break; case ‘d’: case ‘D’: if ( num 2 != 0 ) result = num 1 / num 2; break; case ‘e’: case ‘E’: exit(0); default: cout << “Invalid keyn”; }

Loops A Many jobs that are required to be done with the help of

Loops A Many jobs that are required to be done with the help of a computer are repetitive in nature. A E. g. Calculation of salary of different casual workers in a factory. q q A The salary is calculated in the same manner for each worker (salary = no of hours worked * wage rate). Such type of repetitive calculations can easily be done using loops. C++ provides three kinds of loop controls q q q for … loop while … loop do … while loop

For Loop A Use to repeat a statement or a block of statements a

For Loop A Use to repeat a statement or a block of statements a specified number of times. A E. g. Calculation of salary of 1000 workers. q A In advance, the programmer knows the loop must repeat 1000 times. The usual parts of a for loop handle these steps: q q Setting an initial value to loop control variable(s) ð Setting cur. Worker (loop control variable) to 0. Performing a test to see if the loop should continue ð Testing cur. Worker < 1000 Executing the loop actions ð Compute salary for the current worker Updating the loop control variable(s) ð Move to the next worker

For Loop … A General form: q //Single Statement for ( initialization; test_expn; update_expn

For Loop … A General form: q //Single Statement for ( initialization; test_expn; update_expn ) statement; q //Multiple Statement for ( initialization; test_expn; update_expn ) { statement_1; Indent one tab statement_2; … statement_n; }

For Loop … A Initialization q q q A Loop evaluates initialization just once

For Loop … A Initialization q q q A Loop evaluates initialization just once (as soon as the loop is entered). Typically, programs use this expression to initialize the loop control variable (E. g. cur. Worker = 0; ) This variable will also be used to count the loop cycles. Test expression q If the test_expn (E. g. cur. Worker < 1000) is true (or non-zero), the loop body will be executed. q Otherwise the loop will be terminated.

For Loop … A Update expression q q A is evaluated at the end

For Loop … A Update expression q q A is evaluated at the end of the loop, after the body has been executed. Typically, it is used to increase or decrease the value of the loop control variable (E. g. cur. Worker++). E. g. for ( int cur. Worker = 1; cur. Worker < 1000; cur. Worker++ ) salary[cur. Worker] = hours. Worked[cur. Worker] * wage. Rate; Test expression Initialization Loop body Update expression

Flow Chart – For Loop Start Initialization Test Expn True Body of for Update

Flow Chart – For Loop Start Initialization Test Expn True Body of for Update Expn False End

While Loop A Use when we do not know the exact number of repetitions

While Loop A Use when we do not know the exact number of repetitions before the loop execution begins. q A E. g. 1 Withdraw money from your bank account as long as your bank balance is above Rs. 1000/-. General form: q //Single Statement while ( test_expression ) q //Multiple Statements while ( test_expression ) { statement_1; statement_2; Indent one tab … statement_n; }

While Loop … A First a program evaluates the test_expression. A If the test_expression

While Loop … A First a program evaluates the test_expression. A If the test_expression evaluates to a non-zero value (true), the program executes the statement(s) in the body. A After finishing with the body, the program returns to the test_expression and reevaluates it. A If the test_expression is again non-zero, the program executes the body again. A This cycle of testing and execution continues until the test_expression evaluates to 0 (false). Note: While loop does not execute its body if the test_expression is initially 0 (false).

Flow Chart – While Loop Start Test Expn True Body of while False End

Flow Chart – While Loop Start Test Expn True Body of while False End

While Loop … A E. g. Test expression while ( balance > 1000 )

While Loop … A E. g. Test expression while ( balance > 1000 ) { cout << “Input your withdraw amount: “; cin >> withdraw. Amt; if ( balance – withdraw. Amt <= 1000 ) cout << “Sorry: Balance is not sufficientn”; else balance = balance – withdraw. Amt; } Loop body

Do … While Loop A The While loop evaluates its test_expression at the beginning

Do … While Loop A The While loop evaluates its test_expression at the beginning of the loop. ð A A A Loop will not never execute if the test_expression is zero (false). But there are situations where you need to execute the body at least once. In such situations, you should use a do…while. Do … while loop executes its body first. Next, it evaluates the test_expression. A If the test_expression is non-zero (true) executes the body again. A This cycle of testing and execution continues until the test_expression evaluates to 0 (false). A

Do … while Loop (cont. ) A General form: q //Single Statement //Multiple Statements

Do … while Loop (cont. ) A General form: q //Single Statement //Multiple Statements do { do statement; while ( test_expression ); statement_1; statement_2; … statement_n; } while ( test_expression ) ; Indent one tab A q E. g. do { cout cout } while (ch << << << != “Enter the numerator: “; cin >> num; “Enter the denomenator: “; cin >> den; “Quotient is “ << num / den << “n”; “Remainder is “ << num % den << “n”; “Do another? (y/n): ”; cin >> do. Again; ‘n’);

Flow Chart – Do …While Loop Start Body of do…while Test Expn True False

Flow Chart – Do …While Loop Start Body of do…while Test Expn True False End

Break Statement A Exits out of the current loop and transfers to the statement

Break Statement A Exits out of the current loop and transfers to the statement immediately following the loop. A E. g. while ( i > 0 ) { cout << “Count = “ << i++ << “n”; if ( i = = 5 ) // breaks out the loop when i = 5 break; } cout << “End of program”; Output Count = 0 Count = 1 Count = 2 Count = 3 Count = 4 End of program

Continue Statement A The break statement takes you out of the bottom of a

Continue Statement A The break statement takes you out of the bottom of a loop. A Sometimes you need to go back to top of the loop, when something happens unexpectedly. A E. g. do { cout cout } while (ch q ð << << << != “Enter the numerator: “; cin >> num; “Enter the denomenator: “; cin >> den; “Quotient is “ << num / den << “n”; “Remainder is “ << num % den << “n”; “Do another? (y/n): ”; cin >> do. Again; ‘n’); What is the output if the user keyed a zero (0) as den? Occurs an runtime error as num / den is not defined.

Continue Statement … A A Use a continue statement to move to the top

Continue Statement … A A Use a continue statement to move to the top of the loop when the user inputs zero as den. E. g. do { cout << “Enter the numerator: “; cin >> num; cout << “Enter the denomenator: “; cin >> den; if ( den = = 0 ) { cout << “Illegal denomenatorn”; continue; } cout << “Quotient is “ << num / den << “n”; cout << “Remainder is “ << num % den << “n”; cout << “Do another? (y/n): ”; cin >> do. Again; } while (ch != ‘n’);