4 Control Statements.

Slides:



Advertisements
Similar presentations
More on Algorithms and Problem Solving
Advertisements

3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 Control structures  Algorithm & flowchart  If statements  While statements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 3 - Structured Program Development
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Structured Program Development in C
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
The University of Texas – Pan American
Control Structures Session 03 Mata kuliah: M0874 – Programming II Tahun: 2010.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
1 CSCE 1030 Computer Science 1 Control Statements in Java.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
C Lecture Notes 1 Structured Program Development.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
1 C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved. 4.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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,
Chapter 04 Control Statements: Part II. OBJECTIVES In this part you will learn: if…else Double-Selection Statement. while Repetition Statement.
1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.
Chapter 05 (Part III) Control Statements: Part II.
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Lecture 4: C/C++ Control Structures Computer Programming Control Structures Lecture No. 4.
Structured Program Development Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2005 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
 2007 Pearson Education, Inc. All rights reserved C Program Control.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Branching statements.
Chapter 4 – C Program Control
Lecture 7: Repeating a Known Number of Times
Chapter 2.1 Control Structures (Selection)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Control Statements Kingdom of Saudi Arabia
JavaScript: Control Statements.
MSIS 655 Advanced Business Applications Programming
Structured Program
Chapter 3 - Structured Program Development
3 Control Statements:.
Chapter 3 - Structured Program Development
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
Control Statements Paritosh Srivastava.
Structural Program Development: If, If-Else
Control Statements:.
Presentation transcript:

4 Control Statements

RECAP We have learnt: Variables and Data Types Relational Operators Declaration and initialization int, char, double, float, long, short, strings Size and ranges of data types Scope of variables, global and local variables Limited to the block where they are declared Constants using #define and const Relational Operators AND, OR, NOT, &&, ||,!

RECAP We have learnt: Compound assignment Increase / Decrease ++ -- +=, -=, *=, /=, %= Value += increase Value = Value + increase Value -= increase Value = Value - increase Increase / Decrease ++ -- C++; C+=1; C=C+1 Can be used both as prefix or suffix

RECAP We have learnt: Creating functions Calling functions Passing arguments Functions have prototypes (or signatures) that indicate to both the compiler and the programmer how to use the function

RECAP We have learnt: Decision Making using if and if…else selection statements to choose among alternative actions Compound statements or blocks A block can be placed anywhere a single statement can be placed Nested If else Dangling else, else is associated with the last if

OBJECTIVES In this class you will learn: Basic problem-solving techniques. To use the while repetition statement to execute statements in a program repeatedly To use the for repetition statement To use Do-While statements More functions

Introduction Before writing a program Have a thorough understanding of problem Carefully plan your approach for solving it While writing a program Know what “building blocks” are available Uptill now we have been focusing on the building blocks Use good programming principles

Algorithms Any solvable computing problem can be solved by the execution of a series of actions in a specific order Algorithms are the procedure for solving a problem in terms of The actions to execute The order in which these actions execute Program control Specifies the order in which actions execute in a program This is performed in C++ through control statements

Pseudocode Pseudocode Artificial, informal language used to develop algorithms Used to think out program before coding Easy to convert into C++ program Similar to everyday English Only executable statements No need to declare variables Not executed on computers

Control Structures Normal statements in a program Transfer of control Sequential execution Statements executed in sequential order Transfer of control some statements allow a programmer to specify that the next statement executed is not the next one in sequence Structured programming Eliminated goto statements Clearer, easier to debug Only three control structures in C++ Sequence structure Programs executed sequentially by default Selection structures if, if…else, switch Repetition structures while, do…while, for

Selection statements Three types of selection statements if if…else Single selection statement if…else Double selection statement Selects between two different actions Switch statement Multiple selection statement Selects between many different actions

Conditional Operator ?: Closely related to if…else statements Three operands First operand is a condition Second operand is the value of the entire expression if the condition is true Third operand is the value of the entire expression if the condition is false cout << ( grade >= 60 ? "Passed" : "Failed" ); Values in the conditional expression can also be actions to execute grade >= 60 ? cout << "Passed" : cout << "Failed"; Meaning: If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed"

4.6 if…else Double-Selection Statement (Cont.) Ternary conditional operator (?:) Three arguments (condition, value if true, value if false) Code could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); Condition Value if true Value if false

Repetition statements Three types of repetition statements in C++ Enable programs to perform an operation repeatedly as long as a condition is true While Loop Performs the actions zero or more times For Loop Performs the actions in the body zero or more times Do…While Loop Performs the actions in the body at least once

Repetition statements Counter-controlled repetition requires: Name of a control variable (loop counter) Initial value of the control variable Loop-continuation condition that tests for the final value of the control variable Increment/decrement of control variable at each iteration

Shopping trip example While there are more items on my shopping list Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false

Shopping trip example While there are more items on my shopping list Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true

Shopping trip example While there are more items on my shopping list Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true The action will be performed repeatedly while the condition is true This action constitutes the body of the while loop It can be a single statement or a block {}

Shopping trip example While there are more items on my shopping list Purchase next item and cross it off my list Condition: While there are more on my list It can be either true or false If it is true The action will be performed repeatedly while the condition is true This action constitutes the body of the while loop It can be a single statement or a block {} Once the condition is false, the loop would no longer be executed and execution will start from the next statement

While statements

Outline Control-variable name is counter with variable initial value 1 fig05_01.cpp (1 of 1) Condition tests for counter’s final value Increment the value in counter While the while loop beings execution, counter is 1 Each repetition of the loop, counter is incremented The loop executes till the counter <= 10 Loop executes 10 times What if we do not increase the counter by 1?

Common Programming Error Floating-point values are approximate, so controlling counting loops with floating-point variables can result in imprecise counter values and inaccurate tests for termination.

While Example code: down-counter.cpp 1: int main() 2: { 3: int counter = 10; // Initialize variable 4: 5: while ( counter > 0 ) // loop continuation condition 6: { 7: cout << counter << " "; 8: counter = counter - 1; // decrease control counter by 1 9: } 10: return 0; 11: } While the while loop beings execution, counter is 10 Each repetition of the loop, the value of counter is reduced by 1 The loop executes till the counter > 0 Loop executes 10 times while ( ++counter <= 10 ) cout << counter << " ";

for Repetition Statement Specifies counter-controlled repetition details in a single line of code

Outline The the condition counter <=10 is checked Increment for counter Condition tests for counter’s final value Control-variable name is counter with initial value 1 Variable counter is declared and initialized on line 11 The the condition counter <=10 is checked Condition is true so goes onto line 12 Then counter ++ is executed, incrementing the counter Loop begins again from line 11 If condition is false, program continues to line 14

for statement header components.

Good Programming Practice Using the final value in the condition of a while or for statement and using the <= relational operator will help avoid off-by-one errors. For a loop used to print the values 1 to 10, for example, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which is an off-by-one error) or counter < 11 (which is nevertheless correct). Many programmers prefer so-called zero-based counting, in which, to count 10 times through the loop, counter would be initialized to zero and the loop-continuation test would be counter < 10.

for Repetition Statement (Cont.) General form of the for statement for ( initialization; loopContinuationCondition; increment ) statement; Can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } If the control variable is declared in the initialization expression It will be unknown outside the for statement

Common Programming Error When the control variable of a for statement is declared in the initialization section of the for statement header, using the control variable after the body of the statement is a compilation error.

Good Programming Practice Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they should execute only once, like initialization statements) or in the loop body (if they should execute once per repetition, like incrementing or decrementing statements).

for Repetition Statement (Cont.) The initialization and increment expressions can be comma-separated lists of expressions These commas are comma operators Comma operator has the lowest precedence of all operators Expressions are evaluated from left to right Value and type of entire list are value and type of the rightmost expressions

Common Programming Error Using commas instead of the two required semicolons in a for header is a syntax error.

Common Programming Error Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for statement an empty statement. This is usually a logic error.

Software Engineering Observation Placing a semicolon immediately after a for header is sometimes used to create a so-called delay loop. Such a for loop with an empty body still loops the indicated number of times, doing nothing other than the counting. For example, you might use a delay loop to slow down a program that is producing outputs on the screen too quickly for you to read them. Be careful though, because such a time delay will vary among systems with different processor speeds.

Error-Prevention Tip Although the value of the control variable can be changed in the body of a for statement, avoid doing so, because this practice can lead to subtle logic errors.

Examples Using the for Statement for statement examples Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) Vary control variable from 100 to 1 in increments of -1 for ( int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in steps of 7 for ( int i = 7; i <= 77; i += 7 ) Vary control variable from 20 to 2 in steps of -2 for ( int i = 20; i >= 2; i -= 2 ) Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 for ( int i = 2; i <= 20; i += 3 ) Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for ( int i = 99; i >= 0; i -= 11 )

Common Programming Error 5.6 Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as incorrectly using i <= 1 instead of i >= 1 in a loop counting down to 1) is usually a logic error that yields incorrect results when the program runs.

Outline Vary number from 2 to 20 in steps of 2 Add the current value of number to total

do…while Repetition Statement do…while statement Similar to while statement Tests loop-continuation after performing body of loop Loop body always executes at least once

Good Programming Practice Always including braces in a do...while statement helps eliminate ambiguity between the while statement and the do...while statement containing one statement.

Outline Declare and initialize control variable counter do…while loop displays counter’s value before testing for counter’s final value

break and continue Statements break/continue statements Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do…while or switch statements continue statement Skips remaining statements in loop body Proceeds to increment and condition test in for loops Proceeds to condition test in while/do…while loops Then performs next iteration (if not terminating) Used in while, for or do…while statements

Exit for statement (with a break) when count equals 5 Outline Loop 10 times Exit for statement (with a break) when count equals 5

Skip line 14 and proceed to line 9 when count equals 5 Outline Loop 10 times Skip line 14 and proceed to line 9 when count equals 5

Good Programming Practice Some programmers feel that break and continue violate structured programming. The effects of these statements can be achieved by structured programming techniques we soon will learn, so these programmers do not use break and continue. Most programmers consider the use of break in switch statements acceptable.

Performance Tip The break and continue statements, when used properly, perform faster than do the corresponding structured techniques.

Factorial Program #include <iostream> using namespace std; int Factorial (int); int main() { int maximum; // Maximum number int counter = 0; // initialize counter cout << " Enter max number for factorial "<< endl; cin >> maximum; while (counter <= maximum) cout << "Factorial of "<< counter cout << " = " << Factorial(counter)<<endl; counter++; } return 0;

Factorial Program int Factorial(int number) { int temp = 1; int count = 0; while (count<number) count = count + 1; temp = temp * count; } return temp;

Factorial Program Enter max number for factorial 18 Factorial of 0 = 1

Nested Loops int main() { int j,k,limit; cout << “Number for multiply table:”<<endl; cin >> limit; for(j=1; j <= limit; j++) { for(k=1; k <= j; k++) { cout << k*j << " "; } cout << endl; return 0; Number for multiply table: 6 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36