Objects Types, Variables, and Constants 1 Chapter 3.

Slides:



Advertisements
Similar presentations
1 © 1998, 2001, 2002Calvin College, Keith Vander Linden, Jeremy D. Frens, Larry R. Nyhoff Objects (Chap. 2) Variables and Constants.
Advertisements

CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
Types and Variables. Computer Programming 2 C++ in one page!
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Announcements Quiz 1 Next Week. int : Integer Range of Typically -32,768 to 32,767 (machine and compiler dependent) float : Real Number (i.e., integer.
1 9/8/08CS150 Introduction to Computer Science 1 Data Types Section 2.7 – 2.12 CS 150 Introduction to Computer Science I.
1 Lecture 3 Bit Operations Floating Point – 32 bits or 64 bits 1.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Data types and variables
The Fundamentals of C++ Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc.
Overview of C++ Chapter 2 in both books programs from books keycode for lab: get Program 1 from web test files.
CS150 Introduction to Computer Science 1
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
First Program in C With Output. C Language Keywords.
Objectives You should be able to describe: Data Types
CPS120: Introduction to Computer Science Lecture 8.
Simple Data Type Representation and conversion of numbers
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
1 Workshop Topics - Outline Workshop 1 - Introduction Workshop 2 - module instantiation Workshop 3 - Lexical conventions Workshop 4 - Value Logic System.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Input & Output: Console
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Chapter 6 Fundamental Types Dept of Computer Engineering Khon Kaen University.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
COSC1557: Introduction to Computing Haibin Zhu, PhD. Professor Department of Computer Science Nipissing University (C) 2014.
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 2 Variables.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Comments Allow prose or commentary to be included in program Importance Programs are read far more often than they are written Programs need to be understood.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
Objects Variables and Constants. Our Scuba Problem #include // cin, cout, > using namespace std; int main() { const double FEET_PER_ATM = 33.0, LBS_PER_SQ_IN_PER_ATM.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
1 Objects Types, Variables, and Constants Chapter 3.
A Sample Program #include using namespace std; int main(void) { cout
7. BASIC TYPES. Systems of numeration Numeric Types C’s basic types include integer types and floating types. Integer types can be either signed or unsigned.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
1 CE 454 Computer Architecture Lecture 4 Ahmed Ezzat The Digital Logic, Ch-3.1.
Chapter 2 Variables.
Chapter 1.2 Introduction to C++ Programming
ECE Application Programming
Documentation Need to have documentation in all programs
What to bring: iCard, pens/pencils (They provide the scratch paper)
Chapter 2: Introduction to C++
Introduction to Abstract Data Types
Chapter 2 Variables.
Chapter 2: Introduction to C++.
Unit 3: Variables in Java
Chapter 2 Variables.
The Fundamentals of C++
ECE 120 Midterm 1 HKN Review Session.
Presentation transcript:

Objects Types, Variables, and Constants 1 Chapter 3

Overview of C++ Statements 2 C++ Statements Declarations;Expressions; Other Objects Operations

Expressions In a C++ program, any finite sequence of objects and operations that combine to produce a value is called an expression. Examples from our temperature problem: 1.8 * celsius 1.8 * celsius Even: 1.8; 32; "Hello"; 1 + 1; ;;;; We focus now on C++ objects and will look at operations later. 1.8 fahrenheit = 1.8 * celsius + 32 Aside #1: expression ; is a statement.) Aside #2: expressions may be empty

Object Categories There are three kinds of objects: Literals: unnamed objects having a value ( 0, -3, 2.5, 2.998e8, 'A', "Hello\n",... ) Variables: named objects whose values can change during program execution Constants: named objects whose values cannot change during program execution 4 See Footnote on p. 48 Study §3.2 Have memory allocated to them

Literals – literals are integers: –int literals are integers: -27, 0, 4, +4 or E – There are just two bool literals: false, true 5 Enclose in ' Enclose in " – char literals are single characters: 'A', 'a', '9', '$', '?',... – string literals are sequences of characters: " Hello", "Goodbye", "Goodbye\n" 5 basic types literals are real numbers, and can be: –double literals are real numbers, and can be: fixed-point:,... fixed-point: , 0.5, 1.414,... floating-point:,... floating-point: 2.998e8, e9,... Not inter- changeable Some Variations: unsigned, long, short Variations: float, long double

Variable Declarations Examples: int idNumber; int age = 18; double celsius, kelvin = 0; cin >> celsius; double fahrenheit = 1.8 * celsius + 32; char letterGrade = 'A'; bool ok, done = false; 6 Declare only once Variables are used to store values, and can be either uninitialized or initialized. They must be before they are used. Variables are used to store values, and can be either uninitialized or initialized. They must be declared before they are used. Pattern: Pattern: type name; type name = expression; Allocates a memory location for values of this type and associates its address with name Not a declaration

Assignment Statements Examples: age = 19; celsius = 1.1 * celsius; letterGrade = 'B'; done = true; 7 Pattern: Pattern: name = expression; The value of a variable can be changed during execution by an assignment statement. Changes value in name's memory location to value of expression

Constant Declarations const char MIDDLE_INITIAL = 'A'; const string PROMPT = "Enter a number: "; 8 Pattern: Pattern: const type NAME = expression; Constants are used to represent a value with a meaningful name, and must be initialized. They cannot be changed later. Could use in Proj. 1.3 Examples: const int MAX_SCORE = 100; const double PI = ; Allocates a memory location for values of this type, associates its address with NAME, puts value of expression in it, and locks it.

Identifiers The name of an object is called an (because it identifies the object). The name of an object is called an identifier (because it identifies the object). C++ identifiers must begin with a letter (underscores are permitted, but discouraged) followed by zero or more letters, digits or underscores. Valid:,... Valid: age, r2d2, myGPA, MAX_SCORE,... Invalid:,... Invalid: 123go, coffee-time, sam's, $name,... 9 May not be C++ keywords (See Appendix B) See slide 24

Conventions We will use the following commonly-used convention to keep variable and constant objects distinct. Constant names: all uppercase, with multiple words separated by underscores (e.g., )Constant names: all uppercase, with multiple words separated by underscores (e.g., MAX_SCORE ) Variable names: all lowercase, but the first letter of each word after the first capitalized (e.g., )Variable names: all lowercase, but the first letter of each word after the first capitalized (e.g., lastName ) 10 Use meaningful identifiers for readability! “camelback” notation

Represented in memory by a code. – –ASCII uses 8 bits (1 byte) to represent a character, allowing for 2 8 = 256 different characters. Objects char Objects 'a' = 97 = '0' = 48 = p. 61 App. A Java chars can be treated as small integers; e.g,. char ch1 = 'A', ch2; int x = 2*ch1 + 1; ch2 = ch1 + 1; cout << x << ' ' << ch2 << '\n'; Output? 131 B = Most used code is ASCII: Most commonly used code is ASCII: 'A' = –Unicode's first version used 16 bits to represent a character, allowing for 2 16 = 65,536 different characters. Now, 16, 24, or 32 bits. See Other Course Information class page

Escape Characters C++ provides a number of : C++ provides a number of escape characters: 12 '\n' newline character '\t' horizontal tab '\v' vertical tab '\f' form feed '\a' alert/bell '\\' backslash char '\'' apostrophe '\"' double quote '\ooo' char with octal code ooo '\xhhh' char with hex code hhh See Appendix A

Objects int Objects Three forms: –decimal (base-10): begin with a digit or sign (-45, -2, 0, +21, 36, 65536,...) –decimal (base-10): 0 or begin with a nonzero digit or sign (-45, -2, 0, +21, 36, 65536,...) –octal (base-8): begin with a followed by digits (01, 02, 03, 04, 05, 06, 07, –octal (base-8): begin with a 0 followed by octal digits (01, 02, 03, 04, 05, 06, 07, 010, 011, 012,..., 017, 020, 021, …) 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11,...) –hexadecimal (base-16): begin with followed by digits with a, b, c, d, e, f = 10, 11, 12, 13, 14, 15 (0x1, 0x2,..., 0x7, 0x8, 0x9, –hexadecimal (base-16): begin with 0x followed by digits with a, b, c, d, e, f = 10, 11, 12, 13, 14, 15 (0x1, 0x2,..., 0x7, 0x8, 0x9, 13 See second item on Other Course Information class page

Objects unsigned Objects For objects whose values are never negative, C++ provides the unsigned type. They also may be expressed in decimal, octal, and hexadecimal forms. The major advantage of using unsigned instead of int when values being processed are known to be nonnegative is that larger values can be stored. 14

Ranges of Integer Values Using 32 bits, int values range from ( ) to ( ); unsigned values range from 0 to ( ). An int value "loses" one of its bits to the sign, and so the maximum int value is about half of the maximum unsigned value. 15 INT_MIN defines INT_MIN, INT_MAX, UINT_MAX, and other constants that specify ranges of C++ integers; does this for C++ real values. (See App. D) UINT_MAXINT_MAX

16 //-- Program to demonstrate the effects of overflow #include using namespace std; int main() { int number = 2; for (int i = 1; i <= 15; i = i + 1) { cout << number << '\n'; number = 10 * number; } Output: Strange Behavior of Integer Overflowoverflow Overflow: when a value gets out of range; for example, an integer exceeds INT_MAX = =

17 //-- Program to demonstrate the modular "wrap-around" effect of overflow #include using namespace std; int main() { int number = INT_MAX - 3; for (int i = 1; i <= 7; i = i + 1) { cout << number << '\n'; number = number + 1; } Output: Why this strange behavior? Check INT_MAX + 1, INT_MAX + 2,... INT_MAX INT_MIN Arithmetic is modular INT_MIN... INT_MAX

Representation int Representation Integers are often represented internally in the format, where the high- order (leftmost) bit indicates the number’s sign: twos-complement format, where the high- order (leftmost) bit indicates the number’s sign: 2 10 = = = = = Here we show 16 bits, but 32 or 64 are more common. 18 Sec. 3.3

Two's-Complement To find twos-complement representation of a negative number (e.g., -12): Represent its absolute value in binary: ( ) ( ) Invert (complement) the bits: ( ) ( ) Add 1 19 ( ) ( ) Simpler: Flip all bits to the left of rightmost 1. Stop here for nonnegative numbers Try practice exercises — Week 3 of schedule

* : –6:  carry bits Why Use Two's Complement? Because usual algorithms for +, * work!

Objects double Objects =  sign (1 bit) mantissa (52 bits) exponent (11 bits) Real values are often represented in 64 bits using the IEEE floating point standard: 5.75 = See Ch. 3, pp float (single precision): bias = 127; exponent: 8 bits mantissa: 23 bits Try practice exercises on course schedule "bias" +

22 //-- Effect of roundoff error #include using namespace std; int main() { for (double x = 0; x != 50.0; x = x + 0.1) { doouble y = x * sqrt(1 + sin(x)); cout << x << " " << y << '\n'; //if (x > 60) break; } Execution: So they can't be stored exactly; error in this representation is called roundoff error. Patriot missile failure See Other Course Information Problem:Binary representations of most real numbers do not terminate; e.g., 13.1 = …

23 /* temperature.cpp converts a Celsius temperature to Fahrenheit. John Doe Lab 1 Jan. 6, 2011 CPSC 104X Input: A Celsius temperature Output: Corresponding Fahrenheit temperature */ #include // cin, cout, > using namespace std; int main() { cout << "John Doe CPSC 104X -- Lab 1\n\n"; cout << "** Convert Celsius temps to Fahrenheit **\n"; cout << "Please enter a temperature in Celsius: "; double celsius; cin >> celsius; double fahrenheit = 1.8 * celsius + 32; cout << celsius << " degrees Celsius is " << fahrenheit << " degrees Fahrenheit.\n"; }

24 The name of the song is called "Haddocks' Eyes". "Oh, that's the name of the song, is it?" Alice said, trying to feel interested. "No, you don't understand," the Knight said, looking a little vexed. "That's what the name is called. The name really is 'The Aged Aged Man'." 'Then I ought to have said, "That's what the song is called"?' Alice corrected herself. "No, you oughtn't: that's quite another thing! The song is called 'Ways and Means': but that's only what it's called, you know!" "Well, what is the song, then?" said Alice, who was by this time completely bewildered. "I was coming to that," the Knight said. "The song really is 'A-Sitting On a Gate': and the tune's my own invention." Lewis Carroll, Through The Looking Glass The name of the student's letter grade is called " letterGrade." "Oh, that's the name of the student's letter grade, is it?" Alice said, trying to feel interested. "No, you don't understand," the Knight said, looking a little vexed. "That's what the name is called. The name really is 0x123abc, a memory location that stores the student's letter grade." 'Then I ought to have said, "The student's letter grade is 0x123abc"? Alice corrected herself. "No, you oughtn't: that's quite another thing! The student's letter grade is called 'A': but that's only what it's called, you know!" "Well, what is the letter grade, then?" said Alice, who was by this time completely bewildered. "I was coming to that," the Knight said. "The student's letter grade really is and it's my own initialization."

A int age: 0xbfe0b82c int idNumber: 0xbfe0b828 int x: 0xbfe0b824 int y: 0xbfe0b820 double celsius: 0xbfe0b818 double kelvin: 0xbfe0b810 double fahrenheit: 0xbfe0b808 char letterGrade: 0xbfe0b807 char a: 0xbfe0b806 char b: 0xbfe0b805 char c: 0xbfe0b804 bool ok: 0xbfe0b803 bool done: 0xbfe0b802 bool d: 0xbfe0b801 bool e: 0xbfe0b800 int age = 18; int idNumber, x, y; double celsius = 0, kelvin = 0; double fahrenheit = 1.8 * celsius + 32; char letterGrade = 'A', a, b, c; bool ok, done = false, d, e; int age: 0012FF60 int idNumber: 0012FF54 int x: 0012FF48 int y: 0012FF3C double celsius: 0012FF2C double kelvin: 0012FF1C double fahrenheit: 0012FF0C char letterGrade: 0012FF03 char a: 0012FEF7 char b: 0012FEEB char c: 0012FEDF bool ok: 0012FED3 bool done: 0012FEC7 bool d: 0012FEBB bool e: 0012FEAF Press any key to continue... Unix/Linux Visual C++

B Enter character (* to stop): A Enter character (* to stop): B Enter character (* to stop): C Enter character (* to stop): Z Enter character (* to stop): a Enter character (* to stop): ; Enter character (* to Enter character (* to stop): *

C Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): Enter number (-999 to stop): -999

D Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): Enter number (-99 to stop): -99

E #include using namespace std; int main() { cout << "INT_MAX = " << INT_MAX << endl << "INT_MIN = " << INT_MIN << endl << "UINT_MAX = " << UINT_MAX << endl << "SHRT_MAX = " << SHRT_MAX << endl << "SHRT_MIN = " << SHRT_MIN << endl << "LONG_MAX = " << LONG_MAX << endl << "LONG_MIN = " << LONG_MIN << endl << "CHAR_MAX = " << CHAR_MAX << endl << "CHAR_MIN = " << CHAR_MIN << endl << "FLT_MAX = " << FLT_MAX << endl << "FLT_MIN = " << FLT_MIN << endl << "DBL_MAX = " << DBL_MAX << endl << "DBL_MIN = " << DBL_MIN << endl << "LDBL_MAX = " << LDBL_MAX << endl << "LDBL_MIN = " << LDBL_MIN << endl << "FLT_EPSILON = " << FLT_EPSILON << endl << "DBL_EPSILON = " << DBL_EPSILON << endl << "LDBL_EPSILON = " << LDBL_EPSILON << endl; } INT_MAX = INT_MIN = UINT_MAX = SHRT_MAX = SHRT_MIN = LONG_MAX = LONG_MIN = CHAR_MAX = 127 CHAR_MIN = -128 FLT_MAX = e+038 FLT_MIN = e-038 DBL_MAX = e+308 DBL_MIN = e-308 LDBL_MAX = e+308 LDBL_MIN = e-308 FLT_EPSILON = e-007 DBL_EPSILON = e-016 LDBL_EPSILON = e-016

F #include using namespace std; int main() { for (double x = 0; x != 50.0; x = x +.01) { double y = x * sqrt(1 + sin(x)); cout << x << " " << y << endl; }