Control Statements Control Statements Define the way of flow in which the program statements should take place. Implement decisions and repetitions. There are four types of controls in C: Bi-directional control (if ) Multidirectional conditional control (switch) Loop controls for loop while loop do while loop Unconditional control (goto) If Statement Use, when there are two possibilities (alternatives) could happen. 1 Did the user enter a zero or not? Program should take different actions in the zero case and non-zero case. 2 = b 2 4ac of a quadratic equation is non-negative or negative. Program should give real-valued sol ns for non-negative values of and complex-valued sol ns for negative values of. The if comes in two forms: if if If Statement if statement tests a particular condition if the condition evaluates as true (or nonzero) an action or set of actions is executed Otherwise, the action(s) are ignored. Syntax of the if statement //Single Statement if ( test_expression ) statement; Note: The test_expression must be enclosed within parentheses. //Multiple Statements if ( test_expression ) { statement_1; statement_2;
Flow Chart if Test Exp n False True if If Statement if statement allows either-or condition by using an clause if the condition evaluates as true (or non-zero) action(s) in if clause is/are executed Otherwise, the action(s) in clause is/are executed Syntax of the if statement //Single Statement if (test_expression) statement_1; statement_2; //Multiple Statements if (test_expression) { { Flow Chart if Examples 1) //Single Statement if (x<0) printf( Error: Negative number ); Test Exp n True False 2) //Single Statement if (mark < 40) printf( Very Bad: You failed the examination ); printf( Congratulations: You passed the examination ); if 3) //Multiple Statements if (op = = e op = = E ) { printf( Bye: Use MyProg again ); exit(0);
4) //Multiple Statements if (delta >= 0) { Examples 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 )); { // 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 )); More on if if statement can be nested within an another if. 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 Matching the clause More on if Matching the clause if ( a = = b ) //Correct Version if ( b = = c ) if ( a = = b ) { printf( a, b and c are the same ); if ( b = = c ) printf( a, b and c are the same ); printf( a and b are different ); 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, What s wrong with the code? The clause is matched with the inner if. How would we correct it? printf( a and b are different ); Now clause is matched with the outer if. Use braces { to match the clause correctly. Note: In cases like this, braces are compulsory even we have a single statement.
If Ladder Computer programs, like life, may present more than two selections. Can extend if to meet that need. //Compute student s grade //Revise format if ( mark >= 70 ) if ( mark >= 70 ) grade = A ; grade = A ; if ( mark >= 55 ) if ( mark >= 55 ) grade = B ; grade = B ; if ( mark >= 40 ) grade = C ; if ( mark >= 40 ) grade = C ; grade = F ; grade = F ; The Switch Statement Can use in C to select one of several alternatives. Screen menu that asks the user to select one of following four choices. 1: Add 2. Subtract 3: Multiply 4. Division 5. Exit 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: case const_2: case const_n default: 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 const_1 case const_1 const_2 case const_2 Control Variable const_n case const_n Other Value default 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. What would happen if one of the break statements omit? 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 Both the switch and if statements select a one from list of alternatives. if can handle ranges. But switch isn t designed to handle ranges. Each switch case label must be single valued. When switch statement? The case label value must be a constant. If all the alternatives can be identified with integer constants. Hmmm! We can use if with integer constants. Why then a switch statement? More efficient in terms of code size and execution speed. The Switch Statement Rule of thumb Use switch statement if you have three or more alternatives. 1 switch ( op ) { case 1: //Add result = num1 + num2; See the Indentation case 2: //Subtract result = num1 num2; case 3: //Multiply result = num1 * num2; case 4: // Division if ( num2!= 0 ) result = num1 / num2; case 5: // Exit exit(0); default: cout << Invalid key\n ;
The Switch Statement 2 switch (op) { case a : case A : result = num1 + num2; case s : case S : result = num1 num2; case m : case M : result = num1 * num2; case d : case D : if ( num2!= 0 ) result = num1 / num2; 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. 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). Such type of repetitive calculations can easily be done using loops. C++ provides three kinds of loop controls for loop while loop do while loop For Loop Use to repeat a statement or a block of statements a specified number of times. 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) Setting curworker (loop control variable) to 0. Performing a test to see if the loop should continue Testing curworker < 1000 Executing the loop actions Compute salary for the current worker Updating the loop control variable(s) Move to the next worker General form: For Loop //Single Statement for ( initialization; test_exp n ; update_exp n ) statement; //Multiple Statement for ( initialization; test_exp n ; update_exp n ) { statement_1; statement_2; statement_n;
Initialization For Loop Loop evaluates initialization just once (as soon as the loop is entered). Typically, programs use this expression to initialize the loop control variable ( curworker = 0;) This variable will also be used to count the loop cycles. Test expression If the test_exp n ( curworker < 1000) is true (or non-zero), the loop body will be executed. Otherwise the loop will be terminated. Update expression Initialization For Loop 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 ( curworker++). for ( int curworker = 1; curworker < 1000; curworker++ ) salary[curworker] = hoursworked[curworker] * wagerate; Loop body Test expression Update expression Flow Chart For Loop Initialization Test Exp n True False for While Loop Use when we do not know the exact number of repetitions before the loop execution begins. 1 Withdraw money from your bank account as long as your bank balance is above Rs. 1000/-. General form: //Single Statement while ( test_expression ) statement; //Multiple Statements while ( test_expression ) { statement_1; statement_2; Update Exp n statement_n;
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). Flow Chart While Loop Test Exp n False True while Note: While loop does not execute its body if the test_expression is initially 0 (false). While Loop Test expression while ( balance > 1000 ) { cout << Input your withdraw amount: ; cin >> withdrawamt; if ( balance withdrawamt <= 1000 ) cout << Sorry: Balance is not sufficient\n ; balance = balance withdrawamt; Loop body Do While Loop The While loop evaluates its test_expression at the beginning of the loop. 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. 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.) General form: do { //Single Statement do statement; while ( test_expression ); //Multiple Statements do { statement_1; statement_2; statement_n; while ( test_expression ) ; cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> den; cout << Quotient is << num / den << \n ; cout << Remainder is << num % den << \n ; cout << Do another? (y/n): ; cin >> doagain; while (ch!= n ); Flow Chart Do While Loop do while Test Exp n False True Break Statement Exits out of the current loop and transfers to the statement immediately following the loop. while ( i > 0 ) { cout << Count = << i++ << \n ; if ( i = = 5 ) // breaks out the loop when i = 5 cout << of program ; Output Count = 0 Count = 1 Count = 2 Count = 3 Count = 4 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. do { cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> den; cout << Quotient is << num / den << \n ; cout << Remainder is << num % den << \n ; cout << Do another? (y/n): ; cin >> doagain; while (ch!= 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 Use a continue statement to move to the top of the loop when the user inputs zero as den. do { cout << Enter the numerator: ; cin >> num; cout << Enter the denomenator: ; cin >> 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 );