Control of flow We learned that default flow of instructions is sequential. Then, we learned how to control the flow using "if" and "switch." Now, we will.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
1 CIS Jan Overview Selection Statements –If Statement –Else –Nested If-Else –Switch Repetition Statements –While statement –For Statement.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 4 Program Control Statements
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Selection Structures (if & switch statements) (CS1123)
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
If statement The "if statement" is used to break the sequential flow of execution. Enforces branching in execution according to the result of an expression.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Previously Repetition Structures While, Do-While, For.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Control Structures Repetition or Iteration or Looping Part II.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Control Structures RepetitionorIterationorLooping Part I.
Message: "You are mature"
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Computer Programming -1-
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Introduction to Computer Programming
REPETITION CONTROL STRUCTURE
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Programming Fundamentals
Looping.
Iteration with While You can say that again.
TOPIC 4: REPETITION CONTROL STRUCTURE
Let’s all Repeat Together
Presentation transcript:

Programming in C++ Repetation control structure: Loops EEE 145 Programming in C++ Repetation control structure: Loops

Control of flow We learned that default flow of instructions is sequential. Then, we learned how to control the flow using "if" and "switch." Now, we will learn how to repeat a group of instructions. Read b and c a = b+c Display a Read age Rest of the program Message: "You are young" Message: "You are mature" age<=25 ? T F Read score of the student Add it to the overall sum Display sum Any students left? T F

Types of loops There are three types of loops: "for" loop "while" loop "do-while" loop You can implement anyone of these loops using the others (and possibly an additional if statement and duplication of some statements). The idea is to use the type of loop that is best suited for your problem.

General structure of a loop A loop is typically composed of three parts: the statement block which is to be repeated; a control mechanism to decide whether the statement block should be repeated once more (based on an expression); an update mechanism that affects the value of the control expression (to avoid infinite loops). The update mechanism may be embedded in the statement block.

General structure of a loop One execution of the statement block is called an iteration. Thus, a loop iterates the statement block several times. Make sure: it is possible to enter the loop; it is possible to get out of the loop, once you enter it.

For loop Use for loop if you know the number of iterations. You don't have to know the exact number of iterations; it is enough if you can express it.

For loop Syntax: for (initial_stat(s);int_expr; final_stat(s)) stat_block initial_stat(s) int_expr F final_stat(s) T stat_block Rest of the program

For loop Note that initial and final statements as well as the integer expression are optional according to the syntax. If initial_stat(s) is missing, start directly with the comparison. If final_stat(s) is missing, go directly to the comparison after the execution of the statement block. If int_expr is missing, the comparison is always true. Make use of the break statement (to be discussed later).

for: Example 1 Write a code segment that prints the text "I didn't do my homework" 100 times with every line enumerated. cout<<"1. I didn't do my homework.\n"; cout<< "2. I didn't do my homework.\n"; cout<< "3. I didn't do my homework.\n"; cout<< "4. I didn't do my homework.\n"; cout<< "5. I didn't do my homework.\n"; cout<< "6. I didn't do my homework.\n"; cout<< "7. I didn't do my homework.\n"; cout<< "8. I didn't do my homework.\n"; cout<< "9. I didn't do my homework.\n"; cout<< "10. I didn't do my homework.\n"; cout<< "11. I didn't do my homework.\n"; cout<< "12. I didn't do my homework.\n"; cout<< "13. I didn't do my homework.\n"; cout<< "14. I didn't do my homework.\n"; cout<< "15. I didn't do my homework.\n"; . . cout<< "91. I didn't do my homework.\n"; cout<< "92. I didn't do my homework.\n"; cout<< "93. I didn't do my homework.\n"; cout<< "94. I didn't do my homework.\n"; cout<< "95. I didn't do my homework.\n"; cout<< "96. I didn't do my homework.\n"; cout<< "97. I didn't do my homework.\n"; cout<< "98. I didn't do my homework.\n"; cout<< "99. I didn't do my homework.\n"; cout<< "100.I didn't do my homework.\n";

for: Example 1 (cont'd) Lazy student's solution  int i; for (i=1; i<=100; i++) cout<< i << ".I didn't do my homework.\n";

for: Example 2 Find ab. (a and b integers) int a, b, result=1, i; cin>> a >> b; for (i=0; i<b; i++) result *= a;

for: Example 2 (cont'd) Same question, solved with fewer variable (but the value of b changes). int a, b, result=1; cin>> a >> b; for (; b; b--) result *= a; cout<<“result=“<< result;

for: Example 3 Find the average of the midterm scores of the students in EEE145. int i, sum, no_stu, score; float avg; cin>> no_stu; for (sum=i=0; i<no_stu; i++) { cin >> score; sum += score; } avg = sum/no_stu; What is wrong here? What else? What if "no_stu" is zero?

for: Example 4 Calculate BMI (Body Mass Index) of all students in class  weight/height for (i=0; i<100; i++) { cin>> weight >> height; cout<<"BMI:“<< (float)weight/height; } What if "height" is zero?

for: Example 5 What are the differences between these code segments? for (i=0; i<5; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=0; i<=5; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=1; i<5; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; 0;1;2;3;4;{5} 0;1;2;3;4;5;{6} 1;2;3;4;{5} for (i=1; i<=5; ++i) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (; i<5; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=0;; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; 1;2;3;4;5;{6} Starts from anything ...;3;4;{5} OR MAYBE SOMETHING LIKE {795} 0;1;2;...∞ for (i=0; i<5;) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=0; i<5;) cout<< i++<< ";"; cout<<"{"<< i <<"}"; for (i=0; i++<5;) cout<< i<< ";"; cout<<"{"<< i <<"}"; 0;0;0;0;...∞ 0;1;2;3;4;{5} 1;2;3;4;5;{6}

for: Example 6 Now, compare these code segments. for (i=7; i<5; i++) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=7;++i<5;) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=7;i++<5;) cout<< i<< ";"; cout<<"{"<< i <<"}"; {7} {8} {8} for (i=7; ++i<5; ++i) cout<< i<< ";"; cout<<"{"<< i <<"}"; for (i=0; i<5; ++i) cout<< ++i<< ";"; cout<<"{"<< i <<"}"; {8} 1;3;5;{6}

for: Example 7 What if Carl Friedrich Gauss knew how to program when he was in elementary school? Let's be more generic; add numbers from 1 to n. cin >> n; for (sum=0, i=1; i<=n; i++) sum += i; Of course Gauss would be clever enough to do sum = n * ((n+1)/2);

for: Example 8 Find whether a number is perfect or not. (A number is perfect if sum of its positive divisors except itself is equal to itself. Eg: 6=1+2+3; 28=1+2+4+7+14) int number, i, sum = 0; cin >> number; for (i = 1; i <= number / 2 ; i++) if (number % i == 0) sum += i; if (number == sum) cout<< number << "is a perfect number"; else cout<< number << "is not a perfect number";

While loop Use while loop if the statement block should be executed as long as a condition holds. Syntax: while (int_expr) stat_block int_expr F T stat_block Rest of the program

while: Example 1 Find the average of a sequence of integers terminated with a negative value. int sum=0, n, count=0; float avg; cin >> n; while (n>=0) { sum += n; count++; } avg = (count)?(float)sum/count:0;

while: Example 2 Consider a type of cell that reproduces by mitosis. Assume each cell divides into two cells every second. Display the number of cells after each second for 100 seconds. Start with one cell. int n=1, t=0; while (t<=100) { cout<<"t= " << t <<"n= "<<n<<endl; n *= 2; t++; }

while: Example 3 Assume the user enters a sequence of 1s and 0s. Any other character marks the end of input. Take 1's complement of the input. char ch; ch=getchar(); while ((ch=='0') || (ch=='1')) { cout<< !(ch-'0'); }

Do-while loop Similar to while loop. Syntax: Only difference: Condition is checked after the execution of every iteration. Syntax: do { stat(s) } while (int_expr); stat(s) T int_expr F Rest of the program

do-while: Example 1 Solve the previous example, this time using do-while. Find the average of a sequence of integers terminated with a negative value. int sum=0, n, count=0; float avg; do { cin>> n; if (n>=0) sum += n; count++; } } while (n>=0); avg = (count)?(float)sum/count:0; cout<< avg <<endl; Note that we repeated the condition in the if statement, so it was not a good idea to solve this problem using do-while.

break statement It is possible to terminate a loop prematurely. Remember the break statement we discussed before. break breaks the innermost loop or switch statement.

break: Example Read 100 integers and find their product. However, if one of the numbers is non-positive, stop input. long int mul=1; int i, num; for (i=0; i<100; i++) { cin>>num; if (num<=0) break; mul *= num; } cout<<mul<<endl;

continue statement It is possible to skip the rest of an iteration and continue with the next iteration (if any). In the for loop, continue jumps to the final statement. In the while and do-while loops, continue jumps to the condition expression.

continue: Example 1 Consider the following two code segments. Assume input is: 5 -4 3 2 -5 8 9 1 sum = i = 0; while (i < 6) { cin>>no; if (no <= 0) continue; sum += no; i++; } /* sum becomes 28 */ sum = 0; for (i = 0; i < 6; i++) { cin>>no; if (no <= 0) continue; sum += no; } /* sum becomes 18 */

continue: Example 2 Find the number of passengers/car for every flat in a building with 40 flats. for (i=0; i<40; i++) { cin>>no_cars; if (no_cars==0) continue; cin >> no_residents; cout<< (float)no_residents/no_cars } BURADA KALDIM (18/3/2008)

Example: Nested loops You can nest the loops as you do with if statements.

Nested loops: Example 1 Draw an isosceles triangle using '*' character. Number of lines is read as input. #include <iostream> int main() { int line, i, j; cout<<"Enter the height :"; cin >> line; for (i = 1; i <= line; i++) for (j = 0; j < line - i; j++) cout<<" "; for (j = 0; j < i * 2 - 1; j++) cout<<"*"; cout<<"\n"; } return 0;

Example Read an integer and print its digits in reverse order. #include <iostream> int main() { int num, digit; cin>>num; while (num) { digit=num%10; num /= 10; cout<<digit; } return 0;

Example Solve the question by considering only the first four digits after the decimal point to be significant. Eg: If the input is 35.794678, the output should be 7946.35. #include <stdio.h> int main() { float num, dec, whole; int i; cin>>num; whole = (int) num; dec = num-whole; while (whole>1) whole /= 10; for (i=0; i<4; i++) dec *= 10; num = (int)dec+whole; cout<<num<<endl; }

Example Write a C++ program that will calculate using series representation. Note that this series converges if −1 < x ≤ 1

#include <iostream> #include <cmath> using namespace std; int main() { double sum, term, x=2.0; int n; while(x>1.0 || x<-1.0){ cout<<"Enter a value between -1 and+1:"; cin>>x; } term=sum=x; n=1; while(fabs(term) > 1.0e-8){ ++n; term= -term*(x/n)*(n-1); sum += term; cout<<"The sum of the series:"<< sum<<endl; cout<<"Number of terms in the series:"<< n<<endl; cout<<"cmat function result:"<<log(1+x)<<endl; return 0;

Homework The exponential function can be represented by infinite series Write a C++ program to calculate exp(x) using the given series.

Homework The trigonometric sine function can be represented by infinite series Write a C++ program to calculate sin(x) using the given series.