CS-361: Estructuras de Control Primera Clase - PowerPoint PPT Presentation

1 / 217
About This Presentation
Title:

CS-361: Estructuras de Control Primera Clase

Description:

CS-361: Estructuras de Control Primera Clase Dr. Jes s Borrego Lead Faculty, COS Regis University * setfill Manipulator Output stream variables can use setfill to ... – PowerPoint PPT presentation

Number of Views:185
Avg rating:3.0/5.0
Slides: 218
Provided by: stam151
Category:

less

Transcript and Presenter's Notes

Title: CS-361: Estructuras de Control Primera Clase


1
CS-361 Estructuras de ControlPrimera Clase
  • Dr. Jesús Borrego
  • Lead Faculty, COS
  • Regis University

2
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

3
Instructor
  • Dr. Jesús Borrego
  • Educación
  • PhD MIS MS CS BS CS BS EE
  • Ubicado
  • Colorado Springs
  • Casado, 5 hijos
  • Maestro desde 1989, a nivel de Asociado,
    Licenciado y Maestría
  • En Regis U. desde 1995

4
Introducción
  • Prerequisitos
  • CS 208
  • Experiencia en programación no es necesaria
  • Acceso a computadora personal
  • Compilador Dev C/CodeBlocks
  • Pueden usar otros a su propio riesgo

5
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.

6
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).

7
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_fu
    ndamentals_classroom.htmSupplemental
  • Dev C or CodeBlocks

8
Sobrevista del curso
Páginas 14-15
9
Método de evaluación
Participación 15 Tarea primera noche
5 Tareas en clase 30 Tareas (6
programas) 30 Exámenes (2) 20
10
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

11
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

12
Acerca de sus compañeros
  • Nombre
  • Carrera que cursan
  • Donde trabajan
  • Donde viven
  • Experiencia en programación
  • Que esperan de el curso?

13
Instalación del compilador
  • 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

14
Instrucciones de descarga
15
Instrucciones de descarga(II)
16
Configuración del compilador
17
Verificación del ambiente
18
Configuración de el editor
19
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

20
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.

21
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

22
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

23
Capítulo 1
  • 23-78

24
C Programming From Problem Analysis to Program
Design, Fifth Edition
  • Chapter 1 An Overview of Computers and
    Programming Languages

25
Objectives
  • In 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

26
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

27
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

28
A Brief Overview of the History of Computers
  • Early calculation devices
  • Abacus, Pascaline
  • Leibniz device
  • Babbage machines difference and analytic engines
  • Hollerith machine

29
A Brief Overview of the History of Computers
(cont'd.)
  • Early computer-like machines
  • Mark I
  • ENIAC
  • Von Neumann architecture
  • UNIVAC
  • Transistors and microprocessors

30
A Brief Overview of the History of Computers
(cont'd.)
  • Categories of computers
  • Mainframe computers
  • Midsize computers
  • Micro computers (personal computers)

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

32
Hardware
  • CPU
  • Main memory RAM
  • Input/output devices
  • Secondary storage

33
Central Processing Unit and Main Memory
  • Central processing unit
  • Brain of the computer
  • Most expensive piece of hardware
  • Carries out arithmetic and logical operations

34
Central Processing Unit and Main Memory (cont'd.)
35
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

36
Secondary Storage
  • Secondary storage device that stores information
    permanently
  • Examples of secondary storage
  • Hard disks
  • Flash drives
  • Floppy disks
  • Zip disks
  • CD-ROMs
  • Tapes

37
Input/Output Devices
  • Input devices feed data and programs into
    computers
  • Keyboard
  • Mouse
  • Secondary storage
  • Output devices display results
  • Monitor
  • Printer
  • Secondary storage

38
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

39
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

40
The Language of a Computer (contd.)
41
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

42
The Language of a Computer (cont'd.)
  • EBCDIC
  • Used by IBM
  • 256 characters
  • Unicode
  • 65536 characters
  • Two bytes are needed to store a character

43
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

44
The Evolution of Programming Languages (cont'd.)
  • Assembly language instructions are mnemonic
  • Assembler translates a program written in
    assembly language into machine language

45
The Evolution of Programming Languages (cont'd.)
  • Using assembly language instructions, wages
    rates hours can be written as
  • LOAD rate
  • MULT hour
  • STOR wages

46
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

47
Processing a C Program
  • include ltiostreamgt
  • using namespace std
  • int main()
  • cout ltlt "My first C program." ltlt endl
  • return 0
  • Sample Run
  • My first C program.

48
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)

49
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

50
Processing a C Program (cont'd.)
51
Programming with the Problem AnalysisCodingExecu
tion 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 time

52
The Problem AnalysisCodingExecution Cycle
(contd.)
  • 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
    changes

53
The Problem AnalysisCodingExecution Cycle
(contd.)
54
The Problem AnalysisCodingExecution 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

55
The Problem AnalysisCodingExecution 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

56
The Problem AnalysisCodingExecution 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

57
The Problem AnalysisCodingExecution 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

58
The Problem AnalysisCodingExecution 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

59
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

60
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

61
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

62
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

63
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 totalSales

64
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)

65
Example 1-3 (cont'd.)
  • Calculate payCheck using the equation
  • payCheck baseSalary bonus
  • additionalBonus

66
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

67
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

68
Example 1-5 (cont'd.)
  • Algorithm to determine the grade
  • if average is greater than or equal to 90
  • grade A
  • otherwise
  • if average is greater than or equal to 80 and
    less than 90
  • grade B
  • otherwise
  • if average is greater than or equal to 70 and
    less than 80
  • grade C
  • otherwise
  • if average is greater than or equal to 60 and
    less than 70
  • grade D
  • otherwise
  • grade F

69
Example 1-5 (cont'd.)
  • Main algorithm is as follows
  • totalAverage 0
  • Repeat the following for each student
  • Get students name
  • Use the algorithm to find the average test score
  • Use the algorithm to find the grade
  • Update totalAverage by adding current students
    average test score
  • Determine the class average as follows
  • classAverage totalAverage / 10

70
Programming Methodologies
  • Two popular approaches to programming design
  • Structured
  • Object-oriented

71
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 programming

72
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

73
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

74
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

75
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

76
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

77
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

78
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

79
Capítulo 2
  • 80-161

80
C Programming From Problem Analysis to Program
Design, Fifth Edition
  • Chapter 2 Basic Elements of C

81
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

82
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

83
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

84
Introduction
  • Computer program
  • Sequence of statements whose objective is to
    accomplish a task
  • Programming
  • Process of planning and creating a program

85
A C Program
  • include ltiostreamgt
  • using namespace std
  • int main()
  • int num
  • num 6
  • cout ltlt "My first C program." ltlt endl
  • cout ltlt "The sum of 2 and 3 " ltlt 5 ltlt endl
  • cout ltlt "7 8 " ltlt 7 8 ltlt endl
  • cout ltlt "Num " ltlt num ltlt endl
  • return 0

86
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 instruction

87
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.
  • /

88
Special Symbols
  • Special symbols
  • -
  • /
  • .

? , lt ! gt
89
Reserved Words (Keywords)
  • Reserved words, keywords, or word symbols
  • Include
  • int
  • float
  • double
  • char
  • const
  • void
  • return

90
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

91
Identifiers (cont'd.)
  • Legal identifiers in C
  • first
  • conversion
  • payRate

92
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

93
Data Types
  • Data type set of values together with a set of
    operations
  • C data types fall into three categories

94
Simple Data Types
  • Three categories of simple data
  • Integral integers (numbers without a decimal)
  • Floating-point decimal numbers
  • Enumeration type user-defined data type

95
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

96
Simple Data Types (cont'd.)
  • Different compilers may allow different ranges of
    values

97
int Data Type
  • Examples
  • -6728
  • 0
  • 78
  • 763
  • Positive integers do not need a sign
  • No commas are used within an integer
  • Commas are used for separating items in a list

98
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

99
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

100
Floating-Point Data Types
  • C uses scientific notation to represent real
    numbers (floating-point notation)

101
Floating-Point Data Types (cont'd.)
  • float represents any real number
  • Range -3.4E38 to 3.4E38 (four bytes)
  • double represents any real number
  • Range -1.7E308 to 1.7E308 (eight bytes)

102
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

103
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

104
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

105
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

106
Mixed Expressions
  • Mixed expression
  • Has operands of different data types
  • Contains integers and floating-point
  • Examples of mixed expressions
  • 2 3.5
  • 6 / 4 3.9
  • 5.4 2 13.6 18 / 2

107
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

108
Type Conversion (Casting)
  • Implicit type coercion when value of one type is
    automatically changed to another type
  • Cast operator provides explicit type conversion
  • static_castltdataTypeNamegt(expression)

109
Type Conversion (cont'd.)
110
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

111
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

112
Allocating Memory with Constants and Variables
  • Named constant memory location whose content
    cant change during execution
  • The syntax to declare a named constant is
  • In C, const is a reserved word

113
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

114
Putting Data into Variables
  • Ways to place data into a variable
  • Use Cs assignment statement
  • Use input (read) statements

115
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

116
Assignment Statement (cont'd.)
117
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

118
Declaring Initializing Variables
  • Variables can be initialized when declared
  • int first13, second10
  • char ch' '
  • double x12.6
  • All variables must be initialized before they are
    used
  • But not necessarily during declaration

119
Input (Read) Statement
  • cin is used with gtgt to gather input
  • The stream extraction operator is gtgt
  • For example, if miles is a double variable
  • cin gtgt miles
  • Causes computer to get a value of type double
  • Places it in the variable miles

120
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 gtgt feet gtgt inches
  • Inputs two integers from the keyboard
  • Places them in variables feet and inches
    respectively

121
Input (Read) Statement (cont'd.)
122
Variable Initialization
  • There are two ways to initialize a variable
  • int feet
  • By using the assignment statement
  • feet 35
  • By using a read statement
  • cin gtgt feet

123
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?

x 5 y x
x 5 y x
124
Output
  • The syntax of cout and ltlt is
  • Called an output statement
  • The stream insertion operator is ltlt
  • Expression evaluated and its value is printed at
    the current cursor position on the screen

125
Output (cont'd.)
  • A manipulator is used to format the output
  • Example endl causes insertion point to move to
    beginning of next line

126
Output (cont'd.)
  • The new line character is '\n'
  • May appear anywhere in the string
  • cout ltlt "Hello there."
  • cout ltlt "My name is James."
  • Output
  • Hello there.My name is James.
  • cout ltlt "Hello there.\n"
  • cout ltlt "My name is James."
  • Output
  • Hello there.
  • My name is James.

127
Output (cont'd.)
128
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

129
Preprocessor Directives (cont'd.)
  • Syntax to include a header file
  • For example
  • include ltiostreamgt
  • Causes the preprocessor to include the header
    file iostream in the program

130
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 ltiostreamgt
  • using namespace std

131
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 ltstringgt

132
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

133
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

134
Creating a C Program (cont'd.)
135
Creating a C Program (cont'd.)
  • Sample Run
  • Line 9 firstNum 18
  • Line 10 Enter an integer 15
  • Line 13 secondNum 15
  • Line 15 The new value of firstNum 60

136
Debugging Understanding and Fixing Syntax Errors
  • Compile a program
  • Compiler will identify the syntax error
  • Specifies the line numbers where the errors occur
  • Example2_Syntax_Errors.cpp
  • c\chapter 2 source code\example2_syntax_errors.cp
    p(9) error C2146 syntax error
  • missing '' before identifier 'num'
  • c\chapter 2 source code\example2_syntax_errors.cp
    p(11) error C2065 'tempNum'
  • undeclared identifier
  • Learn how to spot and fix syntax errors

137
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

138
Syntax
  • Errors in syntax are found in compilation
  • int x //Line 1
  • int y //Line 2 error
  • double z //Line 3
  • y w x //Line 4 error

139
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

140
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

141
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) 5
  • are both syntactically correct expressions, but
    have different meanings

142
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

143
Prompt Lines
  • Prompt lines executable statements that inform
    the user what to do
  • cout ltlt "Please enter a number between 1 and 10
    and "
  • ltlt "press the return key" ltlt endl
  • cin gtgt num

144
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

145
Form and Style
  • Consider two ways of declaring variables
  • Method 1
  • int feet, inch
  • double x, y
  • Method 2
  • int feet,inchdouble x,y
  • Both are correct however, the second is hard to
    read

146
More on Assignment Statements
  • C has special assignment statements called
    compound assignments
  • , -, , /, and
  • Example
  • x y

147
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

148
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

149
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

150
Programming Example Variables and Constants
  • Variables
  • int feet //variable to hold given feet
  • int inches //variable to hold given inches
  • int totalInches //variable to hold total inches
  • double centimeters //variable to hold length in
  • //centimeters
  • Named Constant
  • const double CENTIMETERS_PER_INCH 2.54
  • const int INCHES_PER_FOOT 12

151
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

152
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

153
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

154
Programming Example Body of the Function
  • The body of the function main has the following
    form
  • int main ()
  • declare variables
  • statements
  • return 0

155
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

156
Programming Example Writing a Complete Program
(contd.)
157
Programming Example Sample Run
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
187 The number of centimeters 474.98
158
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

159
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 used

160
Summary (cont'd.)
  • Use cin and stream extraction operator gtgt to
    input from the standard input device
  • Use cout and stream insertion operator ltlt 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

161
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

162
Capítulo 3
  • 163-212
  • Programas simples 213-215
  • Ayuda
  • Primera tarea

163
C Programming From Problem Analysis to Program
Design, Fifth Edition
  • Chapter 3 Input/Output

164
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

165
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

166
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

167
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

168
I/O Streams and Standard I/O Devices (cont'd.)
  • To use cin and cout, the preprocessor
    directive include ltiostreamgt must be used
  • Variable declaration is similar to
  • istream cin
  • ostream cout
  • Input stream variables type istream
  • Output stream variables type ostream

169
cin and the Extraction Operator gtgt
  • The syntax of an input statement using cin and
    the extraction operator gtgt is
  • The extraction operator gtgt is binary
  • Left-side operand is an input stream variable
  • Example cin
  • Right-side operand is a variable

170
cin and the Extraction Operator gtgt (cont'd.)
  • No difference between a single cin with multiple
    variables and multiple cin statements with one
    variable
  • When scanning, gtgt skips all whitespace
  • Blanks and certain nonprintable characters
  • gtgt distinguishes between character 2 and number 2
    by the right-side operand of gtgt
  • If type char or int (or double), the 2 is treated
    as a character or as a number 2

171
cin and the Extraction Operator gtgt (cont'd.)
  • Entering a char value into an int or double
    variable causes serious errors, called input
    failure

172
cin and the Extraction Operator gtgt (cont'd.)
  • When reading data into a char variable
  • gtgt 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
  • gtgt skips leading whitespace, reads or - sign
    (if any), reads the digits (including decimal)
  • Reading stops on whitespace non-digit character

173
cin and the Extraction Operator gtgt (cont'd.)
174
cin and the Extraction Operator gtgt (cont'd.)
175
cin and the Extraction Operator gtgt (cont'd.)
176
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

177
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

178
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

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

181
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

182
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 expression
  • chExp 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

183
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

184
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

185
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

186
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

187
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

188
Output and Formatting Output
  • Syntax of cout when used with ltlt
  • Expression is evaluated
  • Value is printed
  • Manipulator is used to format the output
  • Example endl

189
setprecision Manipulator
  • Syntax
  • Outputs decimal numbers with up to n decimal
    places
  • Must include the header file iomanip
  • include ltiomanipgt

190
fixed Manipulator
  • fixed outputs floating-point numbers in a fixed
    decimal format
  • Example cout ltlt fixed
  • Disable by using the stream member function
    unsetf
  • Example cout.unsetf(iosfixed)
  • The manipulator scientific is used to output
    floating-point numbers in scientific format

191
showpoint Manipulator
  • showpoint forces output to show the decimal point
    and trailing zeros
  • Examples
  • cout ltlt showpoint
  • cout ltlt fixed ltlt showpoint

192
setw
  • Outputs the value of an expression in specific
    columns
  • cout ltlt setw(5) ltlt x ltlt 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

193
Additional Output Formatting Tools
  • Additional formatting tools that give you more
    control over your output
  • setfill manipulator
  • left and right manipulators
  • unsetf manipulator

194
setfill Manipulator
  • Output stream variables can use setfill to fill
    unused columns with a character
  • Example
  • cout ltlt setfill('')

195
left and right Manipulators
  • left left-justifies the output
  • Disable left by using unsetf
  • right right-justifies the output

196
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

197
Input/Output and the string Type
  • An input stream variable (cin) and gtgt 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

198
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

199
File Input/Output
  • File area in secondary storage to hold info
  • File I/O is a five-step process
  • Include fstream header
  • Declare file stream variables
  • Associate the file stream variables with the
    input/output sources
  • Use the file stream variables with gtgt, ltlt, or
    other input/output functions
  • Close the files

200
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

201
Programming Example I/O
  • Inputs movie name, adult and child ticket price,
    adult and child tickets sold, and percentage of
Write a Comment
User Comments (0)
About PowerShow.com