while for ! do while ! set an accumulator variable to 0 ! add the next number to it inside the loop

Similar documents
What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

While Loop. 6. Iteration

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

UEE1302 (1102) F10 Introduction to Computers and Programming

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Chapter 8 Selection 8-1

6. Control Structures

Appendix K Introduction to Microsoft Visual C++ 6.0

Basics of I/O Streams and File I/O

Logistics. Software Testing. Logistics. Logistics. Plan for this week. Before we begin. Project. Final exam. Questions?

Chapter 9 Text Files User Defined Data Types User Defined Header Files

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Lecture 2 Notes: Flow of Control

Chapter 5. Selection 5-1

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Visual Logic Instructions and Assignments

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Moving from C++ to VBA

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Two-way selection. Branching and Looping

C++ Input/Output: Streams

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Conditions & Boolean Expressions

Ubuntu. Ubuntu. C++ Overview. Ubuntu. History of C++ Major Features of C++

The Payroll Program. Payroll

Chapter One Introduction to Programming

Using C++ File Streams

Answers to Selected Exercises

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

The While Loop. Objectives. Textbook. WHILE Loops

Iteration CHAPTER 6. Topic Summary

LOOPS CHAPTER CHAPTER GOALS

Writing Control Structures

Change Impact Analysis

Flowchart Techniques

Compiler Construction

Figure 1: Graphical example of a mergesort 1.

Test Case Design Techniques

Reading Input From A File

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

A brief introduction to C++ and Interfacing with Excel

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

What is the consequences of no break statement in a case.

Member Functions of the istream Class

The if Statement and Practice Problems

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Selection Statements

El Dorado Union High School District Educational Services

Lab 2: Swat ATM (Machine (Machine))

ENGI E1112 Departmental Project Report: Computer Science/Computer Engineering

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Answers to Review Questions Chapter 7

Decision Logic: if, if else, switch, Boolean conditions and variables

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Repetition Using the End of File Condition

Curriculum Map. Discipline: Computer Science Course: C++

Getting started with the Stata

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

River Dell Regional School District. Computer Programming with Python Curriculum

Passing 1D arrays to functions.

I PUC - Computer Science. Practical s Syllabus. Contents

if and if-else: Part 1

Informatica e Sistemi in Tempo Reale

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Tutorial on C Language Programming

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Java (12 Weeks) Introduction to Java Programming Language

Unit 6. Loop statements

Creating a Simple Visual C++ Program

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Lecture Notes on Linear Search

Different Approaches to White Box Testing Technique for Finding Errors

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Python Programming: An Introduction To Computer Science

Statements and Control Flow

C++FA 5.1 PRACTICE MID-TERM EXAM

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Senem Kumova Metin & Ilker Korkmaz 1

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Problem Solving Basics and Computer Programming

Common Beginner C++ Programming Mistakes

Example of a Java program

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

Answers to the Try It Yourself Sections

Object Oriented Software Design

Test case design techniques I: Whitebox testing CISS

ECE 3401 Lecture 7. Concurrent Statements & Sequential Statements (Process)

While and Do-While Loops Summer 2010 Margaret Reid-Miller

13 Classes & Objects with Constructors/Destructors

Transcription:

Week 7: Advanced Loops while Loops in C++ (review) while (expression) statement statement may be a compound statement (a block: {statements) Gaddis: 5.7-12 CS 1428 Fall 2014 Jill Seaman 1 for if expression is true, statement is executed, repeat equivalent to: do while for (expr1; expr2; expr3) statement do statement while (expression); expr1; while (expr2) { statement expr3; statement is executed. if expression is true, then repeat 2 Counting (review) set a counter variable to 0 increment it inside the loop (each iteration) after each iteration of the loop, it stores the # of loop iterations so far int number; int count = 0; cout << Enter a number between 1 and 10: ; cin >> number; while (number < 1 number > 10) { count = count + 1; cout << Please enter a number between 1 and 10: ; cin >> number; cout << count << invalid numbers entered << endl; // Do something with number here 3 5.7 Keeping a running total (summing) set an accumulator variable to 0 add the next number to it inside the loop after each iteration of the loop, it stores the sum of the numbers added so far (running total) int days; //Counter for count-controlled loop float total = 0.0; //Accumulator float miles; //daily miles ridden cout << How many days did you ride your bike? ; cin >> days; for (int i = 1; i <= days; i++) { cout << Enter the miles for day << i << : ; cin >> miles; total = total + miles; cout << Total miles ridden: << total << endl; total is 0 first time through 4

Output: Keeping a running total How many days did you ride you bike? 3 Enter the miles for day 1: 14.2 Enter the miles for day 2: 25.4 Enter the miles for day 3: 12.2 Total miles ridden: 51.8 How would you calculate the average mileage? 5.8 Sentinel controlled loop sentinel: special value in a list of values that indicates the end of the data sentinel value must not be a valid value -99 for a test score, -1 for miles ridden User does not need to count how many values will be entered Requires a priming read before the loop starts so the sentinel is NOT included in the sum the loop can be skipped (if first value is the sentinel) 5 6 Example: Output: Sentinel example float total = 0.0; //Accumulator float miles; //daily miles ridden cout << Enter the miles you rode on your bike each day, ; cout << then enter -1 when finished. << endl; cin >> miles; //priming read while (miles = -1) { total = total + miles; //skipped when miles==-1 cin >> miles; //get the next one cout << Total miles ridden: << total << endl; Enter the miles you rode on your bike each day, then enter -1 when finished. 14.2 25.4 12.2-1 7 Total miles ridden: 51.8 5.9 Which Loop to use? Any loop can work for any given problem while loop: test at start of loop validating input, sentinel controlled loops, etc. for loop: initialize/test/update count-controlled loops do-while loop always do at least once good for repeating, simple menu processing 8

5.10 Nested loops When one loop appears in the body of another For every iteration of the outer loop, we do all the iterations of the inner loop Example from real life : A clock. For each hour in a day (24), we iterate over 60 minutes. 12:00 1:00 2:00 3:00 12:01 1:01 2:01. 12:02 1:02 2:02........... 12:59 1:59 2:59. 9 Print a bar graph Input numbers from a file. For each number, output that many asterisks (*) in a row. int number; ifstream inputfile; inputfile.open( numbers.txt ); inputfile >> number; //priming read while (number=-1) { for (int i = 1; i <= number; i++) cout << * ; cout << endl; inputfile >> number; numbers.txt: 8 3 6 10-1 Output: ******** *** ****** ********** 10 Calculate grades for a class For each student, input the test scores from the user and output the average. int numstudents, numtests; cout << How many students? ; cin >> numstudents; cout << How many test scores? ; cin >> numtests; for (int student=1; student <= numstudents; student++) { float total = 0, score; cout << Enter the << numtests << test scores for student << student << endl; for (int test=1; test <= numtests; test++) { cin >> score; total = total + score; Inner loop float avgscore = total/numtests; cout << Average for student << student Outer loop << is: << avgscore << endl; 11 Output: Calculate grades for a class How many students? 3 How many test scores? 4 Enter the 4 test scores for student 1 88 90.5 92 77.5 Average for student1 is: 87.0 Enter the 4 test scores for student 2 66.5 70.5 80 86 Average for student2 is: 75.8 Enter the 4 test scores for student 3 99 93.5 80 79 Average for student3 is: 87.9 12

5.11 More File I/O Can test a file stream object as if it were a boolean variable to check for various errors. After opening a file, if the open operation failed, the value of file stream variable is false. ifstream infile; infile.open("test.txt"); if (infile) { cout << "File open failure"; return 1; Reading data from a file Use fin>>x; in a loop Problem: when to stop the loop? First entry in file could be count of number of items problems: maintenance, large files Could use sentinel value problem: may not be one, maintenance Want to automatically detect end of file 13 14 Using >> to detect end of file stream extraction operation (>>) returns true when a value was successfully read, false otherwise int number; ifstream inputfile; inputfile.open( numbers.txt ); bool foundvalue = (inputfile >> number); inputfile >> number: tries to read a value into number if it was successful, value is true if it failed (nothing left to input), value is false (and the value in the variable does not change) 15 Example: Using the result of >> int number; ifstream inputfile; inputfile.open( numbers.txt ); bool foundvalue = (inputfile >> number); if (foundvalue) cout << The data read in was: << number << endl; else cout << Could not read data from file. << endl; Can also use directly as relational expression: if (inputfile >> number)... 16

Code: Sum all the values in the file int number; ifstream inputfile; inputfile.open( numbers.txt ); int total = 0; while (inputfile >> number) { total = total + number; cout << The sum of the numbers in the file: << total << endl; numbers.txt: 84 32 99 77 52 Output: The sum of the numbers in the file: 344 17 5.12 Breaking and Continuing Sometimes we want to abort (exit) a loop before it has completed. The break statement can be used to terminate the loop from within: cout << Guess a number between 1 and 10 << endl; int number; while (true) { cin >> number; if (number == 8) break; cout << You got it. << endl; Don t do this. It makes your code hard to read and debug. 18 Stopping a single iteration Sometimes we want to abort an iteration (skip to the end of loop body) before it is done. The continue statement can be used to terminate the current iteration: for (int i=1; i <= 6; i++) { if (i == 4) continue; cout << i << ; Output: 1 2 3 5 6 Don t do this either. It makes your code hard to read and debug. 19 Programming Assignment 4.5 Practice Rewrite PA3, Prepare a Lab Report, so that it uses a loop to enter the data for any number of rats (ask the user to specify the number of rats before the loop starts). Then rewrite it to take the input from a file (do not input the number of rats, just loop until the end of the file). Rewrite PA4, Calculate a Cell Phone Bill, to ask the user if they want to repeat the program after the bill and savings are output. Also put the input validation in a loop. 20