CSE1301 - Kennesaw State University

CSE1301 - Kennesaw State University

Lecture 2A Data Types Richard Gesick Figures from Lewis, C# Software Solutions, Addison Wesley CSE 1311 Topics Character Strings Variables and Assignments Primitive Data Types CSE 1311

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 CSE 1311

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<

CSE 1311 The + Operator What it does depends on the order and the data types String concatenation addition CSE 1311 Escape Sequences To include a special character in a string, use an escape sequence

CSE 1311 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. CSE 1311 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.

CSE 1311 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. CSE 1311 Common C++ Data Types Keyword Example of a literal bool true

char '5' int 25 double 25.0 string "hello" //#include Copyright 2012 Pearson Education, Inc. CSE 1311 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. CSE 1311 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 CSE 1311 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 CSE 1311 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 CSE 1311 Examples: 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; CSE 1311 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 CSE 1311 Once a variable is declared, its data type cannot be changed. These statements: double cashInHand; int cashInHand; generate a compiler error

CSE 1311 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 CSE 1311 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 CSE 1311 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 CSE 1311 Primitive Data Types 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 CSE 1311 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 CSE 1311 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 = 425612340L; float salesTax = .05F; double interestRate = 0.725; double avogadroNumber = +6.022E23;

CSE 1311 char Data Type One ASCII character (8 bits - 1 byte) Example declarations: char finalGrade = A; char newline, tab, doubleQuotes; CSE 1311 bool Data Type Two values only:

true false Used for decision making or as "flag" variables Example declarations: bool isEmpty; bool passed, failed = false; CSE 1311 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". CSE 1311 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? CSE 1311 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() CSE 1311 C-style String Example #include #include //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; } CSE 1311

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). CSE 1311

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. CSE 1311 Common Methods of the string Class

size( ) empty( ) substr (int start, int len) c_str() CSE 1311 Operators Overloaded for the string Class relational operators < >

== <= concatenation + += assignment = CSE 1311 >=

String Class Example #include #include //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; } CSE 1311

Recently Viewed Presentations

  • Diminished citizenship: The impact of restricted welfare rights

    Diminished citizenship: The impact of restricted welfare rights

    Exploring welfare conditionality across a range of policy domains and groups. Recipients of social security benefits (unemployed people, lone parents, disabled people, Universal Credit), homeless people, social tenants, individuals/families subject to antisocial behaviour orders/family intervention projects, offenders and
  • PowerPoint-Präsentation

    PowerPoint-Präsentation

    ESPEN Guidelines History. 1st . round. Guidelines 2006-2009. Based on German guidelines. 2nd . round. Guidelines 2010-2015. Dementia: Clin. Nutr. 2015 . Dec / Epub ...
  • Flourish Toolbox - NHS Gloucestershire CCG

    Flourish Toolbox - NHS Gloucestershire CCG

    It is also an important communication tool from secondary to primary care about the patients treatment and any ongoing support needed. ... Longfield who provide similar services. Support for carers, complimentary therapies. Other organisations eg GL1, walking groups,
  • Pregnancy, Childbirth, and the Puerperium

    Pregnancy, Childbirth, and the Puerperium

    Chapter Seven PREGNANCY, CHILDBIRTH, AND THE PUERPERIUM B. Oligohydramnios * An alpha-fetoprotein test is performed between 14 and 19 weeks of gestation in order to detect conditions such as neural tube defects and multiple gestations.
  • The birth of a Savior - cwchurchofchrist.com

    The birth of a Savior - cwchurchofchrist.com

    Jesus was born to die. The Birth of a Savior. Isaiah 53:2-6. He grew up before him like a tender shoot, and like a root out of dry ground. He had no beauty or majesty to attract us to him,...
  • Todays Agenda: SSO Teacher Side SAM 2007 SSO

    Todays Agenda: SSO Teacher Side SAM 2007 SSO

    Here is an example of a Coursemate. A Coursemate is like a course in a box! It contains a chapter by chapter ebook, variousl learning resources like flashcards, quizzes, videos and the third part of coursemate, is the ENGAGEMENT TRACKER....
  • Using the RE-AIM Framework nd Pragmatic Studies

    Using the RE-AIM Framework nd Pragmatic Studies

    Russ Glasgow via Cara Lewis via …. LINDA-Starting here lots of problems with not being able to rerad text. Working Definitions. Tabak RG et al. Bridging Research and Practice: Models for Dissemination and Implementation Research . Am J . Prev....
  • A Few Issues in Fluid &amp; MHD Turbulence - Yale University

    A Few Issues in Fluid & MHD Turbulence - Yale University

    A few issues in turbulence and how to cope with them using computers Annick Pouquet, NCAR Alex Alexakis!, Julien Baerenzung&, Marc-Etienne Brachet!, Jonathan Pietarila-Graham&&, Aimé Fournier, Darryl [email protected], Giorgio Krstulovic*, Ed Lee#, Bill Matthaeus%, Pablo Mininni^, Jean-François Pinton!!, Hélène Politano*,