Writing and Reading C++ Programs A programming language has syntax and semantics like any
natural language Syntax is the set of rules like spelling and grammar in natural languages English: syntax spelled, sentences start with subject followed by verb
C++: main spelled, programs start with main() followed by { Semantics is the meaning
English: water means H2O C++: int means integer, + means add
Approaches of learning programming languages Template based
Examine example programs and make analogies Like a child learns how to speak
First learn syntax and semantics, then start by writing small programs, ... Like learning a foreign language
Which one do you prefer? We will follow the second method
First C++ Program Hello world program
#include using namespace std;
/* traditional first program */
int main(){cout
Format of a C++ Program
#include using namespace std;
/* traditional first program */
int main(){
cout
Format of a C++ Program
#include statements make libraries of classes and functions available to the program Utility functions and tools that make the programmers life easier are defined in libraries
Helps programmers develop code independently in a standard way and reuse common operations
Compiler needs access to interface (definition), what the functions look like, but not to the implementation of those functions This is in the #included file e.g. #include
for input/output functions all programs that use standard C++ libraries should have
using namespace std;
Format of a C++ Program Comments make programs readable by humans (and by assistants!)
Easier maintenance Try to use natural language, do not repeat the code!
Bad examplearea = pi * r * r; /* area is pi*r*r */
Better examplearea = pi * r * r; /* calculate area */
Best examplearea = pi * r * r; /* calculate area of a circle
of radius r */ Two ways of commenting
Using // make the rest of the line commentarea = pi * r * r; // calculate area
Between /* and *//*
Calculate area of a circle of radius r*/area = pi * r * r;
Compiler disregards comments In VC++, comments are in green
Format of a C++ Program
Execution of the program begins with main
Each program must have a main function
Execution of C++ programs is organized as a
sequence of statements
Statements execute sequentially one after another statement 0, statement 1, , statement (n-1)
Branching, repetition are possible (we will see them later)
The main function returns a value to the operating
system or the environment in which it is executed
return 0
Why 0? Because 0 means no problems (errors)
encountered!
Format of a C++ Program
Each statement ends with a ; (semicolon)
except #include and function headers like main()
Each statement has optional line break after the ;int main(){// This is valid code toocout
Rules of C++
Now some syntax rules and definitions
ABC of C++
What is a literal?
Reserved words (keywords)
What is an identifier?
Variables and basic types
Symbols and compound symbols
Where to use blanks, line breaks?
Basic Input/Output
Literals Fixed (constant) values
They cannot be changed during programs execution
They can be output by cout
Different format for different types: String literals
Sequences of characters
Within double quotes (quotes are not part of the string)
Almost any character is fine (letters, digits, symbols)
"Hello world!" " 10 > 22 $&*%? "
Numeric literals Integer
3 454 -43 +34
Real
3.1415 +45.44 -54.6 1.2334e3
1.2334e3 is 1.2334 times 10 to the power 3 (scientific notation)
Identifiers Names of programmer defined elements in a program
Names of variables, functions and parameters
Examples:number1 valid
number_1 valid
mySum valid
my_sum_1 valid
1number not valid
Syntax (rules):1.Sequence of letters (a .. z, A ..Z), digits (0 ..9) underscore _
2.Cannot start with a digit or underscore
3.Case sensitive (number1 and Number1 are not the same)
Pick meaningful names to improve readability and understandability of your program (be consistent)
Hungarian notation
Reserved Words (Keywords)
Special and fixed meanings
built-in in C++ language
no need to have libraries to use them
You cannot use a reserved word as a user-defined identifier
Cannot be changed by programmer
int
return
Full list is Table 2.1 of the textbook
Full list also in MSDN:
http://msdn.microsoft.com/en-us/library/aa245310(VS.60).aspx
In MS VC++, reserved words are automatically blue
Variables and Types
Variables are used to store data values that can
change during the program
Input (cin) data is stored in variables
Results are stored in variables
Named memory locations of certain sizes
Must be defined before they can be used
Often initialized before use
Syntax:
type name; identifier
type name1, name2, , namek;
Common types:
int number1, age, sum;
string myName, last_name;
float area, distance;
number1 age
Memory
area
distance
myName
sum
last_name
Symbols
Non-digit and non-letter characters with special meanings
Mostly used as operators (some examples below, full list later)Symbol Meaning Example
+ addition, sign 12 + 2, +67
- subtraction, minus 37 5, -8
* multiplication 3 * 5 * number
/ division 5.2 / 1.5
% modulus/remainder 7 % 2
= assignment sum = x + 5;
Symbol Meaning Example
/* comment start /* calculates
*/ comment end area */
stream input cin >> number;
== equality comparison number == 0
Compound symbols (two consecutive symbols one meaning),
examples below, full list later
Arithmetic Operations
Operators: + - * / %
Operands: values that operator combines
variables or literals
Combination of operators and operands is called expression
Syntax and semantics for arithmetic operations:
AdditionSubtraction
Multiplication Division Modulus
23 + 4 23 * 4 21 / 4 is 5 21 / 4 is 5
x + y x * 3.0 21 / 4.0 is5.25
18 % 2 is 0
d 14.0 + 23 d * 23.1 * 4 x / 4 x % 4
5 - 3 + 2 5 3 * 2 x / y x % y
See Figure 3.4 in the book.
Assignment Operator
Stores a new value in a variable
variable = expression;
The value of expression becomes
the value of variable
int number;
number = 40;
number = 40 + 5;
string name;
name = "Gulsen";
number * 4 = 56; wrong syntax
Previous value of variable is lost
Be careful about the types of left and right hand sides
they must match
compiler may or may not warn you int a = 32.6;
Memory
number
45
name
name
Gulsen
value
Example Program Write a program to calculate the area of a circle
program first input a name and print a greeting input the radius calculate and display area
identify literals, identifiers, keywords, symbols, variables and expressions
#include #include using namespace std;
// area calculation program
int main(){int radius;float area;string myname;cout > myname;cout
Issues with the Example Program
What happens if the user enters a real number for
radius?
wrong result
solution: real radius
Can we combine?cout
Where to use Blanks (Newline) You must have at least one blank
between two words (identifiers or keywords) e.g. int number;
between a word and numeric literal e.g. return 0;
You cannot have a blank within a word (e.g. float) within a compound symbol (e.g.
Stream Output
Output is necessary for our programs
Standard output stream cout is the monitor (read see-out)
cout is implemented in the iostream library
Output is sent to stream by the
Stream Input Input is also necessary for our programs
Standard input stream cin is the keyboard (read see-in)
cin is also implemented in the iostream library
You can input only to variables
Input is read from the stream by the >> operatorcin >> number;
More than one input could be read from the streamcin >> variable1 >> variable2 >> variable3 ;
Data will be read into the variables in the same order they are in the cin statement
int a, b, anynumber;
cin >> b >> anynumber >> a;
first the value for b, then the value for anynumber, then the value of a must be entered by the user using the keyboard
Stream Input You have to have at least one blank between any two inputentry
Multiple blanks are OK
You may input values at several lines for a single cin statement
You cannot display something using cin statement
Type match between variable and the corresponding input value
If mismatch then the input entry fails for the rest of the program
But the values read up to that point are kept in the variables
Stream Input Example showing the
operation
Data Types string
used it in previous lectures
more technically, string is a class
char for single character
digits, letters, symbols
uses up one byte
range 0 ... 255
why? one byte (8 bits) can store 28 = 256 different values.
stores the code of the character
e.g. 65 for A
character arithmetic is possible (will see later)
char literals are in single quotes (strings are in double quotes ")
'z' 'T' '4' '&'
bool
boolean (will see later)
Numeric Types
to represent integer and real numbers
int
integer numbers
no infinity in computers
limited range
2 or 4 bytes (16 or 32 bits) depending on the computer and
compiler you use
in our case: 4 bytes (32 bits)
integer range:
32,768 ... 32,767 for 16-bit computers
why?
2,147,483,648 ... 2,147,483,647 for 32-bit computers
why?
Numeric Types (contd)
short int (or just short ) always 16-bit integer
long int (or just long ) always 32-bit integer
signed versus unsigned integers you can put signed or unsigned keywords before the type
we discussed signed integers signed is default
unsigned integers use the same amount of bits but ranges are different 16-bit: 0 ... 65,535 (216 1) 32-bit: 0 ... 4,294,967,295 (232 1)
Numeric Types (contd)
Real numbers in C++
Real literals 3.14159 -2.5 5.43e21
Real data types (their difference is in precision) float
consumes 4 bytes
Range: 0 U [-1.175494351e38 ... -3.402823466e+38]
U [1.175494351e38 ... 3.402823466e+38]
Tapestry does not like float
double consumes 8 bytes
Range: 0 U [-2.2250738585072014e308 ... -1.7976931348623158e+308]
U [2.2250738585072014e308 ... 1.7976931348623158e+308]
Standard but a bit complex representation
see floating point representation item in MSDN Library index: http://msdn.microsoft.com/en-us/library/0b34tf65.aspx
More on C++ types
Check out these items in MSDN Library Index
Fundamental types
more on C++ types
LIMITS.H header file (Microsoft Visual Studio\VC98\Include)
limits of integer and char types
MSDN help on Integer Limits
floating limits (FLOAT.H)
limits for the floating points numbers (float, double)
MSDN help on Floating Limits
floating point representation
if you are interested in to learn how the real numbers are
represented in computers
MSDN help
Integer vs. Real
Real values can be assigned to Integer variables, but this is not recommended since we loose precision
int a;double r;r = 125.879;a = r;
What is the value of a? 125
Real value is truncated before storing in an integer variable
Avoid doing this
VS 2008 Compiler warns you but does not give error
Be careful when passing arguments to parameters as well passing an integer argument to a double parameter causes the same precision problem
Overflow
See daysecs.cpp
Overflow occurs when the result of an integer expression is outside the limits
Run the program with 365 days
result: 31536000 seconds correct result and output
14500 days result: 1252800000 seconds correct result and output
25129 days result: -2123821696 seconds incorrect result and output due to overflow
65400 days result: 1355592704 seconds incorrect result and output due to overflow
Arithmetic Operations
Operators: + - * / %
Operands: values that operator combines
variables or literals
Combination of operators and operands is called expression
Syntax and semantics for arithmetic operations:
AdditionSubtraction
Multiplication Division Modulus
23 + 4 23 * 4 21 / 4 is 5 21 / 4 is 5
x + y x * 3.0 21 / 4.0 is
5.25
18 % 2 is 0
d 14.0 + 23 d * 23.1 * 4 x / 4 x % 4
5 - 3 + 2 5 3 * 2 x / y x % y
Arithmetic Operations (contd)
Mixed type expressions
what if one operator is int other is double?
integer is converted into double before operation
5.0 * 8 is 40.0
5 / 10 is 0 (integer division)
5.0 / 10 is 0.5 (real division)
10 8 is 2 (integer)
10 8.0 is 2.0 (double)
Expressions with several operators
You can use parentheses in expressions to group them Open ( and close ) parentheses should match
Rule 1: Parenthesized sub-expressions are evaluated first inside to out
Rule 2: Within an expression/subexpression if there are several operators, use operator precedence, evaluate * / % before + -
Rule 3: If the operators are in the same expression/subexpression and at the same precedence level, then associativity rule applies evaluate operators from left-to-right
Examples(5 - 3 * (7 - 3)) * 8 is -56
10 / 2 * 6 / 2 + (5 - 3 * (2 - 1)) is 17
Expressions with several operators
Are the following expressions equivalent?(40 32) * 5 / 9
(40 32) * (5 / 9)
NO, first one is 4, second one is 0
What about this?(40 32.0) * 5 / 9
Operations are double operations. Result is 4.44444
Are these operators sufficient?
how to calculate square root?
Later well study functions like sqrt, cos, sin, pow,
For complicated mathematical operations that you cannot
easily do using basic operators
Accessible using #include (or )
Integer vs. Real (More on
Precision) What is the difference between red and blue parts in the
following program (fahrcels.cpp)?
red: integer arithmetic (low precision)
blue: real arithmetic (high precision)
int main(){
int ifahr;double dfahr;
cout > ifahr;cout
More on Assignment operator (4.1 & 4.3.4)
Assignment operator is =
to store values in variables
variable = expression;
first the right hand side expression is evaluated using the current values
then the evaluated expression is stored in variable
Types should be compatible, otherwise
a syntax error may occur (e.g. string variable, integer expression), or
precision is lost (e.g. integer variable, real expression)
Example: what is the value of a after the assignment?
int a, b;
b = 25; a = 8;
a = b 3 * a + 2;
Answer: 3
A rule: Right hand side expression is evaluated before the assignment operator is executed.
If you use the left hand side variable in the right hand side expression as well, then the current value is used in the expression.
See Program 4.1 in textbook.
More on Assignment operator (4.1 & 4.3.4)
Assigning single expression to several variablesvariable1 = variable2 = variable3 = ... variablen = expression;
all variables are assigned the same value of expression
example:int x, y, z;
x = y = z = 5;
x, y and z contain 5
Arithmetic assignment operators+= -= *= /= %=
Combines arithmetic operation and assignment in one operator
variable += expression is the same as variable = variable + expression
Example: x += 1 is the same as x = x + 1
Same for -= *= /= and %=
x -= 1 x *= 3 x /= 2 and x %= 2