Chapter 3 Assignment and Interactive Input

Slides:



Advertisements
Similar presentations
Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
Advertisements

CS1 Lesson 3 Expressions and Interactivity CS1 -- John Cole1.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Basic Elements of C++ Chapter 2.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Objectives You should be able to describe: Data Types
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Operaciones y Variables
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Chapter 2: Using Data.
計算機程式語言 Lecture 03-1 國立臺灣大學生物機電系 3 3 Assignment, Formatting, and Interactive Input.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
A FIRST BOOK OF C++ CHAPTER 3 ASSIGNMENT AND INTERACTIVE INPUT.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 3 Expressions and Interactivity.
Expressions and Interactivity. 3.1 The cin Object.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Recap……Last Time [Variables, Data Types and Constants]
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
CMPSC 121- Spring 2015 Lecture 6 January 23, 2015.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Chapter 4: Introduction To C++ (Part 3). The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 3 Assignment and Interactive Input.
Completing the Problem-Solving Process
Objectives You should be able to describe: Interactive Keyboard Input
Programming Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Basic Elements of C++ Chapter 2.
Expressions and Interactivity
Introduction to C++ Programming
A First Book of ANSI C Fourth Edition
Chapter 3: Input/Output
C++ Programming Basics
C++ for Engineers and Scientists Second Edition
Presentation transcript:

Chapter 3 Assignment and Interactive Input A First Book of C++ Chapter 3 Assignment and Interactive Input

Objectives In this chapter, you will learn about: Assignment Operators Formatted Output Mathematical Library Functions Interactive Keyboard Input Symbolic Constraints Common Programming Errors Errors, Testing, and Debugging A First Book of C++ 4th Edition

Assignment Operators Basic assignment operator Format: variable = expression; Computes value of expression on right of = sign, assigns it to variable on left side of = sign If not initialized in a declaration statement, a variable should be assigned a value before used in any computation Variables can only store one value at a time Subsequent assignment statements will overwrite previously assigned values A First Book of C++ 4th Edition

Assignment Operators (cont'd.) Operand to right of = sign can be: A constant A variable A valid C++ expression Operand to left of = sign must be a variable If operand on right side is an expression: All variables in expression must have a value to get a valid result from the assignment A First Book of C++ 4th Edition

Assignment Operators (cont'd.) Expression: combination of constants and variables that can be evaluated Examples: sum = 3 + 7; diff = 15 –6; product = .05 * 14.6; tally = count + 1; newtotal = 18.3 + total; average = sum / items; slope = (y2 – y1) / (x2 – x1); A First Book of C++ 4th Edition

Assignment Operators (cont'd.) A First Book of C++ 4th Edition

Coercion Value on right side of a C++ expression is converted to data type of variable on the left side Example: If temp is an integer variable, the assignment temp = 25.89; causes integer value 25 to be stored in integer variable temp A First Book of C++ 4th Edition

Assignment Variations sum = sum + 10; is a valid C++ expression The value of sum + 10 is stored in variable sum Not a valid algebra equation A First Book of C++ 4th Edition

Assignment Variations (cont'd.) A First Book of C++ 4th Edition

Assignment Variations (cont'd.) A First Book of C++ 4th Edition

Assignment Variations (cont'd.) Assignment expressions such as: sum = sum + 25; can be written by using the following shortcut operators: += -= *= /= %= Example: sum = sum + 10; can be written as: sum += 10; A First Book of C++ 4th Edition

Accumulating The following statements add the numbers 96, 70, 85, and 60 in calculator fashion: A First Book of C++ 4th Edition

Accumulating (cont'd.) A First Book of C++ 4th Edition

Counting Has the form: Increment operators (++), (--) variable = variable + fixedNumber; Each time statement is executed, value of variable is increased by a fixed amount Increment operators (++), (--) Unary operator for special case when variable is increased or decreased by 1 Using the increment operator, the expression: variable = variable + 1; can be replaced by either: ++variable; or variable++; A First Book of C++ 4th Edition

Counting (cont'd.) Examples of counting statements: i= i + 1; n = n + 1; count = count + 1; j = j + 2; m = m + 2; kk = kk + 3; A First Book of C++ 4th Edition

Counting (cont'd.) Examples of the increment operator: A First Book of C++ 4th Edition

Counting (cont'd.) A First Book of C++ 4th Edition

Counting (cont'd.) Prefix increment operator: the ++ or -- operator appears before a variable The expression k = ++n performs two actions: n = n + 1; // increment n first k = n; // assign n’s value to k Postfix increment operator: the ++ or -- operator appears after a variable The expression k = n++ works differently: k = n; // assign n’s value to k n = n + 1; // and then increment n A First Book of C++ 4th Edition

Formatted Output A program must present results attractively Field width manipulators: control format of numbers displayed by cout Manipulators included in the output stream A First Book of C++ 4th Edition

Formatted Output (cont'd.) A First Book of C++ 4th Edition

A First Book of C++ 4th Edition

The setiosflags() Manipulator Field justification manipulator Example: cout << “|” << setw(10) << setiosflags(ios::left) << 142 << “|”; A First Book of C++ 4th Edition

Hexadecimal and Octal I/O oct and hex manipulators are used for conversions to octal and hexadecimal Display of integer values in one of three possible numbering systems (decimal, octal, and hexadecimal) doesn’t affect how the number is stored in a computer All numbers are stored by using the computer’s internal codes A First Book of C++ 4th Edition

Hexadecimal and Octal I/O (cont'd.) A First Book of C++ 4th Edition

A First Book of C++ 4th Edition

Hexadecimal and Octal I/O (cont'd.) A First Book of C++ 4th Edition

Mathematical Library Functions Standard preprogrammed functions that can be included in a program Example: sqrt(number) calculates the square root of number Table 3.5 lists more commonly used mathematical functions provided in C++ To access these functions in a program, the header file cmath must be used Format: #include <cmath> <- no semicolon A First Book of C++ 4th Edition

Mathematical Library Functions (cont'd.) Before using a C++ mathematical function, the programmer must know: Name of the desired mathematical function What the function does Type of data required by the function Data type of the result returned by the function A First Book of C++ 4th Edition

Mathematical Library Functions (cont'd.) A First Book of C++ 4th Edition

Mathematical Library Functions (cont'd.) A First Book of C++ 4th Edition

Mathematical Library Functions (cont'd.) A First Book of C++ 4th Edition

Mathematical Library Functions (cont'd.) A First Book of C++ 4th Edition

Casts Cast: forces conversion of a value to another type Two versions: compile-time and runtime Compile-time cast: unary operator Syntax: dataType (expression) expression converted to data type of dataType Run-time cast: requested conversion checked at runtime, applied if valid Syntax: staticCast<dataType> (expression) expression converted to data type dataType A First Book of C++ 4th Edition

Interactive Keyboard Input If a program only executes once, data can be included directly in the program If data changes, program must be rewritten Capability needed to enter different data cin object: used to enter data while a program is executing Example: cin >> num1; Statement stops program execution and accepts data from the keyboard A First Book of C++ 4th Edition

Interactive Keyboard Input (cont'd.) A First Book of C++ 4th Edition

Interactive Keyboard Input (cont'd.) First cout statement in Program 3.8 prints a string Tells the person at the terminal what to type A string used in this manner is called a prompt Next statement, cin, pauses computer Waits for user to type a value User signals the end of data entry by pressing Enter key Entered value stored in variable to right of extraction symbol Computer comes out of pause and goes to next cout statement A First Book of C++ 4th Edition

A First Look at User-Input Validation A well-constructed program should validate all user input Ensures that program does not crash or produce nonsensical output Robust programs: programs that detect and respond effectively to unexpected user input Also known as “bulletproof” programs User-input validation: checking entered data and providing user with a way to reenter invalid data A First Book of C++ 4th Edition

Symbolic Constants Magic numbers: literal data used in a program Some have general meaning in context of program Tax rate in a program to calculate taxes Others have general meaning beyond the context of the program π = 3.1416; Euler’s number = 2.71828 Constants can be assigned symbolic names const float PI = 3.1416f; const double SALESTAX = 0.05; A First Book of C++ 4th Edition

Symbolic Constants (cont'd.) const: qualifier specifies that the declared identifier cannot be changed A const identifier can be used in any C++ statement in place of number it represents circum = 2 * PI * radius; amount = SALESTAX * purchase; const identifiers commonly referred to as: Symbolic constants Named constants A First Book of C++ 4th Edition

Placement of Statements A variable or symbolic constant must be declared before it is used C++ permits preprocessor directives and declaration statements to be placed anywhere in program Doing so results in very poor program structure A First Book of C++ 4th Edition

Placement of Statements (cont'd.) As a matter of good programming practice, the order of statements should be: preprocessor directives int main() { // symbolic constants // variable declarations // other executable statements return 0; } A First Book of C++ 4th Edition

Placement of Statements (cont'd.) A First Book of C++ 4th Edition

Common Programming Errors Forgetting to assign or initialize values for all variables before they are used in an expression Using a mathematical library function without including the preprocessor statement #include <cmath> Using a library function without providing the correct number of arguments of the proper data type Applying increment or decrement operator to an expression A First Book of C++ 4th Edition

Common Programming Errors (cont'd.) Forgetting to use the extraction operator, >>, to separate variables in a cin statement Using an increment or decrement operator with variables that appear more than once in the same statement Being unwilling to test a program in depth A First Book of C++ 4th Edition

Summary Expression: sequence of operands separated by operators Expressions are evaluated according to precedence and associativity of its operands The assignment symbol, =, is an operator Assigns a value to variable Multiple assignments allowed in one statement Increment operator(++): adds 1 to a variable Decrement operator(--): subtracts 1 from a variable A First Book of C++ 4th Edition

Summary (cont'd.) Increment and decrement operators can be used as prefixes or postfixes C++ provides library functions for various mathematical functions These functions operate on their arguments to calculate a single value Arguments, separated by commas, included within parentheses following function’s name Functions may be included within larger expressions A First Book of C++ 4th Edition

Summary (cont'd.) cin object used for data input cin temporarily suspends statement execution until data entered for variables in cin function Good programming practice: prior to a cin statement, display message alerting user to type and number of data items to be entered Message called a prompt Values can be equated to a single constant by using the const keyword A First Book of C++ 4th Edition

Chapter Supplement: Errors, Testing, and Debugging Program errors can be detected: Before a program is compiled While the program is being compiled While the program is running After the program has been run and the output is being examined Desk checking Method for detecting errors before a program is compiled Program verification and testing A First Book of C++ 4th Edition

Compile-Time and Runtime Errors Compile-time errors Errors detected while a program is being compiled No one but the programmer ever knows they occurred Runtime errors Errors that occur while a program is running More troubling because they occur while a user is running the program Can be caused by program or hardware failures A First Book of C++ 4th Edition

Syntax and Logic Errors Syntax error Error in ordering valid language elements in a statement or the attempt to use invalid language elements Logic error Characterized by erroneous, unexpected, or unintentional output that’s a result of some flaw in the program’s logic A First Book of C++ 4th Edition

Testing and Debugging Program testing should be well thought out to maximize the possibility of locating errors Bug: a program error Debugging Process of isolating and correcting the error and verifying the correction Program tracing Process of imitating the computer by executing each statement by hand as the computer would Echo printing A First Book of C++ 4th Edition