c++ basics cs 1428 week 2 texas state university tom o’hara spring 2011
TRANSCRIPT
C++ BasicsC++ BasicsCS 1428 Week 2
Texas State UniversityTom O’HaraSpring 2011
Important topics from week Important topics from week 11Basic computer organization
◦von Neumann architecture◦CPU, registers, memory, etc.
Algorithm versus program◦Top-down stepwise refinement◦Program syntax
C versus C++
Lecture OverviewLecture OverviewC++ program structurePreprocessorData types overviewConstantsVariablesData type detailsC++ Gotcha’s
Common Program Common Program StructureStructure
Program header
Main function:
Start of block
Declarations
Input
Processing
Output
Exit code
End of block
#include <iostream>
using namespace std;
int main ()
{
double celsius, fahrenheit;
cin >> celsius:
fahrenheit = 9.0/5*celsius+32;
cout << fahrenheit;
return (0);
}
Skeleton ProgramsSkeleton ProgramsTemplates with “fill in the blanks”Useful for simple programsAvoids compilation errors due to
typo’s◦#'s, <'s, etc. wreak havoc on poor
typists!Customize yourself on ongoing basis
◦Add name, email alias, etc.◦Revise based on code typed over and
over again
Sample C++ Program Sample C++ Program SkeletonSkeleton
// <program description goes here>
#include <cstdlib> // Common routines like system
#include <iostream> // I/O streams cout & cin
using namespace std; // Import standard namespace
int main ()
{
<variable declarations and initializations go here>
<program statements go here>
// Exit with successful execution statussystem("PAUSE"); // wait for user (for Dev C+
+)return (0);
}
PreprocessingPreprocessingInclusion Files (“header files”)
◦Tells compiler which library packages required
#include <iostream>FYI: Text substitutions
◦Poor man's symbolic constants#define PI 3.14159
◦Efficient alternative to functions#define MAX(x,y) (x > y ? x : y)
◦Not recommended (esp. for beginners)! C++ has good alternatives to each of these
Data typesData typesIn memory, data is all the same: 1's
& 0'sLanguages provide common
abstractions◦Numeric
integers {..., -2, -1, 0, 1, 2, ...}
real numbers (e.g., 3.15159, 6.022x1023)
◦Textual (single) characters {'A', 'B', 'C', ...}
strings (e.g., “home address", "C++")
C++ Constants (aka C++ Constants (aka literals)literals)Values that never changeIntegers: [sign]digit...
7 13 -1 +100000
Reals: [sign]digit...[point]digit...[e[sign]digit...]
-7.0 1e9 0.5 6.022e23 -1.75e-50
Characters: 'character''A' 'b' ''©'' ' '
Strings: "character...""San Marcos, TX" "Jane Doe" ""
Syntax NotationSyntax Notation◦category italicized text indicates a type
digit one of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}◦text boldface text must be specified as is
if the keyword 'if' (used in decisions)◦x | y a choice between item x or y
+|- numeric sign (i.e., a plus or minus)◦[specification] brackets indicate optional items
[+|-] an optional plus or minus sign◦ item ... one or more instances of item
digit... a series of digits
VariablesVariablesVariables hold values that can changeSymbolic names for memory location
“average” in place of “@1123”
Declaration: type label [= value];
char initial = 'P';
Labels use alphanumeric characters and '_'
alpha [alpha | numeric | _]...
total pi standard_deviation Boeing747
Character dataCharacter dataSingle character
◦1 byte (8 bits, so 28 or 256 distinct values)◦Any of the ASCII characters from Appendix B
char grade = 'A'; // underlying value is code 65
Character strings◦Unlimited:1byte per character + 1 for end mark
string pet = "dog"; // values: 100, 111, 103, 0char* name = "O'Hara"; // old way ("C string")
Escape sequences for special characters\t \n \0 \\ // tab, newline, null and backslash
Numeric dataNumeric dataIntegers
◦int data type◦Usually 4 bytes (32 bits;, so > 4 billion values)◦int num_students = 40;
Floating◦double data type◦Usually 8 bytes (64 bits, so > 1.8x1019 values)◦The ‘float’ type just uses 4 bytes but
uncommon◦double average_temp = 94.5;
Logical dataLogical dataBoolean values (i.e., true or false)
◦bool data type◦Value false is 0, and value true is 1◦Usually 1 byte
For making programs more readablebool needs_payment = true;if (age < 18) needs_payment = false;if (age < 65) needs_payment = false;…if (needs_payment) cout << "Payment
required";
Basic arithmetic operatorsBasic arithmetic operatorsAddition and subtraction
expr1 + expr2 num_undergrads + num_grads
expr1 - expr2 num_students - num_failures
Multiplication and division expr1 * expr2 2 * pi * radius expr1 / expr2 width / 2
Modulus (aka remainder) expr1 % expr2 count % 2
C++ Gotcha'sC++ Gotcha'sInteger versus floating point division
F = 9/5 * C + 32 => 9.0/5.0 * C + 32
Treating numbers as strings and vice versaint course = "1428"; int course = 1428;
string bond = 007; string bond = "007";
Single versus double quotes◦Characters use ', but strings use "◦Use escapes for embedded quotes: '\"' "\'"
FYI: Scope of identifiers within blocksif (x > 10) { int y = 5; … cout << y; } // y visiblecout << y; // compiler error: y only occurs in if-block
FYI: Special case data typesFYI: Special case data typesUnsigned int’s (and also char’s)
◦The unsigned qualifier doubles the maximum:
[-231, 231-1] [0, 232-1]
The sign is omitted, so range change from
[-2147483648, 2147483647] to [0, 4294967295]
The long and short qualifiers◦For extra/reduced capacity integer (or floats)◦Platform-specific and uncommon these days
Not important for this class
Program CommentsProgram CommentsFormat: // arbitrary-text Describes intention of program segments
// Interchange values of x and yx = y;y = x;
Myth of self-documenting programsThe above segment is actually incorrect, which might not be apparent without the comment.
Comment in groups, not every statement
Making programs readableMaking programs readablePlace comments throughout
◦Top of program◦Before each function
Except main in simple programs (as top suffices)
Use descriptive variable names◦ex: Use 'temperature' rather than t
Use ample whitespace◦Blank line before comments◦Several before function definitions (e.g.,
main)
Simple OutputSimple Outputcout output stream
◦<< operator◦Format: cout [<< value]… ;
Examples◦cout << "Enter the patient's name: ";◦cout << "The temperature is " << temp;
Gotcha's◦The << must be repeated (commas not
allowed)◦endl required for end of line (or "\n")
cout << "The height is " << height << endl;
Preview: Simple InputPreview: Simple Inputcin input stream
◦<< operator◦Format: cin >> variable [>>
variable]... ;Example
cin >> patient_name;Gotcha's
◦Decimals ignored if integer type◦Whitespace terminates input for strings
Covered next week (chapter 3)
Chapter 2 SynopsisChapter 2 SynopsisImportant
◦Sections 1, 4, 6, 7, 8, 13Useful
◦Sections 2, 3, 5, 9, 11Marginal
◦Sections 10, 12, 16◦Tables 2-2 (keywords), 2-6 (misc.
integer types)◦Serendipity project (likewise in other
chapters)
C++ ResourcesC++ ResourcesOnline reference manuals
www.cplusplus.comwww.cppreference.com
PDF Reference Manualhttp://www.ibm.com/support/docview.wss?uid=swg27002103
Bjarne Stroustrup’s web page on C++http://www2.research.att.com/~bs/C++.html
Humorhttp://www.softpanorama.org/Lang/Cpp_rama/
humor.shtml
Example: "C++: Hard to learn and built to stay that way."