REPETITION CONTROL STRUCTURE LOGO
|
|
- Matthew Burke
- 6 years ago
- Views:
Transcription
1 CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1
2 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2
3 Introduction It is used when a statement or a block of statements need to be executed several times. Programmers use the repetition structures, referred to more simply as a loop, when they need the computer to repeatedly process one or more program instructions until some condition is met, at which time the repetition structures end. Repetition is also known as iteration or loop. 3
4 Introduction Two types of loop: Pretest loop Evaluation occurs before the instructions within the loop are processed Instruction may never be processed while statement, for statement Posttest loop Evaluation occurs after the instructions within the loop are processed Instructions will be processed at least once do..while statement 4
5 Introduction Repeat sequence of instruction many times (as long as condition is TRUE ) Repetition = iteration = loop Similar function, different names Example You have to create a simple program that will receive 5 integer inputs from user. Sum those 5 inputs and calculate the average. Check out the C++ code with and without looping 5
6 Introduction A program that will receive 5 integer inputs from user and sum those 5 inputs and calculate the average. /* Problem: Sum 5 numbers, calculate the average, display the results */ Is this what you are thinking??? int num1, num2, num3, num4, num5; int sum; float average; cin>>num1>>num2>>num3>>num4>>num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5; cout<<"sum: "<<sum<<"\taverage: "<<average; 6
7 Introduction The correct way by using repetition Solution int num, sum = 0, count = 0; using float average; while(count < 5) looping!!! { cout<<"num "<<(count + 1)<<": "; cin>>num; sum = sum + num; count = count + 1; } average = sum / 5; cout<<"sum: "<<sum<<"\taverage: "<<average; 7
8 Types of Repetition Statement Types of repetition for while do while 8
9 Types of Repetition Structure Types of repetition structure Counter-controlled repetition Number of repetition is fixed (known in advance) e.g. repeat a process 10 times Sentinel-controlled repetition Stop looping whenever a special value is entered e.g. enter -1 to end the loop Flag-controlled repetition When a defined value is matched, it stops looping, else loop will continue e.g. looping will continue 1000 times, however it will stop immediately if the value entered by user matches with ID = 102 9
10 Requirements of Repetition /* example using while loop */ int i = 0; //initialize while(i < 10) { statements; i++; } Loop Body Loop Condition Loop Control Variable (LCV) 10
11 Requirements of Repetition /* example using for loop */ for(i = 0; i < 10; i++) { statements; } Loop Control Variable (LCV) Loop Body Loop Condition 11
12 Requirements of Repetition Loop Control Variable (LCV) A variable whose value determines whether the loop body will be executed or not It has initial value and increment/decrement value Loop Condition If the condition is true, the loop body is executed; if condition is false the loop exits Loop Body A block of statements to be repeated 12
13 Requirements of Repetition Execution of loop body is controlled by 3 operations: Initialization of the LCV Evaluation of LCV in the loop condition Update of the LCV by incrementing (e.g. x++) or decrementing (e.g. x--) 13
14 Requirements of Repetition Increment operator Table 4.1: Increment operator Common Equivalent to statement x++ x = x + 1 x += 1 - x = x + 3? -? x += 5 - x = x + i? 14
15 Requirements of Repetition Decrement operator Table 4.2: Decrement operator Common Equivalent to statement x-- x = x - 1 x -= 1 - x = x - 9? -? x -= 2 -? x -= sum 15
16 Introduction example Let say, you want to display I love C++ 5 times. I love C++ I love C++ I love C++ I love C++ void main() { cout << I love c++!\n ; cout << I love c++!\n ; cout << I love c++!\n ; cout << I love c++!\n ; cout << I love c++!\n ; } I love C++ 16
17 Introduction example The idea of using a loop Pseudocode Begin Repeat output I love C++ End Flow Chart I love C++ QUESTION: HOW DO WE STOP THE LOOP??? 17
18 Introduction example Adding a loop control variable Pseudocode Begin counter = 1 Repeat (if counter <= 5) output I love C++ counter ++ End Variable counter is LCV Flow Chart counter = 1 counter <= 5 F T I love C++ counter ++ 18
19 Introduction loop control variable A LCV controls the number of times the statement or the block of statements is being executed. Flow Chart Pseudocode Begin counter = 1 Repeat (if counter <= 5) output I love C++ counter ++ End Counter = 1 Counter <= 5 F T I love C++ Counter ++ 19
20 Introduction Requirement of a repetition structure Flow Chart Loop body Initialize LCV Counter = 1 Counter <= 5 T Evaluate LCV (loop condition) F I love C++ Counter ++ Update LCV 20
21 Introduction Task associated with loop: Counter to determine number of items. counter = counter + 1 Is done by adding a constant, such as 1 or 2, to the value of a variable. Accumulator to find totals. sum = sum + variable Is done by adding a variable to another variable. 21
22 Introduction Indicator value use to end the loop Indicators Counter control Sentinel control While(counter<=5) sentinel=999; While(number!=sentinel) Counter control sentinel control 22
23 The for loop 23
24 for loop Also called as a counted or indexed for loop The general form of the for statement is: for ([initial statement]; loop condition; [update statement]) statement; The initial statement, loop condition, and update statement are called for loop control statements Items in square brackets ([ ]) are optional. 24
25 for loop for ([initial statement]; loop condition; [update statement]) statement; The for loop executes as follows: 1. The initial statement executes. 2. The loop condition is evaluated. If the loop condition evaluates to true i. Execute the for loop statement. ii. Execute the update statement (the third expression in the parentheses). 3. Repeat Step 2 until the loop condition evaluates to false. The initial statement usually initializes a variable. In C++, for is a reserved word. 25
26 for loop Example 1 Example : Displaying the numbers 1 through 3 initialization condition update for (int count = 1; count <= 3; count = count + 1) cout << count << endl; Result:
27 for loop Example 1 Using for loop to display Welcome to C++. Pseudocode: Start For( set i to 1; i less than or equal to 3; add 1 to i) display welcome to C++ Endfor End 27
28 for loop Example 1 Flowchart Start i = 0 i <= 10 F End T Display welcome to C++ i ++ 28
29 for loop Example 1 29
30 for loop Example 2 Example: to create a program to display backward the first 10 non negative number. 30
31 for loop Exercises Exercise 1: create a program that display the first 10 positive odd integers. 31
32 for loop Exercises Exercise 1 - answer 32
33 for loop Exercises Exercise 2: how many time the following loop processed? for (int count = 6; count < 6; count = count + 1) cout << count << endl; Answer: 33
34 for loop Exercises Exercise 3: how many time the following loop processed? for (int count = 4; count <= 10; count = count + 2) cout << count << endl; Answer: 34
35 for loop Example 3 Example: to calculate and display total of 3 numbers 35
36 for loop Example 3 Pseudocode: Start Initialize total = 0 For(set counter to 1; counter less than or equal to 3; add 1 to counter) input number total = total + number Endfor Display total End 36
37 for loop Example 3 Flowchart Start counter=1, total = 0, for counter <= 3 T Input number F Output total End total = total + number counter = counter
38 for loop Example 3 C++ program segment total = 0; for (int count = 1; count <= 3; count = count + 1) { cin>>number; total = total + number; } cout << total: <<total<<endl; 38
39 for loop Exercises Exercise 4: Suppose j, sum, and num are int variables, and the input values are 26, 34, 61, 4, and -1. What is the output of the code below? cout << "Enter a number : "; cin >> num; for (j = 1; j <= 4; j++) { sum = sum + num; cout << "Enter a number : "; cin >> num; } cout << sum << endl; 39
40 for loop Exercises Exercise 4: answer 40
41 for loop A semicolon at the end of the for statement (just before the body of the loop) is a semantic error. In this case, the action of the for loop is empty. In the for statement, if the loop condition is omitted, it is assumed to be true. In a for statement, you can omit all three statements initial statement, loop condition, and update statement. The following is a legal for loop: 41
42 for loop for (;;) cout << "Hello" << endl; This is an infinite loop, continuously printing the word Hello 42
43 The while loop 43
44 while loop Repeat or loop as long as the condition is true. The general form of the while statement is: while (expression) { statement; } while is a reserved word. Statement can be simple or compound 44
45 while loop while (expression) { statement; } Expression acts as a decision maker and is usually a logical expression Statement is called the body of the loop The parentheses are part of the syntax 45
46 while loop while (expression) { statement; } Expression provides an entry condition statement executes if the expression initially evaluates to true loop condition is then reevaluated statement continues to execute until the expression is no longer true 46
47 while loop Infinite loop continues to execute endlessly can be avoided by including statements in the loop body that assure exit condition will eventually be false 47
48 while loop The general form of while loop flowchart: 48
49 while loop Example: to display the first five positive integers which increment by five. 49
50 while loop Pseudocode: Begin End Initialize i to 0 While i is less than or equal to 20 Display i add 5 to I (update) End while 50
51 while loop Start Enter the while statement i = 0 i <= 20 Expression evaluates to zero False condition End True condition Expression evaluates to a nonzero number Loop Display i i = i + 5 Go back and reevaluate the expression 51
52 while loop Example C++ program segment: 1) Loop Control Variable (LCV) 2) A starting point / Initialization of the LCV i = 0; while ( i <= 20) { cout << i << ; i = i + 5; } 4) Updating the LCV 3) Testing the loop repetition condition 52
53 while loop Various form of while loops: Counter controlled Sentinel controlled Flag controlled 53
54 while loop counter control If you know exactly how many pieces of data need to be read, the while loop becomes a counter-controlled loop. General syntax: 54
55 while loop counter control Counter controlled while loop includes the following: Counter A numeric variable used for counting something Accumulator Numeric variable used for accumulating something Initializing Assign a beginning value to the counter or accumulator; typically 0 Updating Also called incrementing, means adding a number to the values stored in the counter or accumulator 55
56 while loop counter control Example #include <iostream> #include <conio> int main() { int count; count = 1; initializing while (count <= 10) { cout << count << endl; count++; } updating getch(); return 0; } 56
57 while loop counter control Problem: Create a program that displays the word Hello on the screen 10 times. Solution: Psedocode Begin End Initialize lcv to 0 While lcv is less than 10 Display Hello Update lcv End while 57
58 while loop counter control Flowchart Begin Initialize counter = 0 counter < 10 T Hello update counter F End 58
59 while loop counter control Program and output int main() { int count; } count = 0; while (count < 10) { cout << "Hello" << endl; count++; } getch(); return 0; 59
60 while loop counter control Exercise: Write a C++ statement associated to the following flowchart. Begin Initialize counter = 10 counter < 100 F T Display counter Multiplied by 2 Add 10 to counter End 60
61 while loop counter control Program and output int main() { int count; count = 10; while (count < 100) { cout << count * 2 << endl; count += 10; } getch(); return 0; } 61
62 while loop sentinel control A sentinel-controlled while loop uses a special value called sentinel to control the loop. Sentinel value is a special value that indicates the end of a set of data or of a process Sentinel variable is tested in the condition and loop ends when sentinel is encountered 62
63 while loop sentinel control General syntax : 63
64 while loop sentinel control Example #include <iostream> #include <conio> int main() { char answer; cout << "Do you want to quit (Y - yes, N - no) : "; cin >> answer; while (answer!= 'Y') Sentinel value { cout << "Welcome to the program." << endl; cout << "Do you want to quit (Y - Yes, N - No) : "; cin >> answer; } cout << "Bye."; getch(); return 0; } 64
65 while loop sentinel control Output screen 65
66 while loop sentinel control Exercise: to create a program that process the loop as long as user enter an even number 66
67 while loop sentinel control Solution Flowchart Begin Prompt for a number Get a number number % 2 == 0 T Get another number End F 67
68 while loop sentinel control Program int main() { int number; cout << "Enter a number : "; cin >> number; while (number % 2 == 0) { cout << "Enter the next number : "; } cin >> number; } cout <<"You have entered an odd number to terminate << the program."; getch(); return 0; 68
69 while loop sentinel control Output 69
70 while loop flag control A flag-controlled while loop uses a bool variable to control the loop The flag-controlled while loop takes the form: 70
71 Example while loop flag control void main() { bool found = false; char continues; while (!found) { cout << " Program continued..still want to continue" << " the loop? Press Y for yes, N for No"<< endl; cin>>continues; if(continues == Y ) found = false; else found = true; } cout << "Program terminated"; getch(); } 71
72 The do while loop 72
73 do while loop The general form of a do...while statement is: do statement while (expression); The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes again As long as the expression in a do...while statement is true, the statement executes 73
74 do while loop General form of flowchart: 74
75 do while loop To avoid an infinite loop, the loop body must contain a statement that makes the expression false The statement can be simple or compound. If compound, it must be in braces do...while loop has an exit condition and always iterates at least once (unlike for and while) 75
76 do while loop Example: to display the first five positive integers which increment by five. 76
77 do while loop Pseudocode: Begin End Initialize i to 0 do Display i add 5 to I (update) While i is less than or equal to 20 77
78 do while loop Flowchart Enter do statement Start i = 0 Display i Expression evaluates to zero False condition End Loop True condition i = i + 5 Expression evaluates to a nonzero number i <= 20 Go back and reevaluate the expression 78
79 do while loop C++ program segment i = 0; do { cout << i << ; i = i + 5; } while ( i <= 20); 79
80 do while loop Exercise 1 a. The while loop produces nothing. b. The do..while loop outputs the number 11 and also changes the value of i to
81 do while loop Exercise 2 determine the output of the following program int x = 20; do { cout << x << endl; x = x 4; } while (x > 10) 81
82 do while loop Exercise 3 determine the output of the following program int x = 1; do { cout << x << endl; x = x + 1; } while (x < 5) 82
83 do while loop Exercise 4 determine the output of the following program int total = 1; do { cout << total << endl; total = total + 2; } while (total >=3) 83
84 do while loop Answer: INFINITE LOOP! 84
85 Nested Control Structures 85
86 Nested loop In many situations, it is very convenient to have a loop contained within another loop. Such loops are called nested loops. For each single trip, through the outer loop, the inner loop runs through its entire sequence. Each time counter i increases by 1, the inner loop executes completely. 86
87 Nested loop Example of C++ program segment for (i = 0; i <= 5; i++) { cout << "\n i is now " << i << endl; } for (j = 1; j <= 4; j++) cout << " j = " << j ; 87
88 How it works Nested loop Outer loop i is now 0 j = 1 j = 2 j = 3 j = 4 i is now 1 j = 1 j = 2 j = 3 j = 4 i is now 2 j = 1 j = 2 j = 3 j = 4 i is now 3 j = 1 j = 2 j = 3 j = 4 i is now 4 j = 1 j = 2 j = 3 j = 4 Inner loop i is now 5 j = 1 j = 2 j = 3 j = 4 88
89 Nested loop Suppose we want to create the following pattern. * ** *** **** ***** In the first line, we want to print one star, in the second line two stars and so on. 89
90 Nested loop Since five lines are to be printed, we start with the following for statement. for (i = 1; i <= 5 ; i++) The value of i in the first iteration is 1, in the second iteration it is 2, and so on Can use the value of i as limit condition in another for loop nested within this loop to control the number of starts in a line. 90
91 Nested loop The syntax for (i = 1; i <= 5 ; i++) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } 91
92 Nested loop What pattern does the code produce if we replace the first for statement with the following? for (i = 5; i >= 1; i--) Answer: ***** **** *** ** * 92
93 The jump statements 93
94 break Causes an exit from loop or switch statement void main() { int x; for (x = 1; x<=10; x++) { if (x == 5) break; cout<< x << ; } cout<< loop terminated at x: <<x<<endl; } loop terminated at x: 5 Press any key to continue 94
95 continue Skips the remaining statements in the loop and proceed with the next loop void main() { int x; for (x = 1; x<=10; x++) { if (x == 5) { a=x; continue; } cout<< x << ; } cout<< the number <<a<<endl; cout<< is not printed <<endl; } the number 5 is not printed Press any key to continue 95
96 96
C++ 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 informationChapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?
Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,
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 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 informationChapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition) 1 Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and
More informationIslamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.
Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for
More informationProgramming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester
Programming Language Control Structures: Repetition (while) Eng. Anis Nazer Second Semester 2017-2018 Repetition statements Control statements change the order which statements are executed Selection :
More informationIncrement and the While. Class 15
Increment and the While Class 15 Increment and Decrement Operators Increment and Decrement Increase or decrease a value by one, respectively. the most common operation in all of programming is to increment
More information*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
More information5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.
Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More informationCSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure
Learning Objectives At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable () Use increment (++) and decrement ( ) operators Program
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 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.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators
Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;
More informationLecture 7 Tao Wang 1
Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement
More informationCSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York
CSc 10200 Introduc/on to Compu/ng Lecture 8 Edgardo Molina Fall 2011 City College of New York 18 The Null Statement Null statement Semicolon with nothing preceding it ; Do-nothing statement required for
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 informationWeek 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.
Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than
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 informationC++ Programming Lecture 7 Control Structure I (Repetition) Part I
C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer
More informationCHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad Outline 1. C++ Iterative Constructs 2. The for Repetition Structure 3. Examples Using the for Structure 4. The while Repetition Structure
More informationLECTURE 5 Control Structures Part 2
LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on
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 informationCopyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Chapter 6 : (Control Structure- Repetition) Using Decrement or Increment While Loop Do-While Loop FOR Loop Nested Loop
More informationLoops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017
Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The
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 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 information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationJava. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures
Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,
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 informationChapter 5: Loops and Files
Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;
More informationLooping. Arizona State University 1
Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationChapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1
Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)
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 informationRepetition and Loop Statements Chapter 5
Repetition and Loop Statements Chapter 5 1 Chapter Objectives To understand why repetition is an important control structure in programming To learn about loop control variables and the three steps needed
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 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 informationProgramming Fundamentals
Programming Fundamentals Programming Fundamentals Instructor : Zuhair Qadir Lecture # 11 30th-November-2013 1 Programming Fundamentals Programming Fundamentals Lecture # 11 2 Switch Control substitute
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 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 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 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 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 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 informationC++ Final Exam 2017/2018
1) All of the following are examples of integral data types EXCEPT. o A Double o B Char o C Short o D Int 2) After the execution of the following code, what will be the value of numb if the input value
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 informationAn Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure Objectives Differentiate between a pretest loop and a posttest loop Include a pretest loop in pseudocode Include
More informationControl Structures of C++ Programming (2)
Control Structures of C++ Programming (2) CISC1600/1610 Computer Science I/Lab Fall 2016 CISC 1600 Yanjun Li 1 Loops Purpose: Execute a block of code multiple times (repeat) Types: for, while, do/while
More informationChapter 4: Control structures. Repetition
Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition
More informationwhile for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)
Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent
More informationn Group of statements that are executed repeatedly while some condition remains true
Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,
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 informationPrepared by: Shraddha Modi
Prepared by: Shraddha Modi Introduction In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop consist of two segments Body of
More informationLoops and Files. of do-while loop
L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.
More informationDept. of CSE, IIT KGP
Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of
More informationMultiple Choice (Questions 1 14) 28 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 informationChapter 4: Control structures
Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - Loops Stephen Scott (Adapted from Christopher M. Bourke) 1 / 1 Fall 2009 cbourke@cse.unl.edu Chapter 5 5.1 Repetition in
More information204111: Computer and Programming
204111: Computer and Programming Week 4: Control Structures t Monchai Sopitkamon, Ph.D. Overview Types of control structures Using selection structure Using repetition structure Types of control ol structures
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 informationLoops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input
Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer
More informationComputer Programming I - Unit 5 Lecture page 1 of 14
page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements
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 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 informationLoops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while
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 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 informationPIC 10A Flow control. Ernest Ryu UCLA Mathematics
PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if
More informationCSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.
Chapter 5 While For 1 / 54 Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - s Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 While For 2 / 54 5.1 Repetition
More informationCPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)
Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow
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 informationBuilding on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements
Chapter 5 Looping Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements Advantages of Computers Computers are really
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationUnit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION
INTRODUCTION Decision Making and Looping Unit 5 In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of
More informationControl Structures II. Repetition (Loops)
Control Structures II Repetition (Loops) Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1 to 100 The answer will be 1 + 2 + 3 + 4 + 5 + 6 + +
More informationLoops (while and for)
Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1 Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2 Motivation Name
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 informationcausing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).
Iteration Iteration causing a set of statements (the body) to be executed repeatedly. 1 C++ provides three control structures to support iteration (or looping). Before considering specifics we define some
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 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 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 informationLOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
More informationModule 4: Decision-making and forming loops
1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The
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 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 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 informationSolving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3
Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB A Word About Registration for CS16 FOR THOSE OF YOU NOT YET REGISTERED:
More informationL o o p s. for(initializing expression; control expression; step expression) { one or more statements }
L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat
More informationcausing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).
1 causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). Before considering specifics we define some general terms that
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
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 informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
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 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 informationRepe$$on CSC 121 Spring 2017 Howard Rosenthal
Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when
More informationMultiple Choice (Questions 1 14) 28 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 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 informationProblem Solving With Loops
To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the
More information