Chapter 3 Problem Solving and the Computer

Similar documents
Control Structures. Flowchart Symbols

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.

REPETITION CONTROL STRUCTURE LOGO

Chapter 1 INTRODUCTION

BITG 1233: Introduction to C++

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

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 4 - Notes Control Structures I (Selection)

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

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

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

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Add Subtract Multiply Divide

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

2 nd Week Lecture Notes

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

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

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

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

Programming. C++ Basics

WARM UP LESSONS BARE BASICS

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Introduction to Programming

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

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

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

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

Fundamentals of Programming CS-110. Lecture 2

Introduction to Programming EC-105. Lecture 2

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

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

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

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

download instant at Introduction to C++

UNIT- 3 Introduction to C++

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

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

Loops and Files. of do-while loop

Objectives. In this chapter, you will:

A Freshman C++ Programming Course

Why Is Repetition Needed?

Computer Programming : C++

LAB: INTRODUCTION TO FUNCTIONS IN C++

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

Chapter 6 Pointers and Arrays

Chapter 2 - Control Structures

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

REVIEW. The C++ Programming Language. CS 151 Review #2

C++ Final Exam 2017/2018

Lab ACN : C++ Programming Exercises

Loops / Repetition Statements

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

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

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

A First Program - Greeting.cpp

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Introduction to the C++ Programming Language

3 The L oop Control Structure

Lecture 3 Tao Wang 1

The C++ Language. Arizona State University 1

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Chapter 7 Arithmetic

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Example 3. #include <iostream> using namespace std; int main()

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

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

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)

CHAPTER 3 BASIC INSTRUCTION OF C++

The births of the generations are as follow. First generation, 1945 machine language Second generation, mid 1950s assembly language.

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Subject: Computer Science

CS242 COMPUTER PROGRAMMING

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Chapter 2: Overview of C++

C/C++ Programming Lecture 7 Name:

Chapter 3 - Functions

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

CS101 PLEDGED SPRING 2001

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

PROGRAMMING EXAMPLE: Checking Account Balance

Chapter 2 C++ Fundamentals

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

IT 1033: Fundamentals of Programming Data types & variables

Review of Important Topics in CS1600. Functions Arrays C-strings

Increment and the While. Class 15

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ Programming: From Problem Analysis to Program Design, Third Edition

Transcription:

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 algorithm in a programming language. Before a programmer can write a program to solve a problem or to perform a task, he or she must first determine an algorithm to solve that problem or to perform that task. This chapter discusses computer problem solving methodologies and how these methodologies are used to solve and specify the solutions of some standard problems in computer science. 3.1 Program Development The development of a program to perform a task or to solve a problem is in general performed in six steps. These steps are organized into four phases: 1. the requirements analysis phase 2. the design phase 3. the implementation phase and 4. the testing phase We will use the following simple programming problem to discuss all these steps. Given that the circumference of a circle is 2 * * r, and that its area is * r * r, where r is its radius and is the constant value 3.14, write a C++ program to read the radius of a circle, and to compute its perimeter and area. Requirements Analysis Phase (Steps 1 and 2) Step 1: you analyze the problem or the task in order to determine the desired result(s) or the output items that the program must produce. For our sample programming problem, the objective is to compute the circumference and the area of the circle. The output items are therefore: the circumference of the circle (identified as circumf ) the area of the circle (Identified as area) Step 2: you analyze the problem or the task in order to determine the data items (input or constants) that will be processed in order to produce the desired result(s) or output items. For our sample programming problem, the input item is the radius of the circle (identified as radius). 2017 Gilbert Ndjatou Page 59

Design Phase (Steps 3 and 4) Step 3 1. You design an algorithm for transforming the data items (input or generated) into the desired result(s) or output. 2. You specify the algorithm either in a programming language, using a pseudo-code, or using a flowchart. For our sample programming problem, the algorithm is specified in pseudo-code as follows: 1. Read the radius of the circle into variable radius. 2. Calculate the circumference of the circle as follows: circumf = 2 * 3.14 * radius 3. Calculate the area of the circle as follows: area = 3.14 * radius * radius 4. Display the results (circumference and area). Step 4: You check the algorithm manually using specific data to make sure that it is correct. Implementation Phase (Step 5) Step 5: You write the algorithm that you have designed in step 3 in a programming language. For our sample programming problem, the program is provided in Figure 3.1 Testing Phase (Step 6) Step 6: You test the program (using selected test data) to verify that it works correctly, and that it also fulfills its requirements. 2017 Gilbert Ndjatou Page 60

Figure 3.1 /************************************************************************ Program to read the radius of a circle and to compute its circumference and area. ************************************************************************/ #include <iostream> #include <iomanip> using namespace std; int main() { cout << setprecision(2) << fixed << showpoint; const double PI = 3.14; // holds the value of PI double radius, // to hold the radius of a circle circumf, // to hold its circumference area; // to hold its area /*-----------------read the radius of the circle---------------*/ cout << \nenter the radius of the circle:\t ; cin >> radius; /*--------------compute its circumference----------------------*/ circumf = 2 * PI * radius; /*---------------compute its area -----------------------------*/ area = PI * radius * radius; } /*-------------- print its circumference and area--------------*/ cout << endl << The circumference of the circle is:\t << circumf << endl << and its area is:\t << area; return( 0 ); 2017 Gilbert Ndjatou Page 61

Algorithm, Flowchart, and Pseudo-code The basic operations of a C/C++ programming language are specified using the following statements or structures: the input statement the output statement the assignment statements the single-way selection structure the two-way selection structure the multiple-way selection structure the counter-controlled iteration structure, and the logically-controlled iteration structure. These statements and structures are specified in pseudo-code using English language-like statements: The input statement may be specified using an English-like statement with the keyword read. The output statement may be specified using an English-like statement with the keyword write. The assignment statement may be specified using an English-like statement with the keyword compute or calculate. They may also be specified using the flowchart symbols in Figure 3.2: The input statement is specified by using symbol (b) in which the keyword read is inserted along with the names of the variables where values should be read. The output statement is specified by using symbol (b) in which the keyword write is inserted along with the expressions whose values should be printed. The assignment statement is specified by using symbol (c) in which a C++ like assignment statement is inserted. 2017 Gilbert Ndjatou Page 62

Figure 3.2 Flowchart Symbols SYMBOL NAME DESCRIPTION (a) Terminal Indicates the beginning or the end of an algorithm. (b) (c) Input/Output Process Indicates an input or an output operation. Indicates a computation or a data manipulation. (d) (e) Flow Lines Decision Used to connect the symbols and to indicate the logic flow. Indicates a decision point in an algorithm. (f) Connector Indicates an entry or an exit from another part of the flowchart. The specification of the above algorithm using a Flowchart is provided in Figure 3.3. 2017 Gilbert Ndjatou Page 63

Figure 3.3 Algorithm to read the radius of a circle, and to calculate its circumference and area Input: Output: the radius of the circle its circumference and area Variables: radius (double) to hold the radius of the circle circumf (double) to hold its circumference area (double) to hold its area Start Read radius circumf = 2 * 3.14 * radius area = 3.14 * radius * radius circumf, area Stop Exercise 3.1* a. Specify an algorithm (in pseudo-code and using a flowchart) to read the width and the length of a rectangle and to calculate its perimeter and area. b. the C++ code segment that corresponds to the algorithm in part a. Exercise 3.2 In the division of a positive integer value by 10, the quotient is the same number without the right-most digit (for example, 345 / 10 = 34) and the remainder is the right-most digit (for example, 345 % 10 = 5). a. Specify an algorithm (using a flowchart) to read a 3-digit positive integer value, and to output its digits in reverse order (for example, if the integer value is 345, the output will be 5 4 3). b. the C++ program segment that corresponds to the algorithm in part a. 2017 Gilbert Ndjatou Page 64

3.3 Logical Expressions The specification of each of the programming language structures above involves a test that the CPU must first performs on a logical expression (also referred to as a condition). We will therefore discuss logical expressions before we can discuss these structures. A logical expression (or condition) is an expression that evaluates to either true or false. There are two types of conditions: simple conditions and Compound conditions. Simple Conditions A simple condition has the following syntax: <arithmetic expression> <relational operator> <arithmetic expression> Relational Operators C/C++ Symbol Meaning < is less than > is greater than == is equal to <= is less than or equal to >= is greater than or equal to!= is not equal to Evaluations of simple conditions Assuming that the variables are defined and initialized as follows: int num1 = 5, num2 = 7, num3 = 2; float fnum = 11.75; char ch = K ; Evaluate the following conditions: a) num1 >= 5 d) num2 + 3 == num3 * 4 b) fnum + 7.2!= fnum / 2 e) 3 * num1 + 4 < num3 * 2 c) fnum * 2 > num1 + 20 f) A <= ch 2017 Gilbert Ndjatou Page 65

Solutions a) num1 >= 5 d) num2 + 3 == num3 * 4 5 >= 5 7 + 3 == 2 * 4 10 == 8 b) fnum + 7.2!= fnum / 2 e) 3 * num1 + 4 < num3 * 2 11.75 + 7.2!= 11.75 / 2 3 * 5 + 4 < 2 * 2 18.95!= 5.875 19 < 4 c) fnum * 2 > num1 +20 f) A <= ch 11.75 *2 > 5 + 20 A <= K 13.75 > 25 Characters are ordered according to their ASCII code representations: 0' < 1' < 2' <... < 9' < A <... < Z < a... < z. Relational operators have a lower precedence than arithmetic operators: o In the absence of parentheses, arithmetic operations are evaluated before any relational operation is evaluated. However, it is a good programming practice to use parentheses to clarify the meaning of logical expressions. For example: (fnum * 2) > (num1 + 20) Exercise 3.3* Assuming that the variables are defined and initialized as follows: int num1 = 9, num2 = 5, num3 = 10; float fnum = 12.50; char ch = P ; Evaluate the following conditions: a. num1 <= 5 b. 3 * num1 + 4 < num3 * 2 c. 3 * num2 > fnum + 2 d. 2 * num1 + 12 == 3 * num3 e. num1 + 3!= num1 * 4 f. ch M == 5 2017 Gilbert Ndjatou Page 66

Compound Conditions A compound condition is built from simple conditions and logical operators. Logical Operators C++ Symbol Meaning Evaluation && AND <condition1> && <condition2> is true if and only if both conditions are true OR <condition1> <condition2> is true if and only if at least one of the two conditions is true! NOT!<condition> is true if and only if <condition> is false Evaluations of compound conditions Tue && && && && short-circuit evaluation There is a short-circuit evaluation of a compound condition when you do not have to evaluate the right-most condition in order to get the true value of the compound condition: and Therefore - Also, && and && Therefore && - Exercise 3.4* Assuming that the variables are defined and initialized as follows: int num1 = 5, num2 = 7, num3 = 2; float fnum = 11.75; char ch = K ; Compute the true value of each of the following compound conditions: a) num1 >= 5 num2 + 3 == num3 d) num2 + 3 == num3 * 4 ch >= Z b) A <= ch && fnum + 7.2!= 2.5 e) num1 < 3 && num2 > num3 c)!(3 * num1 + 4 < num3 * 2) f)!(fnum * 2 < num1 + 20) 2017 Gilbert Ndjatou Page 67

Solutions a) num1 >= 5 num2 + 3 == num3 d) num2 + 3 == num3 * 4 ch >= Z 5 >= 5 7 + 3 == 2 * 4 K >= Z 10 == 8 b) A <= ch && fnum + 7.2!= 2.5 e) num1 < 3 && num2 > num3 A <= K && 11.75 + 7.2!= 2.5 5 < 3 && && 18.95!= 2.5 && c)!(3 * num1 + 4 < num3 * 2) f)!(fnum * 2 < num1 + 20)!( 3 * 5 + 4 < 2 * 2)!(11.75 * 2 < 5 + 20)!( 19 < 4)!( 23.50 < 25)!! In the evaluation of an expression, operators with higher precedence are evaluated before those with lower precedence. Operators with the same precedence are evaluated in the order specified in the order of evaluation column. Precedence of C/C++ Operators Operator Order of Evaluation Precedence! Unary right to left 7 * / left to right 6 % + - left to right 5 < <= > left to right 4 <= == left to right!= 3 && left to right 2 left to right 1 2017 Gilbert Ndjatou Page 68

Accuracy of Floating-Point Values The fact that floating-point values are approximated inside a computer makes it difficult to test for the equality of floating-point values. For example, if the variable fnum is defined as follows: float fnum = 7.1; Then, the condition: fnum / 2 == 3.55 may not be true. The problem may be solved by assuming that two floating-point values are equal if their difference is relatively very small. This is done by testing if the absolute value of their difference is less than a certain value chosen by the programmer (for example 0.000001). Using the library function fabs() that takes as argument a floating-point value and returns its absolute value, the condition: value1 == value2 is replaced with the condition: fabs(value1 - value2) < 0.000001 which tests whether the difference between the two values is small enough so that we can make them equal. Evaluation of and In the C/C++ programming language, false is represented by the integer value 0, and any value other than 0 represents true. Therefore, the following two conditions have the same true value (are equivalent): Conditions value!= 0 and value (Saying that value is not zero is the same thing as saying that value is true) Conditions value == 0 and! value (Saying that value is zero is the same thing as saying that!value is true) bool Data Type A variable with data type bool can only hold the bool values true and false. Examples: bool flag = true; bool condvalue = false, HighTemperature, ExtremeTemperature; double temperature; HighTemperature = false; cin >> temperature; HighTemperature = (temperature >= 120) ExtremeTemperature = (HighTemperature (temperature <= -20); 2017 Gilbert Ndjatou Page 69

Exercise 3.5 A. Assuming that the variables are defined and initialized as follows: int num1 = 9, num2 = 5, num3 = 10; float fnum = 12.50; char ch = P ; Evaluate the following conditions (using short circuit evaluation whenever possible): a. 2 * num1-5 >= 9 fnum / 2 + 10 <= 6.5 b. num1 + num2 == num3 + 5 && 2 * num3 <= 4 * num2 c.! (num1 + 5 <= 13) d. 3 * num1 > num1 + num2 && num1+ 3 >= 12 e.! ( num3 % 4 < 3) f. num1-5 >= num3 num2 < 15 && num1 >= 9 B. Which of the following conditions are equivalent (that means have the same true value)? a. num1!= 0 b.!num1 c. num1 == 0 d.!(num1 == 0) e. num1 C. Suppose that a person s age is stored in the variable age, his number of children in the variable NumChild, his salary in the variable salary, and his height in the variable height. relational expressions to specify the following conditions: a. he is 45 year old. b. he is more than 5.7 feet tall. c. his salary is between 35,000 and 50,000. d. he does not have 3 children. h. he is either 6.0 feet tall, or he has less than 4 children. j. he is not older that 35 and he has 2 or 3 children 2017 Gilbert Ndjatou Page 70

3.4 Two-Way Selection using the if-else Structure The solution of some problems requires the CPU to test a condition and to select the action to be performed based on whether or not that condition is true. Example: Suppose that at a party, you serve alcohol drinks only to guests who are 21 or older, and a juice to guests who are less than 21. When a guest comes to get a drink, you first test his age: if he is 21 or older, you serve him an alcohol drink; otherwise you serve him a juice. The solutions of these types of problems are written using a two-way selection structure which is specified using a flowchart as follows: Condition F-Statement T-Statement Next-Statement It says to do the following: Test condition a. if it is true, perform the actions (T-Action) specified by T-Statement, b. otherwise, perform the actions (F-Action) specified by F-Statement. Next-Statement is the statement that says what to do after any of the actions (F-Action or T-Action) above has been executed. 2017 Gilbert Ndjatou Page 71

A two-way selection structure may be specified using pseudo-code as follows: 1. If <condition> is true, do the following: <T-Statement> 2. Otherwise, do the following: <F-Statement> 3. <Next-Statement> It is specified in C++ using the if - else structure as follows: if (<condition>) <T-statement> else <F-statement> <Next-Statement> <T-statement> is a single statement that specifies the T-Action <F-statement> is a single statement that specifies the <F-Action>. Case Study 3.1 Problem Statement a program to read the age of an individual, and to output the message serve alcohol drink if he is 21 or older, and the message serve juice otherwise. Your program will then output the message thank you for using this program. Program Logic output: Input: Serve alcohol or Serve Juice, depending on the individual s age. an individual s age. Variables: age (int) to hold an individual s age. Algorithm Specification (using Pseudo-code) 1. Read the individual s age into variable age. 2. If this individual s age is 21 or more, do the following: 2.a. output the message serve alcohol drink. 3. Otherwise, do the following: 3.a. output the message serve juice. 4. Output the message thank you for using this program. 2017 Gilbert Ndjatou Page 72

Algorithm Specification (using a Flowchart) start Read age serve a juice age >= 21 serve alcohol drink Thank you for Using this program Stop Figure 3.4 Using the if-else Structure /************************************************************************* Program to read the age of an individual and to output the type of drink that he should be served *************************************************************************/ #include <iostream> using namespace std; #define DRINKAGE 21 int main() { int age; } // to hold an individual s age /*----------------- read the individual s age------------------------*/ cout << \n\nenter the individual s age please:\t ; cin >> age; /*--------determine what type of drink he should be served ---------*/ if (age >= DRINKAGE) // he is over the drinking age cout << endl << Serve alcohol drink ; else // he can not drink alcohol cout << endl << Serve juice ; cout << endl << Thank you for using this program ; return (0); 2017 Gilbert Ndjatou Page 73

Exercise 3.6* a. Specify an algorithm (in pseudo-code and using a flowchart) to read a nonzero integer value and to determine if it is positive or negative. If it is positive, print it with the message POSITIVE, otherwise, print it with the message NEGATIVE. At the end, print the message Thank You. b. the C++ code segment that corresponds to the algorithm in part a. Exercise 3.7* a. Specify an algorithm (using a flowchart) to read a character value and to determine if it is a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). If it is, print it with the message DIGIT ; otherwise print it with the message NOT A DIGIT. b. the C++ code segment that corresponds to the algorithm in part a. Exercise 3.8 a. Specify an algorithm (using a flowchart) to read a character and to determine if it is a letter of the alphabet. If it is a letter of the alphabet, print it with the message, it is a letter otherwise, print it with the message, it is not a letter. b. the C++ code segment that corresponds to the algorithm in part a. Case Study 3.2 Problem Statement a program to read a positive integer value and to determine if it is even or odd. If it is even, print it with the message EVEN ; otherwise, print it with the message ODD. Program Logic Output: Input: Variable: Note: the input value with the message EVEN or ODD, depending on whether the input value is even or odd. an integer value. num (int) to hold the input value. An integer value is even if the remainder in its division by 2 is 0; otherwise, it is odd. Algorithm Specification (using Pseudo-code) 1. Read a positive integer value into the variable num. 2. If num % 2 is 0, then do the following: 2.a print the input value with the message EVEN. 3. Otherwise do the following: 3.a print the input value with the message ODD 2017 Gilbert Ndjatou Page 74

Algorithm Specification (using a Flowchart) Start Read num num % 2 = 0 num, odd num, even Stop Figure 3.5 Using the if - else Structure /************************************************************************ Program to read an integer value and to determine if it is even or odd ************************************************************************/ #include <iostream> using namespace std; int main() { int num; } // to hold the value read /*---------------- read in an integer value--------------------------*/ cout << \n\nenter an integer value please:\t ; cin >> num; /*----------------determine if it is even or odd --------------------*/ if (num %2 == 0) // it is even cout << endl << num << \teven ; else // it is odd cout << endl << num << \todd ; return ( 0 ); Exercise 3.9* a. Specify an algorithm (using a flowchart) to read an integer value and to determine if it is a multiple of 5. If it is a multiple of 5, print it with the message MULTIPLE OF 5, otherwise, print it with the message NOT MULTIPLE OF 5. b. the C++ code segment that corresponds to the algorithm in part a. 2017 Gilbert Ndjatou Page 75

Compound Statement A compound statement has the following syntax: Example { } { } (One or more statements to be executed as a block) num2 = num1 + 5; num1 = num1 +1; The statements of a compound statement are executed one after another, starting with the first one in the sequence. A compound statement may appear anywhere in a C++ program where a single statement may appear. If you have to specify two or more statements as the T-statement or the F-statement of an if-else structure, these statements must be specified as a compound statement. Examples if(num1 > num2) { num2 = num1 + 5; num1 = num1 +1; } else num1 = num2-5 ; if(num1 < num2) num2 = num1 + 4; else { num2 = num1 + 5; num1 = num1 +1; } Case study 3.3 Problem Statement a program to read an integer value and to do the following: If the value read is zero, print it with the message INVALID DIVISOR. Otherwise read a second value and then compute and print the quotient and the remainder in the division of the second value by the first. At the end write the message Thank you for using this program. 2017 Gilbert Ndjatou Page 76

Program Logic Output: Input: Variables: the quotient and the remainder in the division of the second value by the first or the message 0 is invalid divisor depending on the input. one or two integer values, depending on the value of the first. divisor (int) to hold the first value. dividend (int) to hold the second value. Note: The second value is input and the quotient and the remainder in the division of the second value by the first are computed only if the first value is not zero. Algorithm Specification (using a Flowchart) Start Read divisor divisor == 0 Read dividend dividend / divisor dividend % divisor divisor invalid divisor Thank you Stop 2017 Gilbert Ndjatou Page 77

Algorithm Specification (using Pseudo-Code) 1. Read the first value into variable divisor. 2. If the value read is zero (divisor == 0), do the following; 2.a write the value read (0) with the message INVALID DIVISOR 3. Otherwise do the following: 3.a read the second value into variable dividend. 3.b write the quotient of second value divided by the first: dividend / divisor 3.c write the remainder of the second value divided by the first: dividend % divisor 4. the message Thank you for using this program. The program is provided in figure 3.6. Figure 3.6 Using a Compound Statement in an if-else Structure /************************************************************************* Program to read two integer values and to compute the quotient and the remainder in the division of the second value by the first. *************************************************************************/ #include <iostream> using namespace std; int main() { int divisor, dividend; // to hold the first value // to hold the second value /*---------------------- read in the divisor-----------------------*/ cout << \n\nenter the divisor please:\t ; cin >> divisor; } /*-----read the dividend and compute the quotient and the remainder--*/ if (divisor == 0) // it is invalid cout << endl << divisor << \tis INVALID DIVISOR ; else { cout << \n\nenter the dividend please:\t ; cin >> dividend; cout << \nthe quotient in the division of:\t << dividend << by << divisor << \tis:\t << (dividend / divisor); cout << \nand the remainder is:\t << (dividend % divisor); } cout << \n\nthank you for using this program ; return( 0 ); 2017 Gilbert Ndjatou Page 78

Exercise 3.10* Assuming that all variables are properly defined and initialized, what are the error(s) in each of the following program segments? a. cin >> num; if (num = 5) sum = num + 4; else sum = num + 10; b. cin >> num; if (num > 5 && <= 10) cout << (num + 15); else cout << (num - 3); c. cin >> num; if (num < 15) result1 = 2 * num; result2 = num + 20; else result1 = 5 * num; result = result1 + result2; cout << \nthe result is:\t << result; Exercise 3.11* Trace the execution of the following program segment and show its output for each of the following input values: a. input: 4 b. input: 20 Line # Statements 1 cin >> num; 2 if (num <10 ) { 3 num = num + 6; 4 cout << endl << num =\t << num; } else 5 cout << endl << num / 4 =\t << (num / 4); 6 cout << endl << result =\t << (2 * num); 2017 Gilbert Ndjatou Page 79

Exercise 3.12 a. Specify an algorithm (using a flowchart) to read an integer value into variable num1and another integer value into variable num2 and to do the following: if the value in variable num1 is greater than the value in variable num2 do the following: add 1 to the value in num1 and 5 to the value in num2 and then print the result of the product of the new value in num1 and the new value in num2; otherwise, do the following: subtract 1from the value in num1 and 5 from the value in num2 and then print the result of the product of the new value in num1 and the new value in num2. b. the C++ code segment that corresponds to the algorithm in part a. Exercise 3.13 a. A department store offers a rebate of 5% if the total price of the purchase is at least 100 and a rebate of 2% otherwise. A sale tax of 8.25 % is also imposed on the total price of each purchase (after the rebate). Specify an algorithm (using a flowchart) to read the unit price and the number of items purchased, and to output the amount of the rebate and the (total) price (plus taxes) of the purchase. b. the C++ code segment that corresponds to the algorithm in part a. 2017 Gilbert Ndjatou Page 80

3.5 Counter-Controlled Iteration using the while Structure The solution of some problems requires the CPU to repeat the execution of one or more statements a set number of times. Example: Suppose that a candy bar costs 70 cents in a candy machine that only accepts dimes. To buy a candy bar from this machine, a user has to deposit a dime in the machine seven times. The solutions of these types of problems are written using a counter-controlled iteration (or loop) which is specified using a flowchart as follows: counter = initial-value Counter < final-value Body-of-the-Loop Next-Statement Body-of- the- Loop counter Next-Statement Initial/Final Value consists of the statements whose executions are repeated by the CPU. is called the loop counter it is a variable that is used to hold the number of repetitions is the first statement to be executed after the repetitions. If the initial value is 0 (no execution is done yet), then the final value must be the number of executions. If the initial value is 1 (one execution is about to be done), then the final value must be the number of execution plus 1. Loop Increment After each execution of the body-of-the-loop, the loop counter must be updated to reflect the number of executions. The statement that you use to update the loop counter is called the loop increment. The loop increment is a statement in the body-of-the-loop. 2017 Gilbert Ndjatou Page 81

Algorithm of the Candy Bar Machine (using a flowchart) Start total = 0 count = 0 count < 7 Read coin total = total + coin count = count + 1 Thank you Stop Specification of a Counter-Controlled Iteration in Pseudo-Code A counter-controlled iteration may be specified in pseudo-code as follows: 1. Set the loop-counter to the initial-value. 2. As long as the loop-counter is less than the final-value, do the following: <Body-of-of the-loop (including the increment-statement)> 3. Execute the next operation. 2017 Gilbert Ndjatou Page 82

Algorithm of the Candy Bar Machine (in pseudo-code) 1. Set the total value of the coins to 0: total = 0. 2. Set the loop counter to 0: count = 0. 3. As long as the loop counter is less than 7, do the following: 3.a. read the value of the coin into the variable coin. 3.b. add the value of the coin read into the total value: total = total + coin. 3.c. increment the loop counter by 1: count = count + 1. 4. Thank You Specification of a Counter-Controlled Iteration in C++ A counter-controlled iteration may be specified in C++ using the while structure as follows: counter = initial-value; while (counter < final-value) { <Body-of-of the-loop (including the increment-statement)> } <Next-statement> Algorithm of the Candy Bar Machine (in C++) int total, coin, count; // to hold the total value of the coins // to hold the value of a coin // to hold the number of repetitions total = 0; count = 0; while ( count < 7 ) { cin >> coin; total = total + coin; count = count + 1; } cout << endl << Thank You ; 2017 Gilbert Ndjatou Page 83

Case Study 3.4 Problem Statement a program to read 30 weight measurements in pounds and to convert them into kilograms. Note that 1 Lb =.454 Kg. Program Logic Notes: Input: Output: 30 weight measurements (in Lbs). 30 weight measurements (in Kgs). We use the variable count as the loop counter: Its initial value is 0 (no weight measurement is read so far) and Its final value is 30 (30 weight measurements are already read) Variables: count (int) pound (double) to count the weight measurements. Initial value is 0 - Final value is 30. to hold a weight measurement in Lbs. Algorithm Specification (using Pseudo-code) 1. Set the loop counter (count) to 0: count = 0 2. As long as the current value of the loop counter (count) is less than 30, do the following: 2.a read a weight measurement into the variable pound. 2.b convert it to kilogram and print the result. 2.c increment the loop counter by 1: count = count + 1 3. Thank you. The flowchart follows and the program is provided in figure 3.7. 2017 Gilbert Ndjatou Page 84

Algorithm Specification (using a flowchart) Start count = 0 count < 30 Read pound.454 * pound count = count + 1 Thank you Stop 2017 Gilbert Ndjatou Page 85

Figure 3.7 Counter-Controlled Iteration using the while Structure Line Number 1 /********************************************************** 2 Program to read 30 weight measurements in pounds and convert 3 them into kilograms 4 **********************************************************/ 5 #include <iostream> 6 #include <iomanip> 7 #define MAXCOUNT 30 8 #define COEFICIENT.454 9 10 int main() 11 { 12 int count; // to count weight measurements 13 double pound, // the current weight measurement in Lbs 14 15 cout << setprecision(2) << fixed << showpoint; 16 17 /*read weight measurements (Lb) and convert them to kg*/ 18 count = 0; // no weight measurement is read so far 19 while (count < MAXCOUNT) // repeat thirty times 20 { 21 cout << \nenter a weight measurement please:\t ; 22 cin >> pound; 23 cout << \t = << (.454 * pound); 24 count = count + 1; 25 } 26 27 cout << endl << Thank you ; 28 return (0); 29 } The body of the loop consists of the statements in line 21 to line 24. The loop-counter is initialized in line 18; and the loop-increment statement is in line 24. 2017 Gilbert Ndjatou Page 86

Exercise 3.14* 1. Assuming that all variables are properly defined, indicate what is wrong with each of the following while structures: a. b. c. while( count < 10 ) while(count < 10) count = 0; { { while(count < 10 ) cin >> num; count = 0; { cout << 2 * num; cin >> num; cin >> num; count = count + 1; cout << 2 * num; cout << 2 * num; } count = count + 1; } } Exercise 3.15 a. Specify an algorithm (in pseudo-code and using a flowchart) to read 50 temperature values in Fahrenheit and to convert them to Celsius. You convert a Fahrenheit temperature to Celsius by using the following formula: Celsius = 5.0 / 9 (Fahrenheit - 32). b. the C++ code segment that corresponds to the algorithm in part a. Using a Running Total A running total is a variable that is used to compute the sum of values processed at each iteration of a loop: it is first initialized to 0 and each new value processed in the loop is added to the previous total. Case Study 3.5 Problem Statement a program to read 20 integer values and to compute their sum. Program Logic Input: 20 integer values. Output: their sum. Variable: count (int) to count the values. Initial value is 0 (no value is read so far); Final value is 20. value (int) to hold the integer value read. totalvalue (int) to hold the sum of the integer values read so far: Initial value is 0. 2017 Gilbert Ndjatou Page 87

Algorithm Specification (using Pseudo-code) 1. Set the running total value (totalvalue) to 0: totalvalue = 0 2. Set the loop counter (count) to 0: count = 0 3. As long as the current value of the loop counter (count) is less than 20, do the following: 3.a read an integer value into the variable value. 3.b add the integer value read to the running total value: totalvalue = totalvalue + value 3.c add 1 to the loop counter (count): count = count + 1 4. Print the sum of all values The flowchart follows and the program is provided in figure 3.8. Algorithm Specification (using a Flowchart) Start totalvalue = 0 count = 0 count < 20 Read value totalvalue = totalvalue + value totalvalue count = count + 1 Stop 2017 Gilbert Ndjatou Page 88

Figure 3.8 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read twenty integer values and to compute their sum. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 #define MAXCOUNT 20 7 8 int main() 9 { 10 int count; // to count values 11 value, // to hold the value read 12 totalvalue; // the hold the sum of the values read so far 13 14 /*------read all values and compute their sum-------*/ 15 totalvalue = 0; 15 count = 0; // no value has been read so far 16 while (count < MAXCOUNT) // repeat twenty times 17 { 18 cout << \nenter an integer value please:\t ; 19 cin >> value; 20 totalvalue = totalvalue + value; 21 count = count + 1; 22 } 23 24 /*-----print the sum of all the values read----------*/ 25 cout << \n\nthe sum of all the values read is:\t 26 << totalvalue; 27 return (0); 28 } Exercise 3.16* Each of the following two code segments is supposed to read and to compute the sum of 10 integer values. Assuming that all variables are properly defined, indicate what is wrong with each of them. a. b. count = 0; count = 0; while (count < 10 ) while (count < 10 ) { { sum = 0; cin >> num; cin >> num; sum = sum + num; sum = sum + num; count = count + 1; count = count + 1; } } 2017 Gilbert Ndjatou Page 89

Exercise 3.17* a. Specify an algorithm (using a flowchart) to read the test scores of twenty students and to compute and print their average. b. a C++ code segment that corresponds to the algorithm in part a. Exercise 3.18 a. A client has purchased 20 products in a store. Specify an algorithm (using a flowchart) to read the unit price and the number of items of each product and to compute and print the total price of all these products. b. a C++ code segment that corresponds to the algorithm in part a. Case Study 3.6 Problem Statement a program to compute the sum of the first 20 positive even integer values (2, 4,...). Program Logic Input: none. Output: the sum of the first 20 positive integer values. Variable: count (int) to count the values: Initial value is 1; Final value is 21. totalvalue (int) to hold the sum of the integer values processed so far: Initial value is 0. Algorithm Specification (using Pseudo-code) 1. Set the running total value (totalvalue) to 0: totalvalue = 0 2. Set the loop counter (count) to 1: count = 1 3. As long as the current value of the loop counter (count) is less than 21, do the following: 3.a multiply the loop counter by 2 and add the result to the running total value: totalvalue = totalvalue + 2 * count 3.c add 1 to the loop counter (count): count = count + 1 4. Print the sum of all values The flowchart follows and the program is provided in figure 3.9. 2017 Gilbert Ndjatou Page 90

Algorithm Specification (using a Flowchart) Start totalvalue = 0 count = 1 totalvalue Stop count < 21 totalvalue = totalvalue + 2 * count count = count + 1 Figure 3.9 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read twenty integer values and to compute their sum. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 #define MAXCOUNT 21 7 int main() 8 { 9 int count, // to count the values 10 totalvalue; // the hold the sum of the values so far 11 totalvalue = 0; 12 count = 1; 13 while (count < MAXCOUNT) // repeat twenty times 14 { 15 totalvalue = totalvalue + 2 * count; 16 count = count + 1; 17 } 18 /*-----print the sum of the first 20 positive even values ---*/ 19 cout << \n\nthe sum of the first 20 positive even values is:\t 20 << totalvalue; 21 return (0); 22 } 2017 Gilbert Ndjatou Page 91

Exercise 3.19 a. Specify an algorithm (using a flowchart) to compute and print the sum of the first 10 positive multiple of 5. b. a C++ code segment that corresponds to the algorithm in part a. Using a Running Product and a Counter with the initial value Greater than the final Value A running product is a variable that is used to compute the product of values processed at each iteration of a loop: it is first initialized to 1 and each new value processed in the loop is multiplied to it. Case Study 3.7 Problem Statement For a positive integer value n, n factorial (written n!) is the product of all the integer values from 1 to n (1 * 2 * 3 *... * n). a program to read a positive integer value n, and to compute and print n! Program Logic Input: a positive integer value. Output: the product of all positive integer values less than or equal to the value read. Variables: number (int) to hold the value read factorial (int) to hold the product of the integer values: initial value = 1 After Iteration Value of number value of factorial - n 1 1 n - 1 1 x n 2 n - 2 1 x n x (n - 1)... n - 1 1 1 x n x (n - 1) x... x 2 2017 Gilbert Ndjatou Page 92

Algorithm Specification (in Pseudo-code) 1. Read a positive integer value into variable number. 2. Initialize the variable factorial to 1: factorial = 1 3. As long as the current value of variable number is greater than 1, do the following: 3.a multiply the current value of variable factorial by the current value of variable number: 3.b subtract 1 from the current value of variable number: number = number-1 4. Print the result. The flowchart follows and the program is provided in figure 3.10. Algorithm Specification (using a Flowchart) Start Read number factorial = 1 number > 1 Factorial = factorial * number number = number - 1 factorial Stop 2017 Gilbert Ndjatou Page 93

Figure 3.10 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read a positive integer value and to compute and print its factorial. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 { 8 int number, //integer value/loop counter 9 factorial = 1; // to hold the product 10 11 /*------------read the integer value --------------------*/ 12 cout << endl << enter a positive integer value:\t ; 13 cin >> number; 14 15 /*-------compute the factorial of the number read -------*/ 16 while (number > 1) 17 { 18 factorial = factorial * number; 19 number = number -1; 20 } 21 22 /*------------------print the factorial------------------*/ 23 cout << endl << n factorial is:\t 24 << factorial; 25 return (0); 26 } The body of the loop consists of the statements in lines 18 and 19. The loop-counter is initialized in line 13; and the loop-increment statement is in line 19. Exercise 3.20* a. Specify an algorithm (using a flowchart) to read ten integer values and to compute and print their product. b. the C++ code segment that corresponds to the algorithm in part a. Exercise 3.21 a. Specify an algorithm (using a flowchart) to generate the squares (n*n) of the integer values 20, 18, 16, 14,... 2, starting with 20. b. the C++ code segment that corresponds to the algorithm in part a. 2017 Gilbert Ndjatou Page 94

3.6 Logically-Controlled Iteration using the while Structure The solutions of a class of problems require the CPU to repeat the execution of one or more statements as long as a certain condition is true (that means, until a certain condition becomes false). Case Study 3.7 Problem Statement A can of soda costs $ 1.00 in a soda machine, and a user buys a can of soda by depositing coins (nickels, dimes or quarters) in the machine until the total value of the coins deposited in the machine is greater than or equal to $ 1.00. a program to read the value of each coin deposited in the soda machine (5, 10, or 25) until the total value of the coins deposited in the machine is greater than or equal to 100. The program will then output the message Thank you for using the soda machine and the amount of the change. Program Logic input: the value of a coin (5, 10 or 25). Output: Note: the message Thank you for using this soda machine and the amount of change. To read the value of each coin deposited in the machine and to compute their sum, we need the following: A variable coinvalue to hold the input value of a coin. A variable totalvalue to hold the sum of the values of the coins read so far. It is initialized to 0 before the body-of-the-loop. The loop condition is: totalvalue < 100. Variables: coinvalue ( int ) totalvalue ( int ) to hold the value of a coin. to hold the total value of the coins deposited so far. Algorithm Specification (in Pseudo-code) 1. Set the total value of the coins (totalvalue) to 0. 2. As long as variable totalvalue is less than 100 do the following: 2.a read the next coin value into the variable coinvalue. 2.b add the value of the coin read to the total value of the coins: totalvalue = totalvalue + coinvalue 3. Output the message Thank you for using the soda machine. 4. Compute and print the change: totalvalue - 100 2017 Gilbert Ndjatou Page 95

Algorithm Specification (using a Flowchart) Start totalvalue = 0 totalvalue < 100 Read coinvalue totalvalue = totalvalue + coinvalue Thank you totalvalue - 100 Stop The program is provided in figure 3.11. 2017 Gilbert Ndjatou Page 96

Figure 3.11 Logically-Controlled Iteration using the while Structure Line Number 1 /***************************************************************** 2 Program to monitor the purchase of a can of soda in a soda machine 3 *****************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 { 8 const int SODAPRICE = 100; // the price of a can of soda 9 int coinvalue, // the value of a coin 10 totalvalue = 0; // the total value of the coins 11 12 while( totalvalue < SODAPRICE ) 13 { 14 /*------------read the value of the next coin------------*/ 15 cout << endl << enter the value of the next coin:\t ; 16 cin >> coinvalue; 17 18 /* compute the total value of the coins deposited so far */ 19 totalvalue = totalvalue + coinvalue; 20 } 21 22 /*--- say thank you and give the change back to the user */ 23 cout << \n\nthank you for using this soda machine 24 << \n\nyour change is:\t << (totalvalue - SODAPRICE); 25 return ( 0 ); 26 } The body-of-the-loop consists of the statements in lines 15 to 19. The loop-initialization statement is the declaration statement in lines 9 and 10; and The loop-increment statement is in line 19. Exercise 3.22* The manager of a store is required to make a deposit of $ 10,000 whenever the total sale in the store is $ 10,000 or more. a. Specify an algorithm (using a flowchart) to repeatedly read the daily sales in that store, and to compute their sum until the total sale is greater than or equal to $ 10,000. The total sale, the message it is time to make a deposit and the remaining balance (above $10, 000) are then printed. b. a C++ code segment that corresponds to the algorithm in part a. 2017 Gilbert Ndjatou Page 97

Exercise 3.23 A store has 120 bags of coffee and every day, the amount of bags sold is deducted from the current stock until it becomes less than or equal to 30. The manager of the store must then place a new order. a. Specify an algorithm (using a flowchart) to read the number of bags sold daily and to update the current stock until it becomes less than or equal to 30. The message place a new order and the amount of bags to purchase in order to have 120 bags are then printed. b. a C++ code segment that corresponds to the algorithm in part a. Case Study 3.7 Problem Statement a program to read a positive integer value and to print its digits in reverse order. That means, 4321 is printed as 1 2 3 4, and 97 is printed as 7 9. Program Logic Input: a positive integer value. Output: the digits of this integer value in reverse order. Notes: In order to read a positive integer value and to write its digits in reverse order, we need: a variable num to hold the integer value. Its digits are printed in reverse order as follows: We divide the value of variable num by 10: The remainder is the right-most digit of this value. We divide the value of variable num again by 10: The quotient is this value without its right-most digit. Example: 345 % 10 = 5 345 / 10 = 34 We now replace the current value of variable num with the above quotient All the digits of the number will be printed if we repeat the above three operations until the current value of variable num becomes 0. Variables: num ( int ) to hold the positive integer value and the successive quotients in the division by 10. 2017 Gilbert Ndjatou Page 98

Algorithm Specification (using Pseudo-Code) 1. Read the integer value into variable num. 2. As long as the value in variable num is not 0, do the following: 2.a write num % 10. 2.b set num to num / 10. Algorithm Specification (using a Flowchart) Start Read num num!= 0 num % 10 num = num / 10 Stop The program is provided in figure 3.12. 2017 Gilbert Ndjatou Page 99

Figure 3.12 Logically-Controlled Iteration using the while Structure Line Number 1 /****************************************************************** 2 Program to read a positive integer value and to print its digits in reverse order. 3 *******************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 { 8 int num; // to hold the value 9 10 /*--------------read a positive integer value--------------*/ 11 cout << \nenter an integer value greater than zero:\t ; 12 cin >> num; 13 14 /*---------- print its digits in reverse order -------------*/ 15 cout << \n\nits digits in reverse order are as follows:\t ; 16 while (num!= 0) 17 { 18 cout << ( num % 10 ); 19 num = num / 10; 20 } 21 return ( 0 ); 22 } Exercise 3.24 a. Specify an algorithm (using a flowchart) to read an integer value greater than 1 and to compute its greatest divisor that is less than the value itself. For example, if the value is 15, the answer is 5, and if the value is 13, the answer is 1. To compute the greatest divisor of an integer value n greater than 1 that is less than n, repeatedly divide that value n by i= 2, then 3, then 4,... etc., until you get a remainder of 0 or i * i> n. If the remainder is 0, then the greatest divisor is n/i, otherwise, it is 1. b. the C++ code segment that corresponds to the algorithm in part a. while Structure with one Statement in the Body-of- the-loop When the body-of-the-loop consists of just one statement, the braces may be omitted from the while structure. Problem Statement a program to compute the smallest power of 5 greater than 10000 (1, 5, 25, 125,... ). 2017 Gilbert Ndjatou Page 100

Program Logic Input: none. Output: the smallest power of 5 greater than 10000. Note: To compute the smallest power of 5 greater than 10000, we need: A variable power to hold the powers of 5. It is initialized with 1 before the body-of-the-loop. The current value of variable power is multiplied by 5 in the body-of-the-loop until it becomes greater than 10000. The loop condition is therefore: power <= 10000. After Value of Iteration variable power - 1 1 1 x 5 = 5 2 5 x 5 = 25 3 25 x 5 = 125... Variable: power (int) to hold the powers of 5. Algorithm Specification (in Pseudo-Code) 1. Set variable power to 1: power = 1 2. As long as the current value of variable power is less than or equal to 10000, do the following: 2.a Multiply the current value of variable power by 5: 3. Output the result. power = power * 5 Algorithm Specification (using a Flowchart) Start power = 1 power <= 10000 Stop Power = power * 5 The program is provided in figure 3.13. 2017 Gilbert Ndjatou Page 101

Figure 3.13 Line Number while Structure with a single statement in the body-of-the-loop 1 /*************************************************************** 2 Program to compute the smallest power of 5 greater than 10000 3 ****************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 { 8 int power; // to hold the current power of 5 9 power = 1; // first power of 5 10 while ( power <= 10000) 11 power = power * 5; 12 13 /*-----------------print the result-------------------------*/ 14 cout << endl << power 15 << is the smallest power of 5 greater than 10000"; 16 return (0); 17 } Although the body-of-the-loop consists of just one statement, it could also be specified as a compound statement as follows: while (power <= 10000) { power = power * 5; } Sentinel-Controlled Iteration When you want to process a list of values and you do not know how many values are in the list, you can use a sentinel value (dummy value, flag value, or signal value) to mark the end of the list. A sentinel value is in general chosen in such a way that they can not possibly be one of the data items in the list. Example: For a program to read and process a list of test scores received by students in an exam, a sentinel value might be -1 or -99. With -99, the list could be: 87 69 95 65 73 86 93 68-99 2017 Gilbert Ndjatou Page 102

The data items in the list are accessed and processed one at a time until the sentinel value is accessed. However, the sentinel value must not be processed. The algorithm to perform this type of repetition is specified using a flowchart as follows: Read/Access the first data item data item!= sentinel Process a data item Next-Statement Read/Access the next data item It is specified using the while structure as follows: <statement-to read/access-the first-value> While(<value-read/access!= sentinel-value>) { <processing-statements> <statement-to-read/access-the-next-value> } <processing-statements> consists of one or more statements used to process a data item in the list. Problem Statement a program to read one or more weight measurements in pounds and to convert them into kilograms. The dummy value -99.0 is entered to end the input of the weight measurements. Note that 1 Lb =.454 Kgs. 2017 Gilbert Ndjatou Page 103