370 likes | 519 Views
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…else ). Multidirectional conditional control ( switch ).
E N D
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…else) • Multidirectional conditional control (switch) • Loop controls • for … loop • while … loop • do … while loop • Unconditional control (goto)
If … else Statement • Use, when there are two possibilities (alternatives) could happen. • 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 = b2 – 4ac 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 ifcomes in two forms: • if … • if … else
If Statement • if statement tests a particular condition • if the condition evaluates as true (or non- zero) 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; • //Multiple Statements if ( test_expression ){ statement_1; statement_2; … } Indent one tab Indent one tab Note: The test_expression must be enclosed within parentheses.
Flow Chart – if … Start Test Expn False End True Body of if End
If … else Statement • if … else statement allows either-or condition by using an ‘else’ clause • 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 • //Single Statement if (test_expression) statement_1; else statement_2; • //Multiple Statements if (test_expression) { statement(s); } else { statement(s); } Indent one tab Indent one tab
Flow Chart – if … else Start Test Expn False Body of else End True Body of if End
Examples //Single Statement if (x<0) printf(“Error: Negative number”); //Single Statement if (mark < 40) printf(“Very Bad: You failed the examination”); else printf(“Congratulations: You passed the examination”); • //Multiple Statements if (op = = ‘e’ || op = = ‘E’) { printf(“Bye: Use MyProg again”); exit(0); }
Examples … • //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 )); }
More on “if … else” • “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 – 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”); • 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 “else” clause is matched with the inner “if”. • 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. //Revise format if ( mark >= 70 ) grade = ‘A’; else if ( mark >= 55 ) grade = ‘B’; else if ( mark >= 40 ) grade = ‘C’; else grade = “F’; //Compute student’s grade 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 • 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: 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 Other Value const_1 const_2 const_n Body of case const_1 Body of case const_2 Body of case const_n Body of default … End
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 … else • Both the “switch” and “if … else” statements select a one from list of alternatives. • “if … else” can handle ranges. But switchisn’t designed to handle ranges. • Each “switch case” label must be single valued. • The “case label value” must be a constant. • When … “switch” statement? • 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 … • Rule of thumb • Use switch statement if you have three or more alternatives. • 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”; } 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). • 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. • 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) • 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
For Loop … • General form: • //Single Statement for ( initialization;test_expn;update_expn) statement; • //Multiple Statement for ( initialization;test_expn;update_expn) { 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_expn (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; Test expression Update expression Initialization Loop body
Flow Chart – For Loop Start Initialization Test Expn False End True Body of for Update Expn
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/-. • General form: • //Single Statement while (test_expression ) statement; • //Multiple Statements while (test_expression ) { statement_1; statement_2; … statement_n; } Indent one tab
While Loop … • First a program evaluates the test_expression. • If the test_expression evaluates to a non-zerovalue (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 Expn False End True Body of while
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. • 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: • //Single Statement do statement; while (test_expression ); • //Multiple Statements do { • statement_1; • statement_2; • … • statement_n; • } while (test_expression ) ; Indent one tab • E.g. 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’);
Flow Chart – Do …While Loop Start Body of do…while Test Expn False End True
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 . • E.g. 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. • E.g. 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’);