Download presentation
Presentation is loading. Please wait.
1
Chapter 4 Program Control Statements
C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
2
In this chapter we will learn about the statements that control a program’s flow of execution.
There are three specific categories of program control statements: Selection - if and switch statements Iteration - for, while, and do-while statements Jump break, continue, return, and goto statements
3
The if Statement Its format is:
if( expression ) statement; else The else clause is OPTIONAL. Both the if and else may contain blocks of code as shown below. if( expression ) { statement1; statement2; } else { statement3; statement4; Code block Code block
4
The if Statement (continued)
At no time will the code in both the if and else blocks be executed. The conditional expression of an if statement can be any type of valid expression that produces a true or false result. For example: int Good; if( Good ) . . . int Fun(); if( Fun() ) . . . if( 8 > 6 ) . . . bool Old; if( Old ) . . . Remember the else clause is OPTIONAL.
5
The Conditional Expression
Remember that a value of zero is automatically converted to false, and all non-zero values are converted to true. Therefore, any expression that results in a zero or non-zero value can be used to control an if statement. The following program reads two integers from the keyboard and divides the first value by the second value displaying the quotient (remember that division by zero is undefined and will cause your program to BLOW-UP).
6
The Conditional Expression (continued)
// Divide the first number by the second. #include <iostream> using namespace std; int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; if( b ) // make sure divisor is not zero cout << a / b << '\n'; else cout << "Cannot divide by zero.\n"; return 0; }
7
The Conditional Expression (continued)
You could have used the following code in the previous program: if( b != 0 ) cout << a / b << endl; Using this code is redundant and potentially inefficient.
8
This sounds complicated!
Nested ifs A nested if is an if statement that is the target of another if or else. They are very common. C/C++ allows at least 256 levels of nesting. An else statement ALWAYS refers to the nearest if statement that is within the same block of code as the else and NOT already associated with an else. This sounds complicated!
9
Nested ifs (continued)
Consider the following: if( i ) { if( j ) statement1; if( k ) statement2; // this if else statement3; // is associated with this else } statement4; // associated with if( i )
10
Nested ifs (continued)
What will the following code output assuming the code compiles correctly? int x = 3; int y = 2; if ( x > 2 ) { if ( y > 2 ) { int z = x + y; cout << "z is " << z << endl; } else cout << “x is " << x << endl;
11
Nested ifs (continued)
What will the following code output assuming the code compiles correctly? int x = 2; int y = 3; if ( x > 2 ) if ( y > 2 ) { int z = x + y; cout << "z is " << z << endl; } else cout << “x is “ << x << endl;
12
Nested ifs (continued)
Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult for you to determine the logical structure of the if statement. In this case it is a common programming practice an if-else-if ladder construct.
13
if-else-if ladder Example: if( condition ) {
// code statements if this condition is True } else if( condition ) { else { // code statements if all conditions are False
14
if-else-if ladder (continued)
As soon as a true condition occurs, the associated statement(s) are executed, and the rest of the ladder is bypassed. If none of the conditions are true, the final else statement is executed (it acts as the default condition). If more than one condition is true, only the task following the first true condition executes. Therefore, the order of the conditions can affect the outcome.
15
if-else-if ladder (continued)
// Demonstrate an if-else-if ladder. #include <iostream> using namespace std; int main() { int x; for( x = 0; x < 6; x++ ) { if( x == 1 ) cout << "x is one\n"; else if( x == 2 ) cout << "x is two\n"; else if( x == 3 ) cout << "x is three\n"; else if( x == 4 ) cout << "x is four\n"; else cout << "x is not between 1 and 4\n"; } return 0;
16
if-else-if ladder (continued)
Output: x is not between 1 and 4 x is one x is two x is three x is four Notice the default else is executed only if none of the preceding if statements are true.
17
Using Separate if Statements
char MaritalStatus; if( MaritalStatus == ‘M’ ) cout << “Married “; if( MaritalStatus == ‘S’ ) cout << “Single “; if( MaritalStatus == ‘D’ ) cout << “Divorced “; if( MaritalStatus == ‘W’ ) cout << “Widowed “; if( MaritalStatus == ‘P’ ) cout << “Separated”; else cout << “Unknown “; Is this code OK?
18
Using Nested if Statements
char MaritalStatus; if( MaritalStatus == ‘M’ ) cout << “Married “; else if( MaritalStatus == ‘S’ ) cout << “Single “; if( MaritalStatus == ‘D’ ) cout << “Divorced “; if( MaritalStatus == ‘W’ ) cout << “Widowed “; if( MaritalStatus == ‘P’ ) cout << “Separated”; cout << “Unknown “; Is this code OK?
19
Using an if-else-if ladder
char MaritalStatus; if( MaritalStatus == ‘M’ ) cout << “Married “; else if( MaritalStatus == ‘S’ ) cout << “Single “; else if( MaritalStatus == ‘D’ ) cout << “Divorced “; else if( MaritalStatus == ‘W’ ) cout << “Widowed “; else if( MaritalStatus == ‘P’ ) cout << “Separated”; else cout << “Unknown “; Is this code OK?
20
The for Loop The general form is: Where:
for ( initialize; expression; increment ) statement; OR for ( initialize; expression; increment ) { statement sequence } Where: initialization - Executed when the loops first starts and is executed only once. This step typically initializes the loop control variable. expression - Tested to see if the expression is true or false. If true the loop continues else it is terminated. increment This step usually increments or decrements the loop control variable each time the loop repeats.
21
The for Loop Example This prgram displays the square roots of the numbers between 1 and 99. #include <iostream> #include <cmath> using namespace std; int main() { int num; double sq_root; for( num = 1; num < 100; num++ ) { sq_root = sqrt( (double) num ); cout << num << “ “ << sq_root << ‘\n’; } return 0;
22
The for Loop Example Output: 1 1 2 1.41421 3 1.73205 4 2 5 2.23607
9 3
23
The for Statement Samples
int num; for( num = 0; num < 10; num++ ) { cout << “Num = “ << num << endl; } int num; for( num = 10; num > 0; num-- ) { cout << “Num = “ << num << endl; } int z; for( num = 0, z = 4; num < 10; num++, z = z * 2 ) { cout << “Num = “ << num << endl; cout << “Z = “ << z << endl; } for( ; ; ) cout << “Good news” << endl;
24
The for Statement Samples (continued)
for( int i = 0; i < 100; i++ ) cout << ‘ ’; num = 1; for( ; num <= 10; num = num + 1 ) { cout << “Num = “ << num << endl; } int num; char ch; for( num = 0; ch != ‘Q’; num++ ) { cout << “Num = “ << num << endl; } for( ; !feof( PayFile ); ) { Process(); }
25
The for Statement The condition expression is ALWAYS tested at the top of the loop. This means (as in a do-while loop) the statements inside the loop will not be executed if the condition is false to begin with. The for is one of the most versatile statements in C/C++. The for statement may have multiple initialization statements (must be separated by commas), conditional expressions, and increment and/or decrement statements. The initialization, conditional expression, and increment sections are all optional, but the semicolons ( ; ) are required.
26
Time Delay Loop The for statement can be used to implement time delay loop. For example: for( x = 0; x < 1000; x++ ); This code simply stops execution of the program for as long as it takes to count to 1000. Note the semicolon at the end of the statement. This is required because the for statement expects at least one statement in the loop.
27
switch Statement The switch statement is useful when the selection is based on the value of a single variable or of a simple expression. The value of the expression may be of type int, char, or an enumerated type. The general syntax is: switch ( variable/value returned from a function ) { case constant1 : statement or statement sequence break; case constant2 : statement or statement sequence . default : statement or statement sequence }
28
switch Statement (continued)
The break causes an exit from the switch statement, and execution continues with the statement that follows the closing brace of the switch statement body. The default statement MUST be last and contains the statement sequence to be executed if non of the other case values are detected. If the break is omitted the execution falls through into the next alternative.
29
switch Statement (continued)
The switch differs from the if in that the switch can test only for equality between the switch expression and the case constant. The if conditional expression can be any type. No two case constants in the same switch can have the same values, unless you have a nested switch statement. A switch statement is usually more efficient than a nested ifs. The statement/statement sequences associated with each case are NOT blocks. However the entire switch statement does define a block ( { } ). A switch statement can have at least 16,384 case statements.
30
Sample switch Statement
#include <iostream> using namespace std; int main() { int x; cout << "Enter a number between 1 and 4: "; cin >> x; switch ( x ) { case 1 : cout << "You entered One\n"; break; case 2 : cout << "You entered Two\n"; case 3 : cout << "You entered Three\n"; case 4 : cout << "You entered Four\n"; default: cout << "You entered an Unrecognized Number\n"; break; // this break statement is optional } return 0;
31
Sample switch Statement
What will this switch statement do? #include <iostream> using namespace std; int main() { int x; cout << "Enter a number between 1 and 4: "; cin >> x; switch ( x ) { case 1 : cout << "You entered One\n"; case 2 : cout << "You entered Two\n"; case 3 : cout << "You entered Three\n"; case 4 : cout << "You entered Four\n"; default: cout << "You entered an Unrecognized Number\n"; } return 0;
32
The break Statement is Optional
#include <iostream> using namespace std; int main() { for( int i = 0; i < 12; i++) switch( i ) { case 0 : case 1 : case 2 : case 3 : case 4 : cout << "i is < than 5“ << endl; break; case 5 : case 6 : case 7 : case 8 : case 9 : cout << “i is < than 10“ << endl; default: cout << "i is 10 or more“ << endl; } // end of switch return 0; } // end of main
33
The break Statement is Optional
Output: i is less than 5 i is less than 10 i is 10 or more
34
int month = 4; char season[12]; switch ( month ) { case 12 : case 1 : case 2 : strcpy(season, "Winter“); break; case 3 : case 4 : case 5 : strcpy(season, “Spring“); case 6 : case 7 : case 8 : strcpy(season, "Summer“); case 9 : case 10 : case 11 : strcpy(season, "Autumn“); default : strcpy(season, "Bogus Month“); } // end of switch cout << "April is in the " << season << ".“ << endl;
35
Sample switch Statement
char MaritalStatus; switch( MaritalStatus ) { case ‘M’ : cout << “Married “; break; case ‘S’ : cout << “Single “; case ‘D’ : cout << “Divorced “; case ‘W’ : cout << “Widowed “; case ‘P’ : cout << “Separated“; default : cout << “Unknown “; } // end of switch
36
Nested switch Statements
Switch statements may be nested. For example: int count; switch ( count ) { case 1 : switch ( target ) { // a nested switch case 0 : cout << “target is zero” << endl; break; case 1 : cout << “target is one” << endl; } // end of nested switch case 2 : . case 3 : } // end of first switch
37
while Loop Another loop provided in C/C++ is the while.
Its general form is: while ( expression ) statement; OR while ( expression ) { statement sequence } As long as the expression evaluates to true the statement or statement sequence is executed. If the expression is initially false, the statement or statement sequence is never executed.
38
while Loop Example This program displays all the ASCII characters between 32 ( a space ) and 255. #include <iostream> using namespace std; int main() { unsigned char ch; ch = 32; while( ch ) { cout << ch; ch++; } // end of while return 0; } // end of main
39
while Loop Example This program displays a series of periods (.). The number of periods displayed depends on the value entered by the user. #include <iostream> using namespace std; int main() { int len; cout << “Enter length ( 1 to 79 ): “; cin >> len; while( len > 0 && len < 80 ) { cout << ‘.’; len--; } // end of while return 0; } // end of main
40
while Loop Example What is wrong, if anything, with this program?
#include <iostream> using namespace std; int main() { int len; cout << “Enter length ( 1 to 79 ): “; cin >> len; while( len > 0 && len < 80 ); { cout << ‘.’; len--; } // end of while return 0; } // end of main
41
The do-while Loop The do-while loop has the same general syntax as the while loop except that it tests its condition at the bottom of the loop. This means that the program statements in the loop body will ALWAYS be executed at least one time. The do-while loop is like the while loop in that you may not know at design time how many times you will need to loop. The general form is: do { statements; } while ( expression ); As long as the expression evaluates to true the statements in the loop are executed.
42
do-while Loop Example This program loops until the number 100 is entered. #include <iostream> using namespace std; int main() { int num; do { cout << “Enter a number (100 to stop): “; cin >> num; } while( num != 100 ); return 0; } // end of main
43
Using a do-while to Process a Menu Selection
#include <iostream> using namespace std; int main() { char choice; do { cout << "Help on:“ << endl; cout << " 1. if“ << endl; cout << " 2. switch“ << endl; cout << " 3. while“ << endl; cout << " 4. do-while“ << endl; cout << " 5. for“ << endl << endl; cout << "Choose one: "; cin >> choice; } while( choice < '1' || choice > '5' ); cout << endl; switch( choice ) { case '1' : cout << "The if:“ << endl; cout << "if(condition) statement;“ << endl; cout << "else statement;“ << endl; break;
44
Using a do-while to Process a Menu Selection
case '2' : cout << "The switch:“ << endl; cout << "switch(expression) {“ << endl; cout << " case constant:“ << endl; cout << " statement sequence“ << endl; cout << " break;“ << endl; cout << " // ...“ << endl; cout << "}“ << endl; break; case '3' : cout << "The while:“ << endl; cout << "while(condition) statement;“ << endl; case '4' : cout << "The do-while:“ << endl; cout << "do {“ << endl; cout << " statement;“ << endl; cout << "} while (condition);“ << endl; case '5' : cout << "The for:“ << endl; cout << "for(init; condition; iteration)“ << endl; cout << " statement;“ << endl; } // end of switch return 0; } // end of main
45
Sample Output Help on: 1. if 2. switch 3. while 4. do-while 5. for
Choose one: 4 The do-while: do { statement; } while ( condition );
46
Using continue You can force an early iteration of a loop, bypassing the loop’s normal control structure, by using the continue statement. The continue statement forces the next iteration of the loop to take place, skipping any statements between itself and the conditional expression that controls the loop. For example: int x; for( . . .; . . .; ) { statement1; if( some-condition ) continue; statement2; statement3; } If the continue statement is executed, statements 2 and 3 are skipped that time through the loop. The test is then made to determine if the loop is to repeat or not.
47
Using continue Here is an example of the using the continue statement:
#include <iostream> using namespace std; int main() { int x; for( x = 0; x <= 100; x++ ) { if( x % 2 ) continue; cout << x << ‘ ‘; } return 0; The program above displays the even numbers from 0 to 100.
48
Using break to Exit Loops
Executing a break statement in a loop causes the loop to be immediately exited/terminated and control is given to the first statement following the loop. For example: #include <iostream> using namespace std; int main() { int t; for( t = 0; t < 100; t++ ) { if( t == 10 ) break; cout << t << ‘ ‘; } return 0;
49
Using break to Exit Loops
#include <iostream> using namespace std; int main() { int t, count; for( t = 0; t < 100; t++ ) { count = 1; for( ; ; ) { cout << count << ‘ ‘; count++; if( count == 10 ) break; } cout << endl; return 0;
50
Nested Loops This program finds all the prime numbers from 2 to 1000.
#include <iostream> using namespace std; int main() { int i, j; for( i = 2; i < 1000; i++ ) { for( j = 2; j <= (i / j ); j++ ) if( !(i % j ) ) break; if( j > (i / j) ) cout << i << “ is prime” << endl; } return 0; This program finds all the prime numbers from 2 to 1000.
51
The goto Statement Does Have its Place
The use of the goto statement, which represents an unconditional branch) has been discouraged for years. The C/C++ language does provide a goto statement. However, there are no programming situations that require the use of the goto statement. Its use is for very special logic situations in a program. The goto statement requires a label which is any valid identifier followed by a colon ( : ). This label MUST be located in the same function as the goto statement that uses it. You CANNOT use a goto statement in any of your programs. It will cost you 200 points.
52
The goto Statement Does Have its Place
void SomeFunction() { for( ) { for( ) { while( ) { if( ) { cout << “Error in program. << endl; goto getout; } } } } getout: } // end of SomeFunction()
53
Happy Trails!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.