scis.regis.edu ● [email protected] cs-361: estructuras de control primera clase dr. jesús borrego...

217
scis.regis.edu [email protected] CS-361: Estructuras de Control Primera Clase Dr. Jesús Borrego Lead Faculty, COS Regis University 1

Upload: joshua-alexander

Post on 27-Dec-2015

219 views

Category:

Documents


2 download

TRANSCRIPT

scis.regis.edu ● [email protected]

CS-361: Estructuras de Control

Primera Clase

Dr. Jesús BorregoLead Faculty, COSRegis University

1

Temas

•Instructor•Introducción y Guía del curso•Tarea de la primera noche•Capítulos 1-2•Actividad 1•Capítulo 3 (pp.117-148)•Instalación de DevC++•Ejemplo de programas•Tarea #1

2

InstructorDr. Jesús BorregoEducación

◦PhD MIS; MS CS; BS CS; BS EE

Ubicado:◦Colorado Springs

Casado, 5 hijosMaestro desde 1989,

a nivel de Asociado, Licenciado y Maestría

En Regis U. desde 1995

3

Introducción•Prerequisitos

▫CS 208▫Experiencia en programación no es necesaria

▫Acceso a computadora personal▫Compilador Dev C++/Code::Blocks Pueden usar otros a su propio riesgo

4

Guía de curso

•Se obtiene de la página del curso: http://academic.regis.edu/jborrego

• Trata sobre los conceptos básicos de la organización informática.

•Desarrolla una metodología precisa y lógica en la reducción de datos complejos y sin formato en formato algorítmico.

•Presenta los conceptos y metodologías de programación estructurada y el diseño.

5

Guía de curso II

•Demuestra los usos, abusos, y las mejores prácticas de las estructuras de control.

•Usamos los conceptos del lenguaje C++ para ilustrar los conceptos.

•Se recomienda DevC++ (“open source”).•Se puede usar otro compilador (no se

recomienda).

6

Materiales de instrucción

•Libro de texto• Malik, D.S. (2011). C++ Programming: From

Problem Analysis to Program Design (5a edición). Boston, MA: Course Technology/Cengage Learning; ISBN-10: 0-538-79808-4; ISBN-13: 978-0-538-79808-2.

• Compilador C++• Por la página del curso• http://academic.regis.edu/mlotfy/CS208/

Computer_fundamentals_classroom.htm#Supplemental

▫Dev C++ or Code::Blocks

7

Sobrevista del curso

8

Páginas 14-15

Método de evaluación

9

Participación 15%Tarea primera noche 5%Tareas en clase 30%Tareas (6 programas) 30%Exámenes (2) 20%

Estándar de código

•Será revisados•Descripción completa en la página del

curso•Comentarios se requieren•Indentar apropiadamente•Espacio en blanco (espacios, líneas en

blanco, indentación)•Constantes globales en vez de valores en el

código•ApellidoNombre_PgmX.cpp

10

Documentación de los programas•Documento requerido•Siempre en español•Primera página en APA•Siguientes páginas sin formato APA•En Microsoft Word•Descripción del problema•Descripción del algoritmo usado•10% del grado del programa•ApellidoNombre_PgmX.doc

11

Acerca de sus compañeros:

•Nombre•Carrera que cursan•Donde trabajan•Donde viven•Experiencia en programación•¿Que esperan de el curso?

12

Instalación del compilador

13

•Se obtiene de la página del curso•Guarden a su ordenador•Ejecuten la aplicación y mantenga las

opciones recomendadas•No cambien opciones a menos que sepan

lo que estan haciendo•Revisen la instalación

Instrucciones de descarga

14

Instrucciones de descarga(II)

15

Configuración del compilador

16

Verificación del ambiente

17

Configuración de el editor

18

Vocabulario Clave

• Compiler – compilador• Hard coded variable – valor usado en vez de

constante• I/O stream – flujo de entradas y salidas• Linker – enlazador• Object code – código objeto• Server – ordenador, servidor, estación de trabajo• Source code – código fuente• Syntax and semantics – sintaxis y semántica• Whitespace – líneas en blanco, espacio, indentar

19

Tarea de la primera noche

•Leer las páginas 1 a 148 y el apéndice E páginas 1248 y 1249 del texto.

•Escoja una actividad que usted hace diariamente, como las que están escrita arriba, y escriba un algoritmo especifico, claro y preciso para la misma, en Español. Si es necesario, enumere los diferentes pasos a seguir.

20

Algoritmo‘una descripción precisa de un método para resolver un problema particular con las operaciones o acciones de un repertorio bien entendido. Algoritmos están en todas partes. Cuando cambiamos los neumáticos de un auto, cortar el césped, aspirar la alfombra, o seguir las instrucciones a un restaurante, se utiliza algoritmo. Una persona puede resolver los problemas por medio de algoritmos expresados en inglés, siempre y cuando la persona entienda inglés. Y una computadora puede resolver problemas por medio de algoritmos expresados en un lenguaje de programación, siempre que el ordenador "entienda" el lenguaje.’ [De John Shore, The Sachertorte Algorithm, 1985]

21

¿Para que usamos algoritmos?

•Programas = Algoritmos + Estructuras de datos

(Niklaus Wirth)•Experimentaremos con algoritmos y control

de datos en esta clase•La próxima clase (CS 362) cubre

estructuras de datos•Antes de escribir un programa, necesitamos

una idea de como resolver el problema▫Esto requiere un algoritmo

22

Capítulo 1

•23-78

23

scis.regis.edu ● [email protected]

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

Chapter 1: An Overview of Computers and Programming Languages

24

ObjectivesIn this chapter, you will:

• Learn about different types of computers

• Explore the hardware and software components of a computer system

• Learn about the language of a computer

• Learn about the evolution of programming languages

• Examine high-level programming languages

25

Objectives (cont'd.)• Discover what a compiler is and what it

does• Examine a C++ program• Explore how a C++ program is processed• Learn what an algorithm is and explore

problem-solving techniques• Become aware of structured design and

object-oriented design programming methodologies

• Become aware of Standard C++ and ANSI/ISO Standard C++

26

Introduction• Without software, the computer is

useless• Software developed with programming

languages– C++ is a programming language

• C++ suited for a wide variety of programming tasks

• Before programming, it is useful to understand terminology and computer components

27

A Brief Overview of the History of Computers•Early calculation devices

▫Abacus, Pascaline▫Leibniz device▫Babbage machines: difference and analytic

engines▫Hollerith machine

28

A Brief Overview of the History of Computers (cont'd.)•Early computer-like machines

▫Mark I▫ENIAC▫Von Neumann architecture▫UNIVAC▫Transistors and microprocessors

29

A Brief Overview of the History of Computers (cont'd.)•Categories of computers

▫Mainframe computers▫Midsize computers▫Micro computers (personal computers)

30

Elements of a Computer System•Hardware•CPU•Main memory•Secondary storage•Input/Output devices•Software

31

Hardware

•CPU•Main memory: RAM•Input/output devices•Secondary storage

32

Central Processing Unit and Main Memory•Central processing unit

▫Brain of the computer▫Most expensive piece of hardware▫Carries out arithmetic and logical

operations

33

Central Processing Unit and Main Memory (cont'd.)

34

Central Processing Unit and Main Memory (cont'd.)•Random access memory•Directly connected to the CPU •All programs must be loaded into main

memory before they can be executed•All data must be brought into main

memory before it can be manipulated •When computer power is turned off,

everything in main memory is lost

35

Secondary Storage

• Secondary storage: device that stores information permanently

• Examples of secondary storage:– Hard disks – Flash drives– Floppy disks– Zip disks– CD-ROMs– Tapes

36

Input/Output Devices

• Input devices feed data and programs into computers– Keyboard – Mouse – Secondary storage

• Output devices display results– Monitor– Printer– Secondary storage

37

Software

•Software: programs that do specific tasks•System programs take control of the

computer, such as an operating system•Application programs perform a specific

task▫Word processors▫Spreadsheets▫Games

38

The Language of a Computer

•Digital signals: sequences of 0s and 1s•Machine language: language of a

computer•Binary digit (bit):

▫The digit 0 or 1 •Binary code:

▫A sequence of 0s and 1s •Byte:

▫A sequence of eight bits

39

The Language of a Computer (cont’d.)

40

The Language of a Computer (cont'd.)•ASCII (American Standard Code for

Information Interchange) ▫128 characters▫A is encoded as 1000001 (66th character)▫3 is encoded as 0110011

41

The Language of a Computer (cont'd.)•EBCDIC

▫Used by IBM▫256 characters

•Unicode ▫65536 characters▫Two bytes are needed to store a character

42

The Evolution of Programming Languages•Early computers were programmed in

machine language •To calculate wages = rates * hours in

machine language:

100100 010001 //Load

100110 010010 //Multiply

100010 010011 //Store

43

The Evolution of Programming Languages (cont'd.)

• Assembly language instructions are mnemonic • Assembler: translates a program written in

assembly language into machine language

44

The Evolution of Programming Languages (cont'd.)•Using assembly language instructions, wages = rates • hours can be written as:

LOAD rateMULT hourSTOR wages

45

The Evolution of Programming Languages (cont'd.)•High-level languages include Basic,

FORTRAN, COBOL, Pascal, C, C++, C#, and Java

•Compiler: translates a program written in a high-level language machine language

•The equation wages = rate • hours can be written in C++ as: wages = rate * hours;

46

Processing a C++ Program#include <iostream>using namespace std;int main() { cout << "My first C++ program." << endl; return 0;

}

Sample Run: My first C++ program.

47

Processing a C++ Program (cont'd.)•To execute a C++ program:

▫Use an editor to create a source program in C++

▫Preprocessor directives begin with # and are processed by a the preprocessor

▫Use the compiler to: Check that the program obeys the rules Translate into machine language (object

program)

48

Processing a C++ Program (cont'd.)•To execute a C++ program (cont'd.):

▫Linker: Combines object program with other

programs provided by the SDK to create executable code

▫Loader: Loads executable program into main memory

▫The last step is to execute the program

49

Processing a C++ Program (cont'd.)

50

Programming with the Problem Analysis–Coding–Execution Cycle• Programming is a process of problem

solving

• One problem-solving technique:– Analyze the problem

– Outline the problem requirements

– Design steps (algorithm) to solve the problem

• Algorithm: – Step-by-step problem-solving process

– Solution achieved in finite amount of time51

The Problem Analysis–Coding–Execution Cycle (cont’d.)• Step 1: Analyze the problem

– Outline the problem and its requirements– Design steps (algorithm) to solve the

problem• Step 2: Implement the algorithm

– Implement the algorithm in code– Verify that the algorithm works

• Step 3: Maintenance– Use and modify the program if the problem

domain changes52

The Problem Analysis–Coding–Execution Cycle (cont’d.)

53

The Problem Analysis–Coding–Execution Cycle (cont'd.)•Thoroughly understand the problem•Understand problem requirements

▫Does program require user interaction?▫Does program manipulate data? ▫What is the output?

•If the problem is complex, divide it into subproblems▫Analyze each subproblem as above

54

The Problem Analysis–Coding–Execution Cycle (cont'd.)•If problem was broken into subproblems

▫Design algorithms for each subproblem•Check the correctness of algorithm

▫Can test using sample data▫Some mathematical analysis might be

required

55

The Problem Analysis–Coding–Execution Cycle (cont'd.)•Once the algorithm is designed and

correctness verified▫Write the equivalent code in high-level

language•Enter the program using text editor

56

The Problem Analysis–Coding–Execution Cycle (cont'd.)•Run code through compiler •If compiler generates errors

▫Look at code and remove errors▫Run code again through compiler

•If there are no syntax errors▫Compiler generates equivalent machine

code•Linker links machine code with system

resources

57

The Problem Analysis–Coding–Execution Cycle (cont'd.)•Once compiled and linked, loader can

place program into main memory for execution

•The final step is to execute the program•Compiler guarantees that the program

follows the rules of the language▫Does not guarantee that the program will

run correctly

58

Example 1-1

•Design an algorithm to find the perimeter and area of a rectangle

•The perimeter and area of the rectangle are given by the following formulas:

perimeter = 2 * (length + width)area = length * width

59

Example 1-1 (cont'd.)

•Algorithm:

▫Get length of the rectangle

▫Get width of the rectangle

▫Find the perimeter using the following equation:

perimeter = 2 * (length + width)

▫Find the area using the following equation:

area = length * width

60

Example 1-3

•Every salesperson has a base salary•Salesperson receives $10 bonus at the

end of the month for each year worked if he or she has been with the store for five or less years

•The bonus is $20 for each year that he or she has worked there if over 5 years

61

Example 1-3 (cont'd.)

•Additional bonuses are as follows: ▫If total sales for the month are $5,000-

$10,000, he or she receives a 3% commission on the sale

▫If total sales for the month are at least $10,000, he or she receives a 6% commission on the sale

62

Example 1-3 (cont'd.)

•Get baseSalary

•Get noOfServiceYears

•Calculate bonus using the following formula:if (noOfServiceYears is less than or equal to five)

bonus = 10 * noOfServiceYears

otherwise

bonus = 20 * noOfServiceYears

•Get totalSales63

Example 1-3 (cont'd.)

•Calculate additionalBonus as follows:if (totalSale is less than 5000)additionalBonus = 0

otherwise if (totalSale is greater than or equal to 5000 and totalSale is less than 10000) additionalBonus = totalSale · (0.03)

otherwise additionalBonus = totalSale · (0.06)

64

Example 1-3 (cont'd.)

•Calculate payCheck using the equationpayCheck = baseSalary + bonus

+ additionalBonus

65

Example 1-5

• 10 students in a class • Each student has taken five tests and each

test is worth 100 points• Design an algorithm to calculate the grade

for each student as well as the class average– Design an algorithm to find the average test score– Design an algorithm to determine the grade

• Data consists of students’ names and their test scores

66

Example 1-5 (cont'd.)•Algorithm to determine the average test

score:▫Get the five test scores▫Add the five test scores

Suppose sum stands for the sum of the test scores

▫Suppose average stands for the average test score: average = sum / 5;

67

Example 1-5 (cont'd.)• Algorithm to determine the grade:

if average is greater than or equal to 90 grade = Aotherwise

if average is greater than or equal to 80 and less than 90 grade = Botherwise

if average is greater than or equal to 70 and less than 80 grade = Cotherwise if average is greater than or equal to 60 and less than 70 grade = Dotherwise grade = F

68

Example 1-5 (cont'd.)• Main algorithm is as follows:

– totalAverage = 0;– Repeat the following for each student:

• Get student’s name• Use the algorithm to find the average test

score• Use the algorithm to find the grade• Update totalAverage by adding current

student’s average test score– Determine the class average as follows:

• classAverage = totalAverage / 10 69

Programming Methodologies•Two popular approaches to

programming design▫Structured

▫Object-oriented

70

Structured Programming• Structured design:

– Dividing a problem into smaller subproblems

• Structured programming:– Implementing a structured design

• The structured design approach is also called:– Top-down (or bottom-up) design

– Stepwise refinement

– Modular programming71

Object-Oriented Programming

•Identify components called objects•Specify relevant data and possible

operations to be performed on that data•Each object consists of data and

operations on that data•An object combines data and operations

on the data into a single unit

72

Object-Oriented Programming (cont'd.)•A programming language that implements

OOD is called an object-oriented programming (OOP) language

•Learn how to represent data in computer memory, how to manipulate data, and how to implement operations

•Write algorithms and implement them in a programming language

73

Object-Oriented Programming (cont'd.)•Learn how to combine data and

operations on the data into a single unit called an object

•C++ was designed to implement OOD•OOD is used with structured design

74

ANSI/ISO Standard C++

•C++ evolved from C •C++ designed by Bjarne Stroustrup at

Bell Laboratories in early 1980s•C++ programs were not always portable

from one compiler to another•In mid-1998, ANSI/ISO C++ language

standards were approved

75

Summary•Computer: electronic device that can

perform arithmetic and logical operations•Computer system has hardware and

software•Central processing unit (CPU): brain•Primary storage (MM) is volatile;

secondary storage (e.g., disk) is permanent•Operating system monitors the overall

activity of the computer and provides services

76

Summary (cont'd.)

•Various kinds of languages, such as machine language, assembly, high-level

•Algorithm: step-by-step problem-solving process; solution in finite amount of time

•Problem-solving process has three steps:▫Analyze problem and design an algorithm▫Implement the algorithm in code▫Maintain the program

77

Summary (cont'd.)

•Structured design: ▫Problem is divided into smaller subproblems▫Each subproblem is solved▫Combine solutions to all subproblems

•Object-oriented design (OOD): a program is a collection of interacting objects▫Object: data and operations on those data

78

Capítulo 2

•80-161

79

scis.regis.edu ● [email protected]

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

Chapter 2: Basic Elements of C++

80

Objectives

In this chapter, you will:•Become familiar with the basic

components of a C++ program, including functions, special symbols, and identifiers

•Explore simple data types•Discover how to use arithmetic operators •Examine how a program evaluates

arithmetic expressions

81

Objectives (cont'd.)

• Learn what an assignment statement is and what it does

• Become familiar with the string data type• Discover how to input data into memory

using input statements• Become familiar with the use of increment

and decrement operators• Examine ways to output results using

output statements

82

Objectives (cont'd.)

•Learn how to use preprocessor directives and why they are necessary

•Learn how to debug syntax errors•Explore how to properly structure a

program, including using comments to document a program

•Learn how to write a C++ program

83

Introduction

•Computer program▫Sequence of statements whose objective is

to accomplish a task•Programming

▫Process of planning and creating a program

84

A C++ Program

#include <iostream>using namespace std;int main(){int num;num = 6;cout << "My first C++ program." << endl;cout << "The sum of 2 and 3 = " << 5 << endl;cout << "7 + 8 = " << 7 + 8 << endl;cout << "Num = " << num << endl;return 0;

}

85

The Basics of a C++ Program

• Function: collection of statements; when executed, accomplishes something

– May be predefined or standard

• Syntax: rules that specify which statements (instructions) are legal

• Programming language: a set of rules, symbols, and special words

• Semantic rule: meaning of the instruction86

Comments• Comments are for the reader, not the

compiler

• Two types:

– Single line// This is a C++ program. It prints the sentence:// Welcome to C++ Programming.

– Multiple line/* You can include comments that can occupy several lines.*/

87

Special Symbols

•Special symbols

+ -*/.;

88

?

,

<=

!=

==

>=

Reserved Words (Keywords)

•Reserved words, keywords, or word symbols▫Include:

int float double char const void return

89

Identifiers•Consist of letters, digits, and the underscore character (_)

•Must begin with a letter or underscore•C++ is case sensitive

▫NUMBER is not the same as number•Two predefined identifiers are cout and cin

•Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea

90

Identifiers (cont'd.)

•Legal identifiers in C++:▫first▫conversion▫payRate

91

Whitespaces

•Every C++ program contains whitespaces▫Include blanks, tabs, and newline

characters •Used to separate special symbols,

reserved words, and identifiers•Proper utilization of whitespaces is

important ▫Can be used to make the program readable

92

Data Types

•Data type: set of values together with a set of operations

•C++ data types fall into three categories:

93

Simple Data Types

•Three categories of simple data▫Integral: integers (numbers without a

decimal)▫Floating-point: decimal numbers▫Enumeration type: user-defined data type

94

Simple Data Types (cont'd.)

•Integral data types are further classified into nine categories:▫char, short, int, long, bool▫unsigned char, unsigned short, unsigned int, unsigned long

95

Simple Data Types (cont'd.)

•Different compilers may allow different ranges of values

96

int Data Type

•Examples:-6728078+763

•Positive integers do not need a + sign•No commas are used within an integer

▫Commas are used for separating items in a list

97

bool Data Type

•bool type ▫Two values: true and false▫Manipulate logical (Boolean) expressions

•true and false ▫Logical values

•bool, true, and false ▫Reserved words

98

char Data Type

•The smallest integral data type•Used for characters: letters, digits, and

special symbols•Each character is enclosed in single

quotes▫'A', 'a', '0', '*', '+', '$', '&'

•A blank space is a character▫Written ' ', with a space left between the

single quotes

99

Floating-Point Data Types

•C++ uses scientific notation to represent real numbers (floating-point notation)

100

Floating-Point Data Types (cont'd.)•float: represents any real number

▫Range: -3.4E+38 to 3.4E+38 (four bytes)•double: represents any real number

▫Range: -1.7E+308 to 1.7E+308 (eight bytes)

101

Floating-Point Data Types (cont'd.)•Maximum number of significant digits

(decimal places) for float values is 6 or 7 •Maximum number of significant digits for double is 15

•Precision: maximum number of significant digits▫Float values are called single precision▫Double values are called double precision

102

Arithmetic Operators and Operator Precedence• C++ arithmetic operators:

– + addition– - subtraction– * multiplication– / division– % modulus operator

• +, -, *, and / can be used with integral and floating-point data types

• Operators can be unary or binary

103

Order of Precedence

•All operations inside of () are evaluated first

•*, /, and % are at the same level of precedence and are evaluated next

•+ and – have the same level of precedence and are evaluated last

•When operators are on the same level▫Performed from left to right (associativity)

•3 * 7 - 6 + 2 * 5 / 4 + 6 means(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

104

Expressions

•If all operands are integers▫Expression is called an integral expression

Yields an integral result Example: 2 + 3 * 5

•If all operands are floating-point▫Expression is called a floating-point

expression Yields a floating-point result Example: 12.8 * 17.5 - 34.50

105

Mixed Expressions

•Mixed expression: ▫Has operands of different data types▫Contains integers and floating-point

•Examples of mixed expressions:2 + 3.56 / 4 + 3.95.4 * 2 – 13.6 + 18 / 2

106

Mixed Expressions (cont'd.)

•Evaluation rules:▫If operator has same types of operands

Evaluated according to the type of the operands

▫If operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point

▫Entire expression is evaluated according to precedence rules

107

Type Conversion (Casting)

•Implicit type coercion: when value of one type is automatically changed to another type

•Cast operator: provides explicit type conversionstatic_cast<dataTypeName>(expression)

108

Type Conversion (cont'd.)

109

string Type• Programmer-defined type supplied in

ANSI/ISO Standard C++ library• Sequence of zero or more characters• Enclosed in double quotation marks • Null: a string with no characters• Each character has relative position in

string– Position of first character is 0

• Length of a string is number of characters in it– Example: length of "William Jacob" is 13

110

Input

•Data must be loaded into main memory before it can be manipulated

•Storing data in memory is a two-step process:▫Instruct computer to allocate memory▫Include statements to put data into memory

111

Allocating Memory with Constants and Variables•Named constant: memory location whose

content can’t change during execution•The syntax to declare a named constant

is:•In C++, const is a reserved word

112

Allocating Memory with Constants and Variables (cont'd.)•Variable: memory location whose content

may change during execution•The syntax to declare a named constant

is:

113

Putting Data into Variables

•Ways to place data into a variable:▫Use C++’s assignment statement▫Use input (read) statements

114

Assignment Statement

•The assignment statement takes the form:

•Expression is evaluated and its value is assigned to the variable on the left side

•In C++, = is called the assignment operator

115

Assignment Statement (cont'd.)

116

Saving and Using the Value of an Expression•To save the value of an expression:

▫Declare a variable of the appropriate data type

▫Assign the value of the expression to the variable that was declared Use the assignment statement

•Wherever the value of the expression is needed, use the variable holding the value

117

Declaring & Initializing Variables•Variables can be initialized when

declared:int first=13, second=10;char ch=' ';double x=12.6;

•All variables must be initialized before they are used▫But not necessarily during declaration

118

Input (Read) Statement

•cin is used with >> to gather input

•The stream extraction operator is >>•For example, if miles is a double variable

cin >> miles;▫Causes computer to get a value of type double

▫Places it in the variable miles

119

Input (Read) Statement (cont'd.)•Using more than one variable in cin

allows more than one value to be read at a time

•For example, if feet and inches are variables of type int, a statement such as: cin >> feet >> inches;▫Inputs two integers from the keyboard▫Places them in variables feet and inches

respectively

120

Input (Read) Statement (cont'd.)

121

Variable Initialization

•There are two ways to initialize a variable:int feet;▫By using the assignment statementfeet = 35;

▫By using a read statementcin >> feet;

122

Increment and Decrement Operators•Increment operator: increment variable

by 1▫Pre-increment: ++variable▫Post-increment: variable++

•Decrement operator: decrement variable by 1▫Pre-decrement: --variable▫Post-decrement: variable—

•What is the difference between the following?

123

x = 5;y = ++x;

x = 5;y = x++;

Output

•The syntax of cout and << is:

▫Called an output statement

•The stream insertion operator is <<

•Expression evaluated and its value is printed at the current cursor position on the screen

124

Output (cont'd.)

•A manipulator is used to format the output▫Example: endl causes insertion point to

move to beginning of next line

125

Output (cont'd.)•The new line character is '\n'

▫May appear anywhere in the string cout << "Hello there.";cout << "My name is James."; Output:Hello there.My name is James.

cout << "Hello there.\n";cout << "My name is James."; Output :Hello there.My name is James.

126

Output (cont'd.)

127

Preprocessor Directives• C++ has a small number of operations• Many functions and symbols needed to

run a C++ program are provided as collection of libraries

• Every library has a name and is referred to by a header file

• Preprocessor directives are commands supplied to the preprocessor

• All preprocessor commands begin with #• No semicolon at the end of these

commands

128

Preprocessor Directives (cont'd.)•Syntax to include a header file:

•For example:

#include <iostream>

▫Causes the preprocessor to include the header file iostream in the program

129

namespace and Using cin and cout in a Program•cin and cout are declared in the header

file iostream, but within std namespace•To use cin and cout in a program, use the

following two statements:#include <iostream>using namespace std;

130

Using the string Data Type in a Program•To use the string type, you need to

access its definition from the header file string

•Include the following preprocessor directive:#include <string>

131

Creating a C++ Program

•C++ program has two parts: ▫Preprocessor directives ▫The program

•Preprocessor directives and program statements constitute C++ source code (.cpp)

•Compiler generates object code (.obj)•Executable code is produced and saved in

a file with the file extension .exe

132

Creating a C++ Program (cont'd.)• A C++ program is a collection of functions,

one of which is the function main• The first line of the function main is called

the heading of the function:– int main()

• The statements enclosed between the curly braces ({ and }) form the body of the function– Contains two types of statements:

• Declaration statements• Executable statements

133

134

Creating a C++ Program (cont'd.)

Creating a C++ Program (cont'd.)Sample Run: Line 9: firstNum = 18Line 10: Enter an integer: 15

Line 13: secondNum = 15Line 15: The new value of firstNum = 60

135

Debugging: Understanding and Fixing Syntax Errors•Compile a program

▫Compiler will identify the syntax error▫Specifies the line numbers where the

errors occurExample2_Syntax_Errors.cppc:\chapter 2 source code\example2_syntax_errors.cpp(9) : error C2146: syntax error :

missing ';' before identifier 'num'c:\chapter 2 source code\example2_syntax_errors.cpp(11) : error C2065: 'tempNum' :

undeclared identifier

•Learn how to spot and fix syntax errors

136

Program Style and Form

•Every C++ program has a function main•Programs must also follow syntax rules•Other rules serve the purpose of giving

precise meaning to the language

137

Syntax

•Errors in syntax are found in compilationint x; //Line 1int y //Line 2: errordouble z; //Line 3

y = w + x; //Line 4: error

138

Use of Blanks

•In C++, you use one or more blanks to separate numbers when data is input▫Used to separate reserved words and

identifiers from each other and from other symbols

▫Must never appear within a reserved word or identifier

139

Use of Semicolons, Brackets, and Commas•All C++ statements end with a semicolon

▫Also called a statement terminator•{ and } are not C++ statements•Commas separate items in a list

140

Semantics

•Possible to remove all syntax errors in a program and still not have it run

•Even if it runs, it may still not do what you meant it to do

•For example,2 + 3 * 5 and (2 + 3) * 5are both syntactically correct expressions, but have different meanings

141

Naming Identifiers

•Identifiers can be self-documenting:▫CENTIMETERS_PER_INCH

•Avoid run-together words :▫annualsale▫Solution:

Capitalize the beginning of each new word: annualSale

Inserting an underscore just before a new word: annual_sale

142

Prompt Lines

•Prompt lines: executable statements that inform the user what to do

cout << "Please enter a number between 1 and 10 and " << "press the return key" << endl;cin >> num;

143

Documentation

•A well-documented program is easier to understand and modify

•You use comments to document programs•Comments should appear in a program to:

▫Explain the purpose of the program▫Identify who wrote it▫Explain the purpose of particular

statements

144

Form and Style

•Consider two ways of declaring variables:▫Method 1

int feet, inch;double x, y;

▫Method 2int feet,inch;double x,y;

•Both are correct; however, the second is hard to read

145

More on Assignment Statements•C++ has special assignment statements

called compound assignments+=, -=, *=, /=, and %=

•Example: x *= y;

146

Programming Example: Convert Length• Write a program that takes as input a

given length expressed in feet and inches– Convert and output the length in

centimeters• Input: length in feet and inches• Output: equivalent length in centimeters• Lengths are given in feet and inches• Program computes the equivalent length in

centimeters• One inch is equal to 2.54 centimeters

147

Programming Example: Convert Length (cont'd.)•Convert the length in feet and inches to

all inches: ▫Multiply the number of feet by 12 ▫Add given inches

•Use the conversion formula (1 inch = 2.54 centimeters) to find the equivalent length in centimeters

148

Programming Example: Convert Length (cont'd.)•The algorithm is as follows:

▫Get the length in feet and inches▫Convert the length into total inches▫Convert total inches into centimeters▫Output centimeters

149

Programming Example: Variables and Constants•Variables

int feet; //variable to hold given feetint inches; //variable to hold given inchesint totalInches; //variable to hold total inchesdouble centimeters; //variable to hold length in //centimeters

•Named Constantconst double CENTIMETERS_PER_INCH = 2.54;

const int INCHES_PER_FOOT = 12;

150

Programming Example: Main Algorithm•Prompt user for input •Get data•Echo the input (output the input)•Find length in inches•Output length in inches•Convert length to centimeters•Output length in centimeters

151

Programming Example: Putting It Together• Program begins with comments • System resources will be used for I/O• Use input statements to get data and

output statements to print results• Data comes from keyboard and the output

will display on the screen• The first statement of the program, after

comments, is preprocessor directive to include header file iostream

152

Programming Example: Putting It Together (cont'd.)• Two types of memory locations for data

manipulation: – Named constants

• Usually put before main– Variables

• This program has only one function (main), which will contain all the code

• The program needs variables to manipulate data, which are declared in main

153

Programming Example: Body of the Function• The body of the function main has the

following form:int main (){ declare variables statements return 0;}

154

Programming Example: Writing a Complete Program•Begin the program with comments for

documentation•Include header files•Declare named constants, if any•Write the definition of the function main

155

Programming Example: Writing a Complete Program (cont’d.)

156

Programming Example: Sample Run

157

Enter two integers, one for feet, one for inches: 15 7

The numbers you entered are 15 for feet and 7 for inches.The total number of inches = 187The number of centimeters = 474.98

Summary

• C++ program: collection of functions where each program has a function called main

• Identifier consists of letters, digits, and underscores, and begins with letter or underscore

• The arithmetic operators in C++ are addition (+), subtraction (-),multiplication (*), division (/), and modulus (%)

• Arithmetic expressions are evaluated using the precedence associativity rules

158

Summary (cont'd.)

• All operands in an integral expression are integers and all operands in a floating-point expression are decimal numbers

• Mixed expression: contains both integers and decimal numbers

• Use the cast operator to explicitly convert values from one data type to another

• A named constant is initialized when declared

• All variables must be declared before used159

Summary (cont'd.)

•Use cin and stream extraction operator >> to input from the standard input device

•Use cout and stream insertion operator << to output to the standard output device

•Preprocessor commands are processed before the program goes through the compiler

•A file containing a C++ program usually ends with the extension .cpp

160

Actividad 1

•En un grupo de 2 personas cada uno:•Ver el programa en páginas 140-141•Escribir y correr el programa•Revisen las salidas contra el ‘Sample Run’

Tiempo: 30 minutos

161

Capítulo 3

•163-212

•Programas simples 213-215•Ayuda•Primera tarea

162

scis.regis.edu ● [email protected]

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

Chapter 3: Input/Output

163

Objectives

In this chapter, you will:• Learn what a stream is and examine input

and output streams• Explore how to read data from the

standard input device• Learn how to use predefined functions in

a program• Explore how to use the input stream

functions get, ignore, putback, and peek

164

Objectives (cont'd.)

• Become familiar with input failure• Learn how to write data to the standard

output device• Discover how to use manipulators in a

program to format output• Learn how to perform input and output

operations with the string data type• Learn how to debug logic errors• Become familiar with file input and output

165

I/O Streams and Standard I/O Devices• I/O: sequence of bytes (stream of bytes)

from source to destination– Bytes are usually characters, unless

program requires other types of information

• Stream: sequence of characters from source to destination

• Input stream: sequence of characters from an input device to the computer

• Output stream: sequence of characters from the computer to an output device

166

I/O Streams and Standard I/O Devices (cont'd.)•Use iostream header file to extract

(receive) data from keyboard and send output to the screen▫Contains definitions of two data types:

istream: input stream ostream: output stream

▫Has two variables: cin: stands for common input cout: stands for common output

167

I/O Streams and Standard I/O Devices (cont'd.)•To use cin and cout, the preprocessor

directive #include <iostream> must be used

•Variable declaration is similar to: ▫istream cin;▫ostream cout;

•Input stream variables: type istream •Output stream variables: type ostream

168

cin and the Extraction Operator >>•The syntax of an input statement using cin and the extraction operator >> is:

•The extraction operator >> is binary▫Left-side operand is an input stream

variable Example: cin

▫Right-side operand is a variable

169

cin and the Extraction Operator >> (cont'd.)

• No difference between a single cin with multiple variables and multiple cin statements with one variable

• When scanning, >> skips all whitespace– Blanks and certain nonprintable

characters• >> distinguishes between character 2 and

number 2 by the right-side operand of >>– If type char or int (or double), the 2 is

treated as a character or as a number 2

170

cin and the Extraction Operator >> (cont'd.)

• Entering a char value into an int or double variable causes serious errors, called input failure

171

cin and the Extraction Operator >> (cont'd.)•When reading data into a char variable

▫>> skips leading whitespace, finds and stores only the next character

▫Reading stops after a single character•To read data into an int or double variable

▫>> skips leading whitespace, reads + or - sign (if any), reads the digits (including decimal)

▫Reading stops on whitespace non-digit character

172

cin and the Extraction Operator >> (cont'd.)

173

cin and the Extraction Operator >> (cont'd.)

174

cin and the Extraction Operator >> (cont'd.)

175

Using Predefined Functions in a Program•Function (subprogram): set of instructions

▫When activated, it accomplishes a task

•main executes when a program is run•Other functions execute only when called •C++ includes a wealth of functions

▫Predefined functions are organized as a collection of libraries called header files

176

Using Predefined Functions in a Program (cont'd.)•Header file may contain several functions •To use a predefined function, you need

the name of the appropriate header file▫You also need to know:

Function name Number of parameters required Type of each parameter What the function is going to do

177

Using Predefined Functions in a Program (cont'd.)•To use pow (power), include cmath

▫Two numeric parameters▫Syntax: pow(x,y) = xy

x and y are the arguments or parameters

▫In pow(2,3), the parameters are 2 and 3

178

Using Predefined Functions in a Program (cont'd.)

179

Using Predefined Functions in a Program (cont'd.)Sample Run:Line 1: 2 to the power of 6 = 64Line 4: 12.5 to the power of 3 = 1953.13Line 5: Square root of 24 = 4.89898Line 7: u = 181.019Line 9: Length of str = 20

180

cin and the get Function

•The get function▫Inputs next character (including

whitespace)▫Stores in memory location indicated by its

argument•The syntax of cin and the get function:

varChar▫Is a char variable▫Is the argument (parameter) of the function

181

cin and the ignore Function

• ignore function – Discards a portion of the input

• The syntax to use the function ignore is:

intExp is an integer expressionchExp is a char expression

• If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp

182

putback and peek Functions

•putback function▫Places previous character extracted by the get function from an input stream back to that stream

•peek function▫Returns next character from the input

stream▫Does not remove the character from that

stream

183

putback and peek Functions (cont'd.)• The syntax for putback:

– istreamVar: an input stream variable (cin)– ch is a char variable

• The syntax for peek:

– istreamVar: an input stream variable (cin)– ch is a char variable

184

The Dot Notation Between I/O Stream Variables and I/O Functions: A Precaution

•In the statement cin.get(ch);

cin and get are two separate identifiers separated by a dot

•Dot separates the input stream variable name from the member, or function, name

•In C++, dot is the member access operator

185

Input Failure

•Things can go wrong during execution•If input data does not match

corresponding variables, program may run into problems

•Trying to read a letter into an int or double variable will result in an input failure

•If an error occurs when reading data▫Input stream enters the fail state

186

The clear Function

•Once in a fail state, all further I/O statements using that stream are ignored

•The program continues to execute with whatever values are stored in variables ▫This causes incorrect results

•The clear function restores input stream to a working state

187

Output and Formatting Output

•Syntax of cout when used with <<

•Expression is evaluated•Value is printed•Manipulator is used to format the output

▫Example: endl

188

setprecision Manipulator

•Syntax:

•Outputs decimal numbers with up to n decimal places

•Must include the header file iomanip:▫#include <iomanip>

189

fixed Manipulator

• fixed outputs floating-point numbers in a fixed decimal format

– Example: cout << fixed;– Disable by using the stream member

function unsetf• Example: cout.unsetf(ios::fixed);

• The manipulator scientific is used to output floating-point numbers in scientific format

190

showpoint Manipulator

•showpoint forces output to show the decimal point and trailing zeros

•Examples:▫cout << showpoint;▫cout << fixed << showpoint;

191

setw

•Outputs the value of an expression in specific columns▫cout << setw(5) << x << endl;

•If number of columns exceeds the number of columns required by the expression▫Output of the expression is right-justified▫Unused columns to the left are filled with

spaces•Must include the header file iomanip

192

Additional Output Formatting Tools•Additional formatting tools that give you

more control over your output:▫setfill manipulator▫left and right manipulators▫unsetf manipulator

193

setfill Manipulator

•Output stream variables can use setfill to fill unused columns with a character

•Example:▫cout << setfill('#');

194

left and right Manipulators

•left: left-justifies the output

•Disable left by using unsetf

•right: right-justifies the output

195

Types of Manipulators

•Two types of manipulators: ▫With parameters▫Without parameters

•Parameterized: require iomanip header▫setprecision, setw, and setfill

•Nonparameterized: require iostream header▫endl, fixed, showpoint, left, and flush

196

Input/Output and the string Type•An input stream variable (cin) and >>

operator can read a string into a variable of the data type string

•Extraction operator▫Skips any leading whitespace characters

and reading stops at a whitespace character

•The function getline▫Reads until end of the current line

197

Understanding Logic Errors and Debugging with cout statements•Syntax errors

▫Reported by the compiler•Logic errors

▫Typically not caught by the compiler▫Spot and correct using cout statements▫Temporarily insert an output statement▫Correct problem▫Remove output statement

198

File Input/Output

• File: area in secondary storage to hold info

• File I/O is a five-step process 1. Include fstream header2. Declare file stream variables3. Associate the file stream variables with

the input/output sources4. Use the file stream variables with >>, <<,

or other input/output functions5. Close the files

199

Programming Example: Movie Ticket Sale and Donation to Charity

• A theater owner agrees to donate a portion of gross ticket sales to a charity

• The program will prompt the user to input:– Movie name– Adult ticket price– Child ticket price– Number of adult tickets sold– Number of child tickets sold– Percentage of gross amount to be donated

200

Programming Example: I/O

• Inputs: movie name, adult and child ticket price, # adult and child tickets sold, and percentage of the gross to be donated

• Program output:

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Movie Name: ....................... Journey to Mars

Number of Tickets Sold: ........... 2650

Gross Amount: ..................... $ 9150.00

Percentage of Gross Amount Donated: 10.00%

Amount Donated: ................... $ 915.00

Net Sale: ......................... $ 8235.00

201

Programming Example: Problem Analysis• The program needs to:

1. Get the movie name2. Get the price of an adult ticket price3. Get the price of a child ticket price4. Get the number of adult tickets sold5. Get the number of child tickets sold6. Get the percentage of the gross amount

donated to the charity.

202

Programming Example: Problem Analysis (cont'd.)

7. Calculate the gross amountgrossAmount = adultTicketPrice * noOfAdultTicketsSold + childTicketPrice * noOfChildTicketsSold;

8. Calculate the amount donated to the charity

amountDonated = grossAmount * percentDonation / 100;

9. Calculate the net sale amountnetSale = grossAmount – amountDonated;

203

Programming Example: Variablesstring movieName;double adultTicketPrice;double childTicketPrice;int noOfAdultTicketsSold;int noOfChildTicketsSold;double percentDonation;double grossAmount;double amountDonated;double netSaleAmount;

204

Programming Example: Formatting Output

• First column is left-justified– When printing a value in the first

column, use left• Numbers in second column are right-

justified– Before printing a value in the second

column, use right• Use setfill to fill the empty space

between the first and second columns with dots

205

Programming Example: Formatting Output (cont'd.)•In the lines showing gross amount,

amount donated, and net sale amount ▫Use blanks to fill space between the $ sign

and the number•Before printing the dollar sign

▫Use setfill to set the filling character to blank

206

Programming Example: Main Algorithm

1. Declare variables2. Set the output of the floating-point to:

– Two decimal places– Fixed – Decimal point and trailing zeros

3. Prompt the user to enter a movie name4. Input movie name using getline

because it might contain spaces5. Prompt user for price of an adult ticket

207

Programming Example: Main Algorithm (cont'd.)6. Input price of an adult ticket7. Prompt user for price of a child ticket8. Input price of a child ticket9. Prompt user for the number of adult

tickets sold10.Input number of adult tickets sold11.Prompt user for number of child tickets

sold12.Input the number of child tickets sold

208

Programming Example: Main Algorithm (cont'd.)

13.Prompt user for percentage of the gross amount donated

14.Input percentage of the gross amount donated

15.Calculate the gross amount16.Calculate the amount donated17.Calculate the net sale amount18.Output the results

209

Summary

• Stream: infinite sequence of characters from a source to a destination

• Input stream: from a source to a computer• Output stream: from a computer to a

destination• cin: common input• cout: common output• To use cin and cout, include iostream

header

210

Summary (cont'd.)• get reads data character-by-character• putback puts last character retrieved

by get back to the input stream• ignore skips data in a line• peek returns next character from input

stream, but does not remove it• Attempting to read invalid data into a

variable causes the input stream to enter the fail state

211

Summary (cont'd.)

•The manipulators setprecision, fixed, showpoint, setw, setfill, left, and right can be used for formatting output

•Include iomanip for the manipulators setprecision, setw, and setfill

•File: area in secondary storage to hold info

•Header fstream contains the definitions of ifstream and ofstream

212

Programas simples

213

Mientras (while)

214

Corregir errores comunes

215

Ayuda•Revisen el #include•No olviden using namespace std;•Incluyan system ("PAUSE"); antes del fin del

programa•Definan las variables antes de usarlas

▫¿Valor inicial?•Usen constantes en vez de valores duros

▫ int const CONV_FACT = 3600;

•Si las salidas no son las esperadas, agregen cout para enseñar los valores en diferentes puntos en el programa

216

Programa 1

•Programa 6 en la página 173•Usar el estándar de código•Revisar entradas y salidas•¿Preguntas?•Entregar en WorldClass/Desire to Learn

antes de la semana 2

217