Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 2A Data Types Richard Gesick

Similar presentations


Presentation on theme: "Lecture 2A Data Types Richard Gesick"— Presentation transcript:

1 Lecture 2A Data Types Richard Gesick
Figures from Lewis, “C# Software Solutions”, Addison Wesley

2 Topics Character Strings Variables and Assignments
Primitive Data Types

3 Character Strings In C++, defined by either of 2 classes, cstring which is null terminated ‘\0’ and the string class which is not null terminated String literal is 0 or more characters enclosed with double quotes “The quick brown fox jumped.” “x” “” Can contain any valid character

4 string Concatenation Operator (+)
String literals cannot span lines Combines string literals with other data types for printing Example: string hello = "Hello"; string there = "there"; string greeting = hello + ' ' + there; cout<<greeting ; Output is: Hello there

5 The + Operator What it does depends on the order and the data types
String concatenation addition

6 Escape Sequences To include a special character in a string, use an escape sequence

7 Copyright © 2012 Pearson Education, Inc.
Declarations A type declaration statement defines new identifiers and allocates memory. Multiple variables can be created in 1 declaration An initial value may be assigned to a memory location at the time an identifier is defined. Syntax [modifier] type specifier identifier [= initial value]; [modifier] type specifier identifier[(initial value)]; Examples double x1, y1(0); int counter=0; const int MIN_SIZE=0; bool error(false); char comma(','); Copyright © 2012 Pearson Education, Inc.

8 Initial Values C++ does not provide initial values for variables.
Thus using the value of a variable before it is initialized may result in ‘garbage’.

9 Literals and Variables
Literals are objects that store specific data that can not be modified. 10 is an integer literal 4.5 is a floating point literal "The distance between the two points is" is a string literal 'a' is a character literal Variables are named memory locations that store values that can be modified. double x1(1.0), x2(4.5), side1; side1 = x2 - x1; x1, x2 and side1 are examples of variables that can be modified.

10 Copyright © 2012 Pearson Education, Inc.
Common C++ Data Types Keyword Example of a literal bool true char '5' int 25 double 25.0 string "hello" //#include<string> Copyright © 2012 Pearson Education, Inc.

11 Copyright © 2012 Pearson Education, Inc.
Symbolic Constants A symbolic constant is defined in a declaration statement using the modifier const. A symbolic constant allocates memory for an object that can not be modified during execution of the program. Any attempt to modify a constant will be flagged as a syntax error by the compiler. A symbolic constant must be initialized in the declaration statement. Copyright © 2012 Pearson Education, Inc.

12 C++ Identifiers Should be carefully chosen to reflect the contents of the object. The name should also reflect the units of measurements when applicable. Must be declared (and therefore typed) before they may be used. C++ is a strongly typed programming language. Avoid names similar to C++ reserved words

13 Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type

14 Assignment Operator Syntax: target = expression; expression: operators and operands that evaluate to a single value --value is then assigned to target --target must be a variable (or constant) --value must be compatible with target's data type

15 Examples: The next statement is illegal
int numPlayers = 10; // numPlayers holds 10 numPlayers = 8; // numPlayers now holds 8 int legalAge = 18; int voterAge = legalAge; The next statement is illegal int height = weight * 2; // weight is not defined int weight = 20;

16 Declare a variable only once
Once a variable is declared, its data type cannot be changed. These statements: double twoCents; double twoCents = .02; generate a compiler error

17 Once a variable is declared, its data type cannot be changed.
These statements: double cashInHand; int cashInHand; generate a compiler error

18 Constants Constants are useful for three important reasons
First, they give meaning to otherwise unclear literal values For example, MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be updated in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers

19 Conventions Use all capital letters for constants and separate words with an underscore: Example: const double TAX_RATE = .05; Declare constants at the top of the program so their values can easily be seen Declare as a constant any data that should not change during program execution

20 Data Types For all data, assign a name (identifier) and a data type
Data type tells compiler: How much memory to allocate Format in which to store data Types of operations you will perform on data Compiler monitors use of data C++ is a "strongly typed" language

21 Primitive Data Types Everything else is an object
3 subsets of integers short, int, long (signed or unsigned) 3 subsets of floating point numbers float, double, long double character bool Everything else is an object

22 Why so many types? Difference is in amount of memory reserved for each (and hence the size of the value stored float only has 7 significant digits Signed numbers have both positive and negative values Unsigned numbers are >= 0

23 Literals All numeric values without a decimal point are considered int
All numeric values with decimal point are considered double int testGrade = 100; long cityPopulation = L; float salesTax = .05F; double interestRate = 0.725; double avogadroNumber = E23;

24 char Data Type One ASCII character (8 bits - 1 byte)
Example declarations: char finalGrade = ‘A’; char newline, tab, doubleQuotes;

25 bool Data Type Two values only:
true false Used for decision making or as "flag" variables Example declarations: bool isEmpty; bool passed, failed = false;

26 C-style Character Strings
A C style strings is defined as a sequence of characters, terminated by the null character. When declaring a character array to store a C style string, memory must be allocated for the null character ('\0'). Literal string constants are enclosed within double quote marks: "a string".

27 C-style String Input Recall that the input operator (>>) skips whitespace . To input strings with embedded whitespace , the getline() function can be used as illustrated: char phrase[SIZE]; cin.getline(phrase, SIZE); The getline() function reads up to SIZE-1 characters from the input stream and will insert the null character. getline() is a member function of what class?

28 C-style String Functions
The Standard C++ library contains a set of predefined functions that operate on C style strings. These functions are defined in the header file: cstring Commonly used string functions: strlen() strcpy() strcat() strcmp()

29 C-style String Example
#include <iostream> #include <cstring> //strcmp(), strcpy(), strcat() uses namespace std; void main() { char str1[30] = "John", str2[30] = "Johnson"; char phrase[20] = "'s shirt was green", sentence[30]; if (strcmp(str1,str2) < 0) strcpy (sentence, str1);//puts "John" into sentence else strcpy (sentence,str2);//puts "Johnson” into sentence strcat(sentence, phrase);//append phrase to sentence cout << "Sentence is: " << sentence << endl; }

30 Avoiding Bugs The null character ( ‘\0’ ) must always mark the end of the string. If there is no null character, functions will produce invalid references that can be difficult to identify (remember that C-style strings are 1D arrays of characters). String sizes are fixed. Input operator does NOT ‘know’ what the array size is; input may result in overflow of the array (invalid references).

31 The String Class The string class implements the concept of a character string. A string object can increase and decrease its size dynamically. Numerous operators and methods are defined in the string class.

32 Common Methods of the string Class
size( ) empty( ) substr (int start, int len) c_str()

33 Operators Overloaded for the string Class
relational operators < > == <= >= concatenation + += assignment =

34 String Class Example #include <iostream> #include <string> //string class uses namespace std; void main() { string str1 = "John", str2 = "Johnson"; string phrase = "'s shirt was green", sentence; if ( str1< str2 ) sentence = str1;//puts "John" into sentence else sentence = str2;//puts "Johnson” into sentence sentence += phrase; //append phrase to sentence cout << "Sentence is: " << sentence << endl; }


Download ppt "Lecture 2A Data Types Richard Gesick"

Similar presentations


Ads by Google