Chapter 4 Program Control Statements

Slides:



Advertisements
Similar presentations
Control Structures Corresponds with Chapters 3 and 4.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 6 Control Structures.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Objectives You should be able to describe:
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CPS120: Introduction to Computer Science Decision Making in Programs.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
The setw Manipulator The setw manipulator causes the number (or string) that follows it in the stream to be printed within a field n characters wide, where.
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
Chapter 2.2 Control Structures (Iteration)
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 2.2 Control Structures (Iteration)
Computing Fundamentals
Control Structures Part 1
2.6 The if/else Selection Structure
Objectives You should be able to describe: The while Statement
Control Statements Paritosh Srivastava.
CSC215 Lecture Control Flow.
Presentation transcript:

Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

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

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

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.

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).

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; }

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.

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!

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 )

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;

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;

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.

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

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.

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;

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.

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?

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?

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?

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.

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;

The for Loop Example Output: 1 1 2 1.41421 3 1.73205 4 2 5 2.23607 6 2.44949 7 2.64575 8 2.82843 9 3 10 3.16228

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;

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(); }

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.

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.

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 }

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.

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.

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;

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;

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

The break Statement is Optional Output: i is less than 5 i is less than 10 i is 10 or more

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;

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

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

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.

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

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

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

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.

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

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;

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

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 );

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.

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.

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;

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;

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.

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.

The goto Statement Does Have its Place void SomeFunction() { for( . . . ) { for( . . . ) { while( . . . ) { if( . . . ) { cout << “Error in program. << endl; goto getout; } . . . . } . . } . . } getout: } // end of SomeFunction()

Happy Trails!