CHAPTER 4 CONTROL STRUCTURES
|
|
- Lisa McCormick
- 5 years ago
- Views:
Transcription
1 CHAPTER 4 CONTROL STRUCTURES 1
2 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
3 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
4 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
5 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 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
6 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
7 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
8 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
9 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
10 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
11 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
12 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
13 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
14 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
15 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
16 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
17 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
18 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
19 * 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
20 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
21 Output Enter number (0 to end): You entered: Enter number (0 to end): You entered: 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
22 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
23 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
24 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
25 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
26 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
27 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
28 Exercises 1. Write an if statement that prints YES if a variable age is greater than 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 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 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
29 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
CHAPTER 4 CONTROL STRUCTURES
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,
More informationUniversity of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.
University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Fifth week Control Structures A program is usually not limited to a linear sequence of instructions. During its process
More information8. Control statements
8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon
More informationUniversity of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.
University of Technology Laser & Optoelectronics Engineering Department C++ Lab Sixth week Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled
More informationThe following expression causes a divide by zero error:
Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct
More informationCHAPTER : 9 FLOW OF CONTROL
CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language
More informationChapter 8 Statement-Level Control Structure
Chapter 8 Statement-Level Control Structure To make programs more flexible and powerful: Some means of selecting among alternative control flow paths. Selection statement (conditional statements) Unconditional
More informationFlow Control. CSC215 Lecture
Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements
More informationProgramming with C++ Language
Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language
More informationDecision Making -Branching. Class Incharge: S. Sasirekha
Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the
More informationKingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS
Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Objectives By the end of this section you should be able to:
More informationCHAPTER 9 FLOW OF CONTROL
CHAPTER 9 FLOW OF CONTROL FLOW CONTROL In a program statement may be executed sequentially, selectively or iteratively. Every program language provides constructs to support sequence, selection or iteration.
More informationCHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++
CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,
More informationMODULE 2: Branching and Looping
MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,
More informationLECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE
Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com
More informationCHAPTER 5 FLOW OF CONTROL
CHAPTER 5 FLOW OF CONTROL PROGRAMMING CONSTRUCTS - In a program, statements may be executed sequentially, selectively or iteratively. - Every programming language provides constructs to support sequence,
More informationModule3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement
Module3 Program Control Statements CRITICAL SKILLS 3.1 Know the complete form of the if statement 3.2 Use the switch statement 3.3 Know the complete form of the for loop 3.4 Use the while loop 3.5 Use
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationINTRODUCTION TO PROGRAMMING
FIRST SEMESTER INTRODUCTION TO PROGRAMMING COMPUTER SIMULATION LAB DEPARTMENT OF ELECTRICAL ENGINEERING Prepared By: Checked By: Approved By Engr. Najeeb Saif Engr. M.Nasim Kha Dr.Noman Jafri Lecturer
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More informationITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University
ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 08: Control Statements Readings: Chapter 6 Control Statements and Their Types A control
More informationInformation Science 1
Topics covered Information Science 1 Fundamental Programming Constructs (1) Week 11 Terms and concepts from Week 10 Flow of control and conditional statements Selection structures if statement switch statement
More informationInformation Science 1
Information Science 1 Fundamental Programming Constructs (1) Week 11 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 10 l Flow of control
More informationSELECTION STATEMENTS:
UNIT-2 STATEMENTS A statement is a part of your program that can be executed. That is, a statement specifies an action. Statements generally contain expressions and end with a semicolon. Statements that
More informationWhy Is Repetition Needed?
Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable
More informationThere are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.
Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate
More informationAll copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva
All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..
More informationChapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationBranching is deciding what actions to take and Looping is deciding how many times to take a certain action.
3.0 Control Statements in C Statements The statements of a C program control the flow of program execution. A statement is a command given to the computer that instructs the computer to take a specific
More informationChapter 3. More Flow of Control
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-2 Flow Of Control Flow of control refers to the
More informationScore score < score < score < 65 Score < 50
What if we need to write a code segment to assign letter grades based on exam scores according to the following rules. Write this using if-only. How to use if-else correctly in this example? score Score
More informationProgramming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester
Programming Language Control Structures: Selection (switch) Eng. Anis Nazer First Semester 2018-2019 Multiple selection choose one of two things if/else choose one from many things multiple selection using
More informationDELHI PUBLIC SCHOOL TAPI
Loops Chapter-1 There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed
More informationChapter 4 - Notes Control Structures I (Selection)
Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by
More informationC++ PROGRAMMING SKILLS Part 2 Programming Structures
C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure
More informationManual. Subject Code: CS593. Computer Science and Engineering
Programming Practices using C++ Laboratory Manual Subject Code: CS593 Computer Science and Engineering B-Tech (5 th Semester) Structure of a program Probably the best way to start learning a programming
More informationControl Statements. If Statement if statement tests a particular condition
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
More informationUnit 3 Decision making, Looping and Arrays
Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.
More informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control
More informationPDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs
PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A
More informationLESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.
LESSON 3 Flow Control In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script. In this chapter we ll look at two types of flow control:
More informationINTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from
INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue
More informationIntroduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
More information5. Control Statements
5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements
More informationChapter 2: Functions and Control Structures
Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow
More informationChapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.
More informationIn this chapter you will learn:
1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2
More informationProgramming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3
Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions
More informationControl Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.
EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationRepetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
More informationCondition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
More informationLooping statement While loop
Looping statement It is also called a Repetitive control structure. Sometimes we require a set of statements to be executed a number of times by changing the value of one or more variables each time to
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection) Control Structures A computer can proceed: In sequence Selectively (branch) - making
More informationSlide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto
CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style
More informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationSTUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode
STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level
More informationProgramming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029
Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities
More informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and
More informationChapter 2. C++ Basics
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables
More informationControl Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way
Control Structures In Text: Chapter 8 1 Control structures Selection One-way Two-way Multi-way Iteration Counter-controlled Logically-controlled Gotos Guarded statements Outline Chapter 8: Control Structures
More informationChapter 4. Flow of Control
Chapter 4. Flow of Control Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr Sequential flow of control
More informationAdd Subtract Multiply Divide
ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient
More informationC++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures
More information3 The L oop Control Structure
3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement
More informationLecture 10. Daily Puzzle
Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch. Daily
More informationSuperior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop
Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.5 for loop and do-while loop Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:
More informationx = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0
6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2
More informationLogical Operators and if/else statement. If Statement. If/Else (4.3)
Logical Operators and if/ statement 1 If Statement We may want to execute some code if an expression is true, and execute some other code when the expression is false. This can be done with two if statements
More informationDECISION CONTROL AND LOOPING STATEMENTS
DECISION CONTROL AND LOOPING STATEMENTS DECISION CONTROL STATEMENTS Decision control statements are used to alter the flow of a sequence of instructions. These statements help to jump from one part of
More informationIntroduction to the Java Basics: Control Flow Statements
Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationRepetition CSC 121 Fall 2014 Howard Rosenthal
Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationSubject: PIC Chapter 2.
02 Decision making 2.1 Decision making and branching if statement (if, if-, -if ladder, nested if-) Switch case statement, break statement. (14M) 2.2 Decision making and looping while, do, do-while statements
More informationUnit 7. 'while' Loops
1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationOther Loop Options EXAMPLE
C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you
More informationComputer Programming : C++
The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program
More informationAdvanced Computer Programming
Hazırlayan Yard. Doç. Dr. Mehmet Fidan WHILE, DO-WHILE and FOR LOOPS Loops are used for executing code blocks repeatedly. Decision of continuing loop is given by boolean expression. If boolean expression
More informationChapter 5: Control Structures
Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18
More informationC++ Programming Lecture 1 Software Engineering Group
C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in
More informationChapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware
Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements Evolution: - FORTRAN I control statements were based directly on IBM 704 hardware - Much research and argument
More informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationCompilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors
First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More informationChapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights
More informationDecision making with if Statement : - Control Statements. Introduction: -
Control Statements Introduction: - Any C program if you consider, the set of statements are normally executed sequentially in the order in which they are written, and such programs have sequential structure
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More information3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)
Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationChapter 3 Problem Solving and the Computer
Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationLoops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
More informationLaboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++
Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It
More informationLab # 02. Basic Elements of C++ _ Part1
Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special
More information