Upload
karin-ellis
View
216
Download
1
Embed Size (px)
Citation preview
Chapter 2
Overview of C++
A Sample Program// This is my first program. It calculates and outputs
// how many fingers I have.
#include <iostream>
using namespace std;
int main ()
{
int digits;
digits = 5*2;
cout << "I have " << digits << " fingers" << endl;
return 0;
}
C++ Language Elements
Comments Compiler directives Function main Declaration statements Executable statements
Comments Used to explain code to author and other
readers /* */ (multi-line, "C style") // (until end of line, "C++ style") Write good meaningful comments! There is a bad example on class page under:
Other Useful Links Don't repeat code in a comment, explain it!
#include <filename>
this is a compiler directive (starts with #) Includes previously written code from a
library into your program E.g.
#include <iostream>
has operators for performing input and output within the program
Libraries allow for code reuse
using namespace std;
Indicates to compiler that this program uses objects defined by a standard namespace called std
The statement ends with a semicolon Follows #include directives in the code Must appear in all programs
The main function
Every C/C++ program must have a function named main and only ONE called main
The start of the main function is the marker for the start of the program execution
int main ( )
{
// function body
return 0;
}
What is in a function heading (header)?
int main( )
type of returned valuename of function
() says no parameters
8
The main function
header is int main () // NOT "void main" empty () in header means no parameters,
indicates no special information passed to the function by the operating system
braces {} around body must balance semicolons mark ends of statements return 0; at the end of the function "satisfies"
the int return value in the header
Code and Data
Almost every statement in the program is concerned with manipulating data inputting it outputting it calculating with it making decisions based on its values storing it temporarily or permanently
Data Properties has a name - either itself or an identifier has a type - integer, character, float, string,
etc. has space in RAM and an address = memory
allocated to hold its value has a value - 7.2, -3, 'd', true, "John" can be referred to as a variable (avg or sum)
OR a named constant (PI or MAX) OR a literal constant (4 or "abc")
Reserved Words (Keywords)
Have special meaning in C++ Cannot be used for other purposes Ones we have seen
main include using return int
Identifiers - the names of data and functions syntax rules for making an identifier
must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits(0-9), or underscores
case sensitive!! Upper vs. lower case cannot be a reserved word they are used for names of
variables, named constants, or functions
Identifiers
VALID
age_of_dog taxRateY2K
PrintHeading ageOfHorse
NOT VALID (Why?)
age# 2000TaxRate Age-Of-Cat int
Data types
The type determines which values can be used and the operations you can perform
Types protect you from making logical mistakes - mixing types in ways that don't make sense - adding a string to a float
"strongly typed" languages versus "weakly typed" languages C++ versus Visual Basic
Data Types
int, float, double - all numeric fractional part (float) versus no fractional part (int) exponential notation for floats / doubles overflow, underflow
char - holds ONE character string - zero or more characters in an object bool - logical values (George Boole) - true,
false
Data Types (con’t)
Floating point (real) number has two parts, integral and fractional e.g. 2.5, 3.66666666, -.000034, 5.0, 5.4E10 float, double, long double stored internally in binary as mantissa and
exponent Exponential or scientific notation for very large
and small numbers (upper or lower case e) 10.0 and 10 are stored differently in memory
Data Types (con’t)
Boolean named for George Boole represent conditional values values: true and false used for storing results of comparisons for later
use "flags" not used for input or output
Data Types (con’t)
Characters represent individual character values
E.g. ’A’ ’a’ ’2’ ’*’ ’”’ ’ ’ stored in 1 byte of memory special characters: escape sequences
E.g. ’\n’ ’\a’ ’\r’ ’\t’ ‘\\’
string Class
Strings not built-in, but come from library A string literal is enclosed in double quotes
E.g.: “Enter speed: “ “ABC” “B” “true”
“1234” #include <string>
for using string variables, but not needed for literals
Declarations of data All variable and function identifiers must be
declared before use and can only be declared ONE time (in one scope)
Constants literal constants ('a', 4, 5.2, true, false, "John")
Don't need declarations, their names are their values named constants (PI, MAX) usually all caps
Must be declared and given a value at one time
What Does a Variable Declaration Do?
A declaration tells the compiler to allocate enoughmemory to hold a value of this data type and to associate the identifier with this location - its value can be changed many times during the program run
int ageOfDog;float taxRate;char middleInitial;
4 bytes for taxRate 1 byte for middleInitial
What does a variable declaration NOT do? Note that the previous slide did not mention
the _starting or initial value_ of the variables A plain declaration of a variable does not give
the variable a starting value - do NOT assume it is zero or blank or any known value
You do not know the value of a variable until YOU give it one
to declare and initialize at one time "int x = 5;" "declaration with initialization"
What is a Named Constant?A named constant is a location in memory that can
be referred to by an identifier and in which a data value that cannot be changed is stored
Valid constant declarations
const string STARS = “****”;
const float NORMAL_TEMP = 98.6;
const char BLANK = ‘ ’;
const int VOTING_AGE = 18;
const float MAX_HOURS = 40.0;
Why use them? good documentation, easy to edit later, prevents typing errors
Identifiers usually upper case, by custom
Program Style
Use of spacing and blank lines one statement per line blanks after comma, around operators in between some lines of code for readability
Use of comments header comments at the top of the file - name,
date, email, section, PURPOSE document algorithm steps describe difficult code
A block is a sequence of zero or more statements enclosed by a pair of curly braces { }
SYNTAX
{Statement, statement, . . .
} Braces should line up and statements inside
should be indented Blocks are used for the body of a function, as well
as grouping statements together
Block(Compound Statement)
Executable statements (to start with) Output statements Input statements Assignment statements Return statement
Input Statements
Obtain data for program to use - different each time the program executes
cin - name of standard input stream associated with standard input device (keyboard)
Extraction operator (>>) E.g.:
cin >> miles;
cin >> age >> firstInitial;
Output statements cout "console output"
cout is the name of the standard output stream output sent to cout always goes to the screen
(standard output device) insertion operator <<
several can be chained in one statement outputting literals outputting variables and named constants endl - a manipulator (ends with "l" - lower case
ell, not the digit 1)
Output StatementsSYNTAX
These examples yield the same output:
cout << “The answer is “;
cout << 3 * 4;
cout << “The answer is “ << 3 * 4;
cout << Expression << Expression . . .;
Return statement
"return 0;" always at the end of the sequence of statements in the main function
semantics: execution control turned back over to Operating System (Windows or Unix)
means the program is over! return value 0 means "normal exit"
Assignment statement Syntax "var = expression;" Semantics - left side location gets the value
of the expression on the right hand side Expressions can use operators of appropriate
types (arithmetic or string) The expression must evaluate to ONE value This one value has a type
either matches type of left hand side or doesn't type coercion or type casting happens if doesn't
Examples:
int x, y, z;
x = 5; // expression 5
y = x * 2; // expression x * 2 or 10
z = x + y - 18; // expression x + y - 18 or -3
x = x + 2; // expression x + 2 or 7
Working with the IDE
Build versus Rebuild versus Clean “build is up-to-date” warning - Watch out!! Errors and warnings
Warning level W2 is what will be used to grade your programs - instructions on how to set this are on the program assignment page
Syntax Errors
The compiler may report lots of syntax errors NO executable generated if there are any! Fix the FIRST one then recompile Try to understand what the error was Error messages are not clear
keep a log of messages and what they mean Do not ignore warning messages!
Logic (Semantic) Errors
Caused by a faulty algorithm They are only found by testing - compiler
does not detect them! Testing
choose an input value calculate by hand the expected output run the program and check the actual output Test several different input values
Runtime Errors
Caused by something the program cannot control in its environment
example: division by zero example: file not found usually crashes the program more advanced - read about 'exceptions'