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



Similar documents
UEE1302 (1102) F10 Introduction to Computers and Programming

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

While Loop. 6. Iteration

The While Loop. Objectives. Textbook. WHILE Loops

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

6. Control Structures

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

Lecture 2 Notes: Flow of Control

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:

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

JavaScript: Control Statements I

Visual Logic Instructions and Assignments

Chapter One Introduction to Programming

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

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

ALGORITHMS AND FLOWCHARTS

Two-way selection. Branching and Looping

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Chapter 8 Selection 8-1

Flowchart Techniques

Basics of I/O Streams and File I/O

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

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Senem Kumova Metin & Ilker Korkmaz 1

Python Loops and String Manipulation

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

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

LOOPS CHAPTER CHAPTER GOALS

Moving from CS 61A Scheme to CS 61B Java

Computer Programming I

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

Iteration CHAPTER 6. Topic Summary

Chapter 2: Elements of Java

KS3 Computing Group 1 Programme of Study hours per week

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

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

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

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

River Dell Regional School District. Computer Programming with Python Curriculum

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

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

Computer Science 217

VB.NET Programming Fundamentals

Python Programming: An Introduction To Computer Science

Conditions & Boolean Expressions

Chapter 5. Selection 5-1

Lecture 1 Introduction to Java

Computer Programming I

C++ Input/Output: Streams

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Conditionals (with solutions)

C# programming. Introduction. By Per Laursen

Passing 1D arrays to functions.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

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

Moving from C++ to VBA

CSC 221: Computer Programming I. Fall 2011

Regression Verification: Status Report

El Dorado Union High School District Educational Services

Chapter 7: Software Development Stages Test your knowledge - answers

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

The programming language C. sws1 1

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Chapter 1: Key Concepts of Programming and Software Engineering

Appendix K Introduction to Microsoft Visual C++ 6.0

Pseudo code Tutorial and Exercises Teacher s Version

Algorithm & Flowchart & Pseudo code. Staff Incharge: S.Sasirekha

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

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 13: Program Development and Programming Languages

Introduction to Java

Chapter 9: Building Bigger Programs

CS 241 Data Organization Coding Standards

Common Beginner C++ Programming Mistakes

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

Introduction to Python

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

C++ Language Tutorial

The Payroll Program. Payroll

Practice Questions. CS161 Computer Security, Fall 2008

1 Description of The Simpletron

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Figure 1: Graphical example of a mergesort 1.

Section IV.1: Recursive Algorithms and Recursion Trees

Problem Solving Basics and Computer Programming

Compiler Construction

Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur

Sources: On the Web: Slides will be available on:

Selection Statements

1 Introduction. 2 Overview of the Tool. Program Visualization Tool for Educational Code Analysis

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Stacks. Linear data structures

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

An Incomplete C++ Primer. University of Wyoming MA 5310

Transcription:

QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For division, if the denominator is zero, output an appropriate message.) The sample output follows: 3+4=7 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 2 QUIZ-II Suppose that we want to write a program that analyzes students GPA. If the GPA is greater than or equal to 3.9, the student makes the dean s honor list. If the GPA is less than 2.00, the student is sent a warning letter indicating that the GPA is below the graduation requirement. C++ Programming: From Problem Analysis to Program Design, Sixth Edition 3 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, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures Objectives (cont d.) In this chapter, you will (cont d.): Learn how to avoid bugs by avoiding patches Learn how to debug loops 5 6 Fall-2015 1

Why Is Repetition Needed? Repetition allows efficient use of variables Can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers: Declare a variable for each number, input the numbers and add the variables together Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers Structure Syntax of the while statement: statement can be simple or compound 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 7 8 9 10 i in previous Example 5-1 is called the loop control variable (LCV) Infinite loop: continues to execute endlessly Avoided by including statements in loop body that assure the exit condition is eventually false 11 12 Fall-2015 2

Case 1: Counter-Controlled while Loops When you know exactly how many times the statements need to be executed Use a counter-controlled while loop Case 2: Sentinel-Controlled while Loops Sentinel variable is tested in the condition Loop ends when sentinel is encountered 13 14 Example 5-5: Telephone Digits Case 3: Flag-Controlled while Loops Example 5-5 provides an example of a sentinel-controlled loop(pg : 278) The program converts uppercase letters to their corresponding telephone digit case 'A': case 'B': case 'C': cout << 2 <<endl; case 'D': case 'E': case 'F': cout << 3 << endl; case 'G': case 'H': case 'I': cout << 4 << endl; case 'J': case 'K': case 'L': cout << 5 << endl; Flag-controlled while loop: uses a bool variable to control the loop 15 16 Number Guessing Game Example 5-6 implements a number guessing game using a flag-controlled while loop (Pg:282) Uses the function rand of the header file cstd lib to generate a random number srand(time(0)); Num = rand()%100; rand() returns an int value between 0 and 32767 To convert to an integer >= 0 and < 100: rand() % 100 17 Case 4: EOF-Controlled while Loops End-of-file (EOF)-controlled while loop: when it is difficult to select a sentinel value The logical value returned by cin can determine if there is no more input 18 Fall-2015 3

Case 4: EOF-Controlled while Loops (cont d.) eof Function The function eof can determine the end of file status eof is a member of data type istream Syntax for the function eof: istreamvar is an input stream variable, such as cin 19 20 More on Expressions in while Statements The expression in a while statement can be complex Example: while ((noofguesses < 5) && (!isguessed)) {... } Programming Example: Fibonacci Number Consider the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34,... Called the Fibonacci sequence Given the first two numbers of the sequence (say, a1 and a2) n th number a n, n >= 3, of this sequence is given by: a n = a n-1 + a n-2 21 22 Programming Example: Fibonacci Number (cont d.) Fibonacci sequence n th Fibonacci number a 2 = 1 a 1 = 1 Determine the n th number a n, n >= 3 Programming Example: Fibonacci Number (cont d.) Suppose a 2 = 6 and a 1 = 3 a 3 = a 2 + a 1 = 6 + 3 = 9 a 4 = a 3 + a 2 = 9 + 6 = 15 Write a program that determines the n th Fibonacci number, given the first two numbers 23 24 Fall-2015 4

Programming Example: Input and Output Input: first two Fibonacci numbers and the desired Fibonacci number Output: n th Fibonacci number Programming Example: Problem Analysis and Algorithm Design Algorithm: Get the first two Fibonacci numbers Get the desired Fibonacci number Get the position, n, of the number in the sequence Calculate the next Fibonacci number Add the previous two elements of the sequence Repeat Step 3 until the n th Fibonacci number is found Output the n th Fibonacci number 25 26 Programming Example: Variables Algorithm Prompt the user for the first two numbers that is, previous1 and previous2 Read (input) the first two numbers into previous1 and previous2 Output the first two Fibonacci numbers Prompt the user for the position of the desired Fibonacci number 27 28 Algorithm (cont d.) Read the position of the desired Fibonacci number into nthfibonacci if (nthfibonacci == 1) The desired Fibonacci number is the first Fibonacci number; copy the value of previous1 into current else if (nthfibonacci == 2) The desired Fibonacci number is the second Fibonacci number; copy the value of previous2 into current Algorithm (cont d.) else calculate the desired Fibonacci number as follows: Start by determining the third Fibonacci number Initialize counter to 3 to keep track of the calculated Fibonacci numbers. Calculate the next Fibonacci number, as follows: current = previous2 + previous1; 29 30 Fall-2015 5

Algorithm (cont d.) (cont d.) Assign the value of previous2 to previous1 Assign the value of current to previous2 Increment counter Repeat until Fibonacci number is calculated: while (counter <= nthfibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; } Algorithm (cont d.) Output the nthfibonacci number, which is current 31 32 Structure for loop: called a counted or indexed for loop Syntax of the for statement: The initial statement, loop condition, and update statement are called for loop control statements 33 34 35 36 Fall-2015 6

The following is a semantic error: The following is a legal (but infinite) for loop: for (;;) cout << "Hello" << endl; 37 38 Structure Syntax of a do...while loop: The statement executes first, and then the expression is evaluated As long as expression is true, loop continues To avoid an infinite loop, body must contain a statement that makes the expression false 39 40 The statement can be simple or compound Loop always iterates at least once 41 42 Fall-2015 7

43 44 Choosing the Right Looping Structure All three loops have their place in C++ If you know or can determine in advance the number of repetitions needed, the for loop is the correct choice If you do not know and cannot determine in advance the number of repetitions needed, and it could be zero, use a while loop If you do not know and cannot determine in advance the number of repetitions needed, and it is at least one, use a do...while loop break and continue Statements break and continue alter the flow of control break statement is used for two purposes: To exit early from a loop Can eliminate the use of certain (flag) variables To skip the remainder of a switch structure After break executes, the program continues with the first statement after the structure 45 46 break and continue Statements (cont d.) Nested Control Structures continue is used in while, for, and do while structures When executed in a loop It skips remaining statements and proceeds with the next iteration of the loop To create the following pattern: * ** *** **** ***** We can use the following code: for (i = 1; i <= 5 ; i++) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } 47 48 Fall-2015 8

Nested Control Structures (cont d.) What is the result if we replace the first for statement with this? Answer: for (i = 5; i >= 1; i--) ***** **** *** ** * Avoiding Bugs by Avoiding Patches Software patch Piece of code written on top of an existing piece of code Intended to fix a bug in the original code Some programmers address the symptom of the problem by adding a software patch Should instead resolve underlying issue 49 50 Debugging Loops Summary Loops are harder to debug than sequence and selection structures Use loop invariant Set of statements that remains true each time the loop body is executed Most common error associated with loops is off-by-one C++ has three looping (repetition) structures: while, for, and do while while, for, and do are reserved words while and for loops are called pretest loops do...while loop is called a posttest loop while and for may not execute at all, but do...while always executes at least once 51 52 Summary (cont d.) Summary (cont d.) while: expression is the decision maker, and statement is the body of the loop A while loop can be: Counter-controlled Sentinel-controlled EOF-controlled In the Windows console environment, the end-of-file marker is entered using Ctrl+z for loop: simplifies the writing of a countercontrolled while loop Putting a semicolon at the end of the for loop is a semantic error Executing a break statement in the body of a loop immediately terminates the loop Executing a continue statement in the body of a loop skips to the next iteration 53 54 Fall-2015 9