# Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.

## Presentation on theme: "Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions."— Presentation transcript:

Control Statements

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

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

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

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

if … else statement allows either-or condition by using an else clause If … else Statement Syntax of the if … else statement //Single Statement if (test_expression) statement_1; else statement_2; //Multiple Statements if (test_expression) { statement(s); } else { statement(s); } 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 Indent one tab

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

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 MyProg again); exit(0); }

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

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

More on if … else … 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); The else clause is matched with the inner if. If a = b = 3 and c = 2, what is the output? Output: a and b are different But a and b are same. Hmmm ! Then, Whats wrong with the code? How would we correct it?

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

If … else Ladder Computer programs, like life, may present more than two selections. Can extend if …else to meet that need. //Compute students grade if ( mark >= 70 ) grade = A; else if ( mark >= 55 ) grade = B; else if ( mark >= 40 ) grade = C; else grade = F; //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 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. 1: Add 2. Subtract 5. Exit 3: Multiply 4. Division Useful when the selection is based on a value of a single variable (controlling variable) a value of a simple expression (controlling expression).

The Switch Statement … 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 … Switch statement works as follows: If the control variable/expression evaluated as 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 End Body of case const_1 const_1 Body of case const_2 const_2 Body of case const_n const_n Body of default Other Value …

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

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

The Switch Statement … Rule of thumb E.g. 1 switch ( op ) { case 1: //Add result = num1 + num2; break; case 2: //Subtract result = num1 – num2; break; case 3: //Multiply result = num1 * num2; break; case 4: // Division if ( num2 != 0 ) result = num1 / num2; break; case 5: // Exit exit(0); default: cout << Invalid key\n; } U se switch statement if you have three or more alternatives. See the Indentation

The Switch Statement … E.g. 2 switch (op) { case a: case A: result = num1 + num2; break; case s: case S: result = num1 – num2; break; case m: case M: result = num1 * num2; break; case d: case D: if ( num2 != 0 ) result = num1 / num2; break; case e: case E: exit(0); default: cout << Invalid key\n; }

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

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

For Loop … //Single Statement for ( initialization; test_exp n ; update_exp n ) statement; General form: //Multiple Statement for ( initialization; test_exp n ; update_exp n ) { statement_1; statement_2; … statement_n; } Indent one tab

For Loop … Initialization 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. curWorker = 0;) This variable will also be used to count the loop cycles. Test expression If the test_exp n (E.g. curWorker < 1000) is true (or non-zero), the loop body will be executed. Otherwise the loop will be terminated.

For Loop … Update expression 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. curWorker++). E.g. for ( int curWorker = 1; curWorker < 1000; curWorker++ ) salary[curWorker] = hoursWorked[curWorker] * wageRate; Initialization Test expressionUpdate expression Loop body

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

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

While Loop … First a program evaluates the test_expression. If the test_expression evaluates to a non-zero value (true), the program executes the statement(s) in the body. After finishing with the body, the program returns to the test_expression and reevaluates it. If the test_expression is again non-zero, the program executes the body again. 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 Exp n Body of while End True False

While Loop … E.g. while ( balance > 1000 ) { cout << Input your withdraw amount: ; cin >> withdrawAmt; if ( balance – withdrawAmt <= 1000 ) cout << Sorry: Balance is not sufficient\n; else balance = balance – withdrawAmt; } Test expression Loop body

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

Do … while Loop (cont.) //Single Statement do statement; while ( test_expression ); //Multiple Statements do { statement_1; statement_2; … statement_n; } while ( test_expression ) ; General form: Indent one tab E.g. do { cout > num; cout > den; cout << Quotient is << num / den << \n; cout << Remainder is << num % den << \n; cout > doAgain; } while (ch != n);

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

Break Statement Exits out of the current loop and transfers to the statement immediately following the loop. 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 The break statement takes you out of the bottom of a loop. Sometimes you need to go back to top of the loop, when something happens unexpectedly. Occurs an runtime error as num / den is not defined. E.g. do { cout > num; cout > den; cout << Quotient is << num / den << \n; cout << Remainder is << num % den << \n; cout > doAgain; } while (ch != n); What is the output if the user keyed a zero (0) as den?

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

Download ppt "Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions."

Similar presentations