Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

Similar documents
Combined Assignment Operators. Flow of Control. Increment Decrement Operators. Operators Precedence (Highest to Lowest) Slide Set 05: Java Loops

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

REPETITION CONTROL STRUCTURE LOGO

Increment and the While. Class 15

Flow of Control. Relational Operators. Operators Review. Order of Operations

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

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.

Chapter 3 Problem Solving and the Computer

DELHI PUBLIC SCHOOL TAPI

C/C++ Programming Lecture 7 Name:

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Chapter 2 - Control Structures

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 2 - Control Structures

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

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

Why Is Repetition Needed?

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

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

Chapter 4 - Notes Control Structures I (Selection)

CSI33 Data Structures

Name Section: M/W T/TH Number Definition Matching (6 Points)

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

In this chapter you will learn:

INTRODUCTION TO COMPUTER SCIENCE - LAB

Add Subtract Multiply Divide

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Name Section: M/W T/TH Number Definition Matching (8 Points)

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

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

6. Control Statements II

Chapter 2 - Control Structures

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Chapter 2 - Control Structures

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

2.1-First.cpp #include <iostream> // contains information to support input / output using namespace std;

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

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

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

Lecture 7 Tao Wang 1

Chapter 5: Control Structures

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Repetition Structures

C++ Final Exam 2017/2018

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

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

Looping. Arizona State University 1

Lab 10: Alternate Controls

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Loops and Files. of do-while loop

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Dept. of CSE, IIT KGP

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Getting started with C++ (Part 2)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Chapter 5: Loops and Files

Chapter 7. Additional Control Structures

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

LAB 4.1 Relational Operators and the if Statement

Name SECTION: 12:45 2:20. True or False (12 Points)

Introduction. C provides two styles of flow control:

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

do { statements } while (condition);

WARM UP LESSONS BARE BASICS

Introduction to Programming

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

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

SFU CMPT Topic: Control Statements

CSCI 111 Midterm 1, version A Exam Fall Solutions 09.00am 09.50am, Tuesday, October 13, 2015

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

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

Introduction to Programming

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

From Pseudcode Algorithms directly to C++ programs

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

Chapter 5: Control Structures II (Repetition)

Programming Fundamentals

Control Structures. Flowchart Symbols

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Sample Code: OUTPUT Daily Highs & Lows

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Transcription:

Control Structures Flow of control Execution sequence of program statements Repetition (Loop) Structure Control structure used to repeat a sequence of instructions in a loop The simplest loop structure is the while() Sequential Control Structure Selection (Branching) Control Structure Repetition (Loop) Control Structure Conditional T/F Assertion Relational & Logical Operators for Assertion Repetition processing while( ) do-while( ) for( ) Statement 1 Assertion Statement 2 Statement 3 Statement 4 Statement 5 Statement 6 Statement 1; while(assertion) Statement 2; Statement 3; Statement 4; Statement 5; Statement 6; Copyright 2005 R.M. Laurie 1 Copyright 2005 R.M. Laurie 2 Repetition (Loop) Structure Repetition (Loop) Structure Display Loop Number Increment Count Display Done Pseudo code: WHILE Display: Count Count = Count +1 WHILE Display: Done Display Loop Number Increment Count Display Done #include <iostream> int main() int ncnt = 1; while(ncnt <= 5) cout << "In Loop " << ncnt << endl; ncnt = ncnt + 1; cout << "Done"; Copyright 2005 R.M. Laurie 3 Copyright 2005 R.M. Laurie 4 Copyright 2005 R.M. Laurie 1

while statement loop control Contents of loop executed repeatedly while(assertion) is true Loop terminated when while(assertion) is false. Counter-Controlled Loop Structure Initialize a counter to count loops Increment or decrement counter within loop while(assertion) Counter value valid? Sentinel-Controlled Loop Structure while(assertion) checks for a sentinel termination value Copyright 2005 R.M. Laurie 5 Counter-Controlled Repetition Structure 3. int main() 4. 5. int nscore, ntotal=0, ncntr=0; 6. while(ncntr < 5) 7. 8. cout << "\n\n>"; 9. cin >> nscore; 10. ntotal = ntotal + nscore; 11. ncntr = ncntr + 1; 12. cout << "Score " << ncntr 13. << " = " << nscore << endl; 14. 15. cout << "----------------------" 16. << "\nthe Average Score = " 17. << ntotal/5 << endl; 18. 19. >90 Score 1 = 90 >100 Score 2 = 100 >80 Score 3 = 80 >60 Score 4 = 60 >70 Score 5 = 70 ---------------------- The Average Score = 80 Copyright 2005 R.M. Laurie 6 Sentinel-Controlled Repetition Structure 3. int main() 4. 5. int nscore=0, ntotal=0, ncntr=0; 6. while(nscore >= 0) 7. 8. cout << "\n\n>"; 9. cin >> nscore; 10. if(nscore >= 0) 11. 12. ntotal = ntotal + nscore; 13. cout << "Score " << ++ncntr 14. << " = " << nscore << endl; 15. 16. 17. cout << "----------------------" 18. << "\nthe Average Score = " 19. << ntotal/ncntr << endl; 20. 21. >90 Score 1 = 90 >80 Score 2 = 80 >83 Score 3 = 83 >87 Score 4 = 87 >-1 ---------------------- The Average Score = 85 Copyright 2005 R.M. Laurie 7 Repetition Practice Programs Create a program that will display the first 10 multiples of an entered number. Will loop be counter or sentinel controlled? Example: if 7 is entered the format is: 1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 Create a program that will add scores until a -1 is entered Will loop be counter or sentinel controlled? Copyright 2005 R.M. Laurie 8 Copyright 2005 R.M. Laurie 2

Filtered Input Application: Wrong Entry is not an option! 4. 5. char centry = 'f'; 6. while(centry!= 'y' && centry!= 'n') 7. 8. cout << "Do you like Programming? (y or n)\n>"; 9. cin >> centry; 10. cin.ignore(100,'\n'); 11. if(centry == 'y') 12. cout << "I\'m glad you like programming!"; 13. else if(centry == 'n') 14. cout << "You will like it if you study."; 15. else 16. cout << "You must enter either y or n!\n\n"; 17. 18. cout << "\n\ndone\n\n"; 19. 20. do - while Structure A loop structure that guarantees the loop body is executed once. Condition is tested at bottom of loop Initialize Counter do statement1; statement2; Increment Counter Check Counter Initialize Counter; REPEAT Statement1 Statement2 Increment Counter UNTIL(Assertion) Copyright 2005 R.M. Laurie 10 Count = 0 Statement 1; Statement 2; Count++ Statement 3; do-while Example Don t forget semicolon for while(...); 1. int ncount=0; 2. do 3. 4. Statement 1; 5. Statement 2; 6. ncount++; Required 7. while(ncount <=0); 8. Statement 3; Copyright 2005 R.M. Laurie 11 Filtered Input Application: Using do while Loop is guarenteed to execute one time because assertion checked at end of loop #include <iostream> int main( ) char centry; // No initialization necessary do cout << "Do you like Programming? (y or n)\n>"; cin >> centry; cin.ignore(100,'\n'); if(centry == 'y') cout << "I\'m glad you like programming!"; else if(centry == 'n') cout << "You will like it if you study."; else cout << "You must enter either y or n!\n\n"; while(centry!= 'y' && centry!= 'n'); cout << "\n\ndone\n\n"; Copyright 2005 R.M. Laurie 3

Designing Loops 1. What condition will end the loop? 2. How should condition be initialized? 3. How should condition be updated? 4. What is the process being repeated? 5. How should the process be initialized? 6. How should the process be updated? 7. What is the state of the program on exiting the loop? Copyright 2005 R.M. Laurie 13 Temperature Program -Ver.3 2. #include <iomanip> 3. 4. int main() 5. 6. // DECLARATION SECTION 7. char cquestion; 8. float ftemperature; 9. cout << fixed; // Allows float point format 10. // PROCESSING SECTION 11. cout << "This program converts temperatures between\n" 12. << "degrees Celsius and degrees Fahrenheit.\n" 13. << "You may enter either a Celsius or " 14. << "Fahrenheit\ntemperature for conversion.\n\n"; 15. while(true) 16. 17. cout << "> <-- Enter C (Celsius), F (Fahrenheit), or Q (Quit)\r>"; 18. cin >> cquestion; 19. cin.ignore(100,'\n'); Copyright 2005 R.M. Laurie 14 20. if(cquestion == 'C' cquestion == 'c') 21. 22. cout << " <-- Enter temperature in degrees Celsius\r>"; Temperature Program Output 23. cin >> ftemperature; 24. cin.ignore(100,'\n'); 25. cout << "Results: " << setprecision(2) This program converts temperatures between 26. << ftemperature << " C = " degrees Celsius and degrees Fahrenheit. 27. << (((ftemperature * 180) / 100) + 32) << " F\n"; You may enter either a Celsius or Fahrenheit 28. 29. else if(cquestion == 'F' cquestion == 'f') temperature for conversion. >r<-- Enter C (Celsius), F (Fahrenheit), or Q (Quit) Fahrenheit \r>"; 32. cin >> ftemperature; >W<-- Enter C (Celsius), F (Fahrenheit), or Q (Quit) 33. cin.ignore(100,'\n'); >C<-- Enter C (Celsius), F (Fahrenheit), or Q (Quit) 34. cout << "Results: " << setprecision(2) >100 <-- Enter temperature in degrees Celsius 30. 31. cout << " <-- Enter temperature in degrees 35. << ftemperature << " F = " Results: 100.00 C = 212.00 F 36. << (((ftemperature - 32) * 100) / 180) << " C\n"; >f<-- Enter C (Celsius), F (Fahrenheit), or Q (Quit) 37. >0 <-- Enter temperature in degrees Fahrenheit 38. else if (cquestion == 'Q' cquestion == 'q') Results: 0.00 F = -17.78 C >q<-- Enter C (Celsius), F (Fahrenheit), or Q (Quit) 39. 40. cout << "\ngood bye"; 41. 42. 43. else 44. cout << "\a"; Good bye Terminated with return code 0 45. Press any key to continue... 46. Copyright 2005 R.M. Laurie 16 Copyright 2005 R.M. Laurie 4

for Loop Structure Nested for Loop Example Loop structure that contains in one statement: for( initialization; assertion; increment ) Display Loop Number Increment Count Display Done int main() int nc = 1; for(nc=1; nc<= 5; nc++) cout << "In Loop " << nc << endl; cout << "Done"; Copyright 2005 R.M. Laurie 17 #include <iostream> int main(void) int ni, nj; for(ni=1; ni<=5; ni++) cout << ni << " "; cout << endl; for(ni = 5; ni >= 0; --ni) cout << endl; for( nj = 4; nj >= 0; --nj) cout << (ni + nj) << ' '; 1 2 3 4 5 9 8 7 6 5 8 7 6 5 4 7 6 5 4 3 6 5 4 3 2 5 4 3 2 1 4 3 2 1 0 Copyright 2005 R.M. Laurie 18 break; continue; commands Statement 1; while(?) Statement 2; continue; Statement 3; if(?) if(?) Statement 4; break; Statement 5; 1. Statement 1; 2. while(?) 3. 4. Statement 2; 5. if(?) 6. continue; 7. Statement 3; 8. if(?) 9. break; 10. Statement 4; 11. 12.Statement 5; Copyright 2005 R.M. Laurie 19 4. 5. char centry = 'f'; 6. while(true) 7. 8. cout << "Do you like Programming? (y or n)\n>"; 9. cin >> centry; 10. cin.ignore(100,'\n'); 11. if(centry == 'y') 12. 13. cout << "I\'m glad you like programming!"; 14. break; 15. 16. if(centry == 'n') 17. 18. cout << "You will like it if you study."; 19. break; 20. 21. cout << "You must enter either y or n!\n\n"; 22. 23. cout << "\n\ndone\n\n"; 24. 25. Copyright 2005 R.M. Laurie 5

4. 5. int nentry; 6. cout << "This program will allow you to enter\n" 7. << "numbers in the range 20 to 100\n\n"; 8. while(true) 9. 10. cout << "Enter number: "; 11. cin >> nentry; 12. cin.ignore(100,'\n'); 13. if(nentry <= 100 && nentry >= 20) 14. 15. cout << "Entry " << nentry << " is valid\n"; 16. break; 17. 18. if(nentry < 20) 19. 20. cout << "Your entry is less then 20!\n\n"; 21. continue; 22. 23. cout << "Your entry is greater then 100!\n\n"; 24. 25. cout << "\n\ndone\n\n"; 26. switch - case Structure A selection structure that can be used to select one of many branches Works best for a switch variable type of Integers or Characters but not strings switch (Grade) case 'P': case 'p': cout << "You Passed\n"; break; case 'F': case 'f': cout << "You Failed"; break; default: cout <<"Incorrect letter Grade."; 27. Copyright 2005 R.M. Laurie 22 4. 5. char centry; 6. cout << "This program will make a" 7. << "comment about your grade.\n\n"; 8. cout << "Enter Grade: "; 9. cin >> centry; 10. cin.ignore(100,'\n'); 11. switch (centry) 12. 13. case 'A': case 'a': 14. cout << "Excellent work"; 15. break; 16. case 'B': case 'b': 17. cout << "Good work"; 18. break; 19. case 'C': case 'c': 20. cout << "Average work"; 21. break; 22. case 'D': case 'd': 23. case 'F': case 'f': 24. cout << "Poor work"; 25. break; 26. default: // catch all other characters 27. cout << "Incorrect letter Grade."; 28. 29. cout << "\n\ndone\n\n"; 30. 31. Copyright 2005 R.M. Laurie 6