CHAPTER 4 CONTROL STRUCTURES

Similar documents
CHAPTER 4 CONTROL STRUCTURES

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

8. Control statements

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

The following expression causes a divide by zero error:

CHAPTER : 9 FLOW OF CONTROL

Chapter 8 Statement-Level Control Structure

Flow Control. CSC215 Lecture

Programming with C++ Language

Decision Making -Branching. Class Incharge: S. Sasirekha

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

CHAPTER 9 FLOW OF CONTROL

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

MODULE 2: Branching and Looping

C++ Programming: From Problem Analysis to Program Design, Third Edition

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

CHAPTER 5 FLOW OF CONTROL

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

INTRODUCTION TO PROGRAMMING

REPETITION CONTROL STRUCTURE LOGO

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Information Science 1

Information Science 1

SELECTION STATEMENTS:

Why Is Repetition Needed?

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

Chapter 3. More Flow of Control

Score score < score < score < 65 Score < 50

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

DELHI PUBLIC SCHOOL TAPI

Chapter 4 - Notes Control Structures I (Selection)

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Manual. Subject Code: CS593. Computer Science and Engineering

Control Statements. If Statement if statement tests a particular condition

Unit 3 Decision making, Looping and Arrays

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Accelerating Information Technology Innovation

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Introduction. C provides two styles of flow control:

5. Control Statements

Chapter 2: Functions and Control Structures

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

In this chapter you will learn:

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Looping statement While loop

C++ Programming: From Problem Analysis to Program Design, Third Edition

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Chapter 4. Flow of Control

Add Subtract Multiply Divide

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

3 The L oop Control Structure

Lecture 10. Daily Puzzle

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Logical Operators and if/else statement. If Statement. If/Else (4.3)

DECISION CONTROL AND LOOPING STATEMENTS

Introduction to the Java Basics: Control Flow Statements

Loops. CSE 114, Computer Science 1 Stony Brook University

Repetition CSC 121 Fall 2014 Howard Rosenthal

Subject: PIC Chapter 2.

Unit 7. 'while' Loops

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Other Loop Options EXAMPLE

Computer Programming : C++

Advanced Computer Programming

Chapter 5: Control Structures

C++ Programming Lecture 1 Software Engineering Group

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

C: How to Program. Week /Mar/05

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Decision making with if Statement : - Control Statements. Introduction: -

STUDENT LESSON A12 Iterations

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 3 Problem Solving and the Computer

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Loops / Repetition Statements

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Lab # 02. Basic Elements of C++ _ Part1

Transcription:

CHAPTER 4 CONTROL STRUCTURES 1

Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may deviate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. With the introduction of control structures we are going to have to introduce a new concept: the compound statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: : statement1; statement2; statement3; Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ().But in the case that we want the statement to be a compound statement it must be enclosed between braces (), forming a block. Only three control structures needed Three control structures Sequence structure Programs executed sequentially by default Selection structures if, if, switch Repetition structures while, do while, for 2

Selection Structures (or) Conditional Structures (or) Branching Structures 1. if structure If keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if(condition) statement; where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. Condition YES Statement NO Continue For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if(x == 100) cout << "x is 100"; 3

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces : if(x == 100) cout<<"x is "; cout<<x; 2. if statement We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword. Its form used in conjunction with if is: if(condition) statement1; statement2; Statement2 NO Condition YES Statement1 Continue 4

For example: if(x==100) cout<<"x is 100"; cout< <"x is not 100"; prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. 3. Multi-w ay if statements (or) if if ladder When a series of many conditions have to be checked we may use the ladder if statement which takes the following general form if(condition-1) statement-1; if(condition-2) statement-2; if(condition-3) statement-3; if(condition-n) statement-n; default statement; statement-x; This construct is known as if construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement x (skipping the rest of the ladder. When all the condition becomes false, the final containing the default statement will be executed. 5

NO Condition-1 YES Statement-1 Condition-2 YES Statement-2 NO Condition-3 YES Statement-3 NO Condition-n YES Statement-n NO Default Statement Statement-x 6

The if + structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero): if(x > 0) cout<<"x is positive"; if(x<0) cout<<"x is negative"; cout<<"x is 0"; Example program using if ladder to grade the student according to the following rules. Marks Grade >=90 A >=80 B >=70 C >=60 D <60 F 7

Example: Algorithm steps If student s grade is greater than or equal to 90 Print A If student s grade is greater than or equal to 80 Print B If student s grade is greater than or equal to 70 Print C If student s grade is greater than or equal to 60 Print D Print F C ++ Program Steps if(studentg rade>= 90) cout<<"a"; if(studentgrade>= 80) cout<<"b"; if(studentgrade>=70) cout<<"c"; if(studentgrade >= 60) cout<<"d"; cout<<"f"; 8

4. Nested if Statements if and if- statements can be nested, i.e. used inside another if or statement Every corresponds to its closest preceding if if(expression) if(e xpression) statement; statement; statement; Example: to find the given two numbers are equal, or greater than other if(first == second) cout<<"these two numbers are equal."; if(first > second) cout<<"the first number is bigger."; cout<<"the second is bigger."; 9

5. The selective structure: switch case In the last Lesson it was shown how a choice could be made from more than two possibilities by using if- ladder statements. However a less unwieldy method in some cases is to use a switch statement. The general form of a switch case statement is: switch(selector) case label1 : group of statement1 ; case label2 : group of statement2 ;... case labeln : group of statementn ; default : statementd; // optional The selector may be an integer or character variable or an expression that evaluates to an integer or a character. The selector is evaluated and the value compared with each of the case labels. The case labels must have the same type as the selector and they must all be different. Switch evaluates selector and checks if it is equivalent to label1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure If the value of the selector cannot be matched with any of the case labels then the statement associated with default is 10

executed. The default is optional but it should only be left out if it is certain that the selector will always take the value of one of the case labels. Note that the statement associated with a case label can be a single statement or a sequence of statements (without being enclosed in curly brackets). 11

For example The following switch statement will set the variable grade to the character A, B or C depending on whether the variable i has the value 1, 2, or 3. If i has none of the values 1, 2, or 3 then a warning message is output. switch(i) case 1: grade = 'A'; case 2: grade = 'B'; case 3: grade = 'c'; default: cout<<i<<"not in range"; The following statement writes out the day of the week depending on the value of an integer variable day. It assumes that day 1 is Sunday. switch(day) case 1: cout<<"sunday"; case 2: cout<<"monday"; case 3: cout<<"tuesday"; 12

case 4: cout<<"wednesday"; case 5: cout<<"thursday"; case 6: cout<<"friday"; case 7: cout<<" Saturday"; default: cout<<" Not an allowable day number"; If it has already been ensured that day takes a value between 1 and 7 then the default case may be missed out. It is allowable to associate several case labels with one statement. For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes unnecessary to include braces surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For exam ple if the above example is amended to write out whether day is a weekday or is part of the weekend: 13

switch(day) case 1: case 7: cout<<"this is a weekend day"; case 2: case 3: case 4: case 5: case 6: cout<<" This is a weekday"; default: cout<<" Not a legal day"; Switch statement something similar to what we did at the beginning of this section with if ladder. Both of the following code fragments have the same behavior: switch example if- equivalent switch (x) if(x == 1) case 1: cout<<"x is 1"; cout<<"x is 1"; if(x == 2) case 2: cout<<"x is 2"; cout<<"x is 2"; default: cout<<"value of x unknown"; cout<<"value of x unknown"; 14

For example the weekday/weekend example above could be written: if(day>=1&&day<=7) if(day==1 day==7) cout<<"this is a weekend day"; cout<<"this is a weekday"; cout<< Not a legal day"; However the first example becomes very tedious- there are eight alternatives! Consider the following: if( day==1) cout<<"sunday"; if(day==2) cout<<"monday"; if(day==3) cout<<"tuesday";.. if(day==7) cout<<"saturday"; cout<<"not a legal day"; Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables s labels (for example case n: where n is a variable) or ranges (case (1..3):) becau se they are not valid C++ constants. If you need to check ranges or values that are not constants, use a concatenation of if and if statements. 15

Common Programming Error Forgetting a break statement when one is needed in a switch statement is a logic error. Omitting the space between the word case and the integral value being tested in a switch statement can cause a logic error. For example, writing case3: instead of writing case 3: simply creates an unused label. Specifying an expression including variables(e.g.,a + b) in a switch statement s case label is a syntax error. Good Programming Pra ctice In a switch statement that lists the default clause last, the default clause does not require a break statement. Some programmers include this break for clarity and for symmetry with other cases. Repetition structures (or) Iteration Structures (or) Looping Structures Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. There are 3 types of loops in C++ 1. while loops 2. do-while loops 3. for loops 1. The while loo p Its format is: while(condition) statement; This while loop executes as long as the given logical expression between parentheses is true. When condition is false, execution continues with the statement following the loop block. 16

The condition is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all, and its functionality is simply to repeat statement while the condition set in expression is true. Two or more number of statements to be repeated then encloses braces. Otherwise no need to enclose brace for single statement repetition. 17

For example, we are going to make a program to countdown using a while-loop: Example Program // custom countdown using while #include<iostream> using namespace std; int main() int n; cout<<"enter the starting number"; cin>>n; while(n>0) cout<<n<<","; --n; cout<<"fire!\n"; return(0); Output Enter the starting number 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3) 18

* condition is false: ignore statement and continue after it (to step 5) 3. Execute statement: cout<<n<<","; --n; (prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. Continue the program right after the block: print FIRE! and end program. When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end. Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers. Note: placing semicolon after the while statement, i.e while(); will produce a logical error. 2. The do-while loop Its format is: do statement; while(condition); Its functionality is exactly the same as the while loops, but guarantees at least one execution of the body 19

Two or more number of statements to be repeated then encloses braces. Otherwise no need to enclose brace for single statement repetition. For example, the following example program echoes any number you enter until you enter 0. Example Program // number echoer #include<iostream> using namespace std; int main() unsigned long n; do cout<<"enter number (0 to end):"; cin>>n; cout<<"you entered:"<<n<<"\n"; while(n!=0); return(0); 20

Output Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0 The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever. Note: Forget to place semicolon after the while statement, i.e while() will produce a syntax error. 3. The for loop Its format is: for(initialization;condition;increment) statement; and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. It works in the following way: 1. Initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 21

2. Condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. Statement is executed. As usual, it can be either a single statement or a block enclosed in braces. 4. Finally, whatever is specified in the increase field is executed and the loop gets back to step 2. Comparison of for and while loops 22

Here is an example of countdown using for loop: Example Program // countdown using a for loop #include<iostream> using namespace std; int main() for(int n=10;n>0;n--) cout<<n<<","; cout<<"fire!\n"; return(0); Output 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: 23

for(;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before). Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop: for(n=0,i=100;n!=i;n++,i-- ) // whatever here... This loop will execute for 50 times if either n or i are modified within the loop: n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50. 24

Nested Loops You can nest loops of any kind inside another to any depth. Example Program //Printing a Triangle #include<iostream> using namespace std; int main() for(int i=1;i<=5;i++) for(int j=1;j<=i;j++) cout<<"*"; cout<<"\n"; return(0); Output * ** *** **** ***** Jumping statements 1. The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): E xample Program // break loop example # include<iostream> using namespace std; 25

int main() int n; for(n=10; n>0; n--) cout<<n<< ", "; if(n==3) cout<<"countdown aborted!"; return(0); Output 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! 2. The con tinue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: Exam ple Program //continue loop example #include<iostream> using namespace std; int main() for(int n=10; n>0; n--) if(n==5) continue; cout<<n<< ", "; cout<<"fire!\n"; 26

return(0); Output 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! 3. The goto sta tement Goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:) Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto: Example Program //goto loop example #include<iostream> using namespace std; int main() int n=10; loop: cout<<n<<","; n--; if(n>0) goto loop; cout<<"fire!\n"; return(0); O utput 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! 27

Exercises 1. Write an if statement that prints YES if a variable age is greater than 21. - 2 Marks 2. Write an if statement that displays YES if a variable age is greater than 21, and displays NO otherwise - 2 Marks 3. Write a for loop that displays the number from 100 to 110. Thank You - 2 Marks 4. Write a while loop that displays the number from 500 to 520. - 2 Marks 5. At least how many times the loop body is executed in a do while loop? - 1 Mark 6. Write a switch statement that prints YES if a variable ch is y, prints NO if ch is n, and prints UNKNOWN otherwise - 2 Marks 7. Write a program to find the biggest among three given numbers - 2 Marks 8. Write a program to find the given number is odd or even - 2 Marks 9. Write a program to find the factorial of a given number - 2 Marks that displays the following set of by using for loop 10. Write a for loop numbers - 2 Marks 0 10 20 30 40 50 60 70 80 90 100 11. Write a program to find sum, difference, multiply and division of given two numbers using switch case selective structure - 3 Marks 12. An electricity board charges the following rates to domestic users to discourage large consumption of energy: For the first 100 units 10 Paisa per unit For next 200 units 20 Paisa per unit Beyond 300 units 30 Paisa per unit If the total cost is more than 10 OMR then an additional surcharge of 15% is added. Write a program to print the consumed unit and total amount for the consumed unit. - 3 Marks 28

13. Write a Program to find the GCD of two numbers by using while loop structure - 2 Marks 14. Write a program to calculate and Print the Following table by using for loop structure - 3 Marks 1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 10*2=20 29