Introduction to Programming
in C++
Section 1 - The Basics
So#ware Development Cycle
Source Program IDE
Compile
Library routines
Edit Link
Other object files
Think Load
Execute
IDEs
• Integrated Development Environments or IDEs
– Supports the en;re so#ware development cycle
• E.g. MS Visual C++, Borland, Code Warrior
• Provides all the capabili;es for developing so#ware
– Editor
– Compiler
– Linker
– Loader
– Debugger
– Viewer
What are the Key Ingredients of a Program?
• Common elements in programming languages:
– Keywords (aka reserved words)
• Defined in C++. Have a special meaning
– Programmer-defined en;;es
• Names made up by programmer
• Used to represent variables, func;ons, etc.
– Operators
• Defined in C++
• For performing arithme;c, comparison, etc. opera;ons
– Constructs
• Defined in C++
• Sequence, selec;on, repe;;on, func;ons, classes, etc.
Every programming language has a syntax (or grammar) that a
programmer must observe
The syntax controls the use of the elements of the program
The Evolu;on of C++
• C (1972)
• ANSI Standard C (1989)
• Bjarne Stroustrup adds features of the language Simula (an
object-oriented language designed for carrying out simula;ons) to
C resul;ng in …
• C++ (1983)
• ANSI Standard C++ (1998)
• ANSI Standard C++ [revised] (2003)
• ANSI Standard C++ (2011)
• The present C++
– A general-purpose language that is in widespread use for
systems and embedded
– The most commonly used language for developing system
so#ware such as databases and opera;ng systems
… the future: another Standard (2014 and 2017?)
C++ - an Object-Oriented Programming Language
Other examples: C# and Java
The modern approach to developing programs
- Objects in a real-world problem are modeled as software objects
Warning: OO features were added to C++ as an “afterthought”
- It is not a “true” OO language such as C# or Java
Program Organiza;on
• Program statement
– Defini;on, e.g. func;on prototype
– Declara;on, e.g. variables and constants
– Ac;on
• Executable unit - Ac;on
– Set of program statements – may be named
– Different languages refer to named executable units by
different names
• Subrou;ne: Fortran and Basic
• Procedure: Pascal
• Func;on: C++
• Method: C++, C#, Java
The simplest C++ program consists of a single func;on named main.
The syntax of such programs is shown below:
#include <iostream>
using namespace std;
int main()
{
declara;on(s)
statement(s)
return 0;
}
The por;ons of the program shown in blue should always be present.
The declara;ons specify the data that is used by the program. These
declara;ons can declare either constants or variables, for example.
The statements specify the algorithm for the solu;on to your problem.
Example – Algorithm for Conver;ng Miles to Kilometers
• Problem Input
miles distance in miles
• Problem Output
kms distance in kilometers
• Algorithm will use Conversion Formula
1 mile = 1.609 kilometers
• Formulate the algorithm that solves the problem.
• Algorithm
1. Get the distance in miles.
2. Convert the distance to kilometers by mul;plying by 1.609
3. Display the distance in kilometers.
• Now convert the algorithm to program code!
Statements
Statements are the executable “units” of a program.
Statements are the transla;on of an algorithm into program code.
Statements may be
- Simple – typically one line of program code
- Structured – a grouping of a number of statements
E.g. control structures; func;ons; etc.
Statements must be terminated with a ; symbol.
Program statements may be executed by one of three control
structures:
- Sequence – execute statements one a#er the other
- Selec;on – select which statement(s) to execute
- Repe;;on – repeatedly execute statement(s)
#include <iostream>
using namespace std;
int main()
{
declara;on(s)
statement(s)
return 0;
}
#include <iostream>
using namespace std;
The #include Direc;ve
int main()
• Preprocessor direc;ve {
declara;on(s)
statement(s)
• Inserts the contents of another file into the program return 0;
}
iostream is C++ library of input/output func;ons
This includes cout and cin
• Do not use ; at end of #include statement
The namespace Direc;ve
This direc;ve allows the cout and cin statements to be used in a
program without using the prefix std::
#include <iostream>
With this direc;ve, may write using namespace std;
cin or cout int main()
{
declara;on(s)
Otherwise, we would have to write statement(s)
return 0;
std::cout or std::cin }
Must use ; at end of namespace directive
Declara;ons - Constants and Variables
Constants are data that having unchanging values.
Variables, as their name implies, are data whose values can change
during the course of execu;on of your program.
For both constants and variables, the name, the data type, and value
must be specified.
Any variable in your program must be defined before it can be used
Data type specifies whether data is integral, real, character or logical.
Constants
Syntax
const type name = expression;
The statement must include the reserved word const, which designates
the declara;on as a constant declara;on.
The type specifica;on is op;onal and will be assumed to be integer.
Examples
const float TAXRATE = 0.0675;
const int NUMSTATES = 50;
Conven;on is to use uppercase leyers for names of constants.
The data type of a constant may be one the types given below
A Simple, Yet Complete, C++ Program
Program producing output only
// Hello world program Comment
#include <iostream> Preprocessor
using namespace std; directives
int main() Function
{ named
cout << "Hello world!" << endl; main()
indicates
return 0;
start of the
} program
Ends execution
of main() which ends the
program
Let us look at the func;on main()
int main()
{
cout << "Hello world!" << endl;
return 0;
}
This example introduces the notion of a text string
"Hello world!"
The basic data types supported by C++ are shown in the table
below
The three integer types allow for whole numbers of three different
sizes.
The two real types permit numbers with decimal parts with two
different amounts of precision.
Finally, there is one type for character data that consists of a single
character, and one type for logical values that are either true or false.
The cout Output Statement
• Used to display informa;on on computer screen
• It is declared in the header file iostream
• Syntax
cout << expression;
• Uses << operator to send informa;on to computer screen
cout << "Hello, there!";
• Can be used to send more than one item
cout << "Hello, " << "there!";
• To get mul;ple lines of output on screen
Either
- Use the endl func;on
cout << "Hello, there!" << endl;
Or
- Use \n in the output string
cout << "Hello, there!\n";
Example
#include <iostream>
using namespace std;
int main()
{
cout << " * " << endl;
cout << " *** " << endl;
cout << " ***** " << endl;
cout << " * " << endl;
cout << " * " << endl;
cout << " * " << endl;
}
#include <iostream> Example
using namespace std;
int main() {
double radius;
double area;
// Step 1: Set value for radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
cout << "The area is ";
cout << area << endl;
}
The cin Statement
• Used to read input from keyboard
• It is declared in the header file iostream
• Syntax
cin >> variable
• Uses >> operator to receive data from the keyboard and
assign the value to a variable
• O#en used with cout to display a user prompt first
• May use cin to store data in one or more variables
• Can be used to input more than one value
cin >> height >> width;
• Mul;ple values from keyboard must be separated by spaces
• Order is important: first value entered goes to first variable, etc.
Example Program – Use of cout to prompt user to enter some data
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "What is your name? ";
cin >> name;
cout << "Hello there, " << name;
return 0;
}
Names
• Used to denote language- and programmer-defined elements
within the program
• A valid name is a sequence of
– Leyers (upper and lowercase)
– Digits
• A name cannot start with a digit
– Underscores
• A name should not normally start with an underscore
• Names are case sensi;ve
– MyObject is a different name than MYOBJECT
• There are two kinds of names
– Keywords
– Iden;fiers
Keywords
• Keywords are words reserved as part of the language - syntax
Example int, return, float, double
• They cannot be used to name programmer-defined elements
• They consist of lowercase leyers only
• They have special meaning to the compiler
Iden;fiers
• Iden;fiers are the names given to programmer-defined en;;es
within the program – variables, func;ons, etc.
• Iden;fiers should be
– Short enough to be reasonable to type (single word is the norm)
• Standard abbrevia;ons are fine
– Long enough to be understandable
• When using mul;ple word iden;fiers capitalize the first leyer
of each word – but this is just a conven;on
• Examples
– Min
– Temperature
– CameraAngle
– CurrentNbrPoints
Example - Valid and Invalid Iden;fiers
IDENTIFIER VALID? REASON IF INVALID
totalSales Yes
total_Sales Yes
total.Sales No Cannot contain .
4thQtrSales No Cannot begin with digit
totalSale$ No Cannot contain $
Integer Data Types
• Designed to hold whole numbers
• Can be signed or unsigned
– 12 -6 +3
• Available in different sizes (in memory): short, int, and long
• Size of short ≤ size of int ≤ size of long
Floa;ng-Point Data Types
• Designed to hold real numbers
12.45 -3.8
• Stored in a form similar to scien;fic nota;on
• All numbers are signed
• Available in different sizes (space in memory: float, double, and long
double
• Size of float ≤ size of double ≤ size of long double
Numeric Types in C++
Defining Variables
• Variables of the same type can be defined
- On separate lines:
int length;
int width;
unsigned int area;
- On the same line:
int length, width;
unsigned int area;
• Variables of different types must be in different defini;ons
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
Variable Assignments and Ini;aliza;on
Assignment
• Uses the = operator
• Has a single variable on the le# side and a value (constant, variable,
or expression) on the right side
• Copies (i.e. assigns) the value on the right to the variable on the le#.
(An expression is first evaluated)
• Syntax
variable = expression ;
item = 12; // constant
Celsius = (Fahrenheit - 32) * 5 / 9; // expression
y = m * x + b; // expression
Assignment Statement
int NewStudents = 6; NewStudents 6
int OldStudents = 21; OldStudents 21
int TotalStudents; TotalStudents ?
TotalStudents = NewStudents + OldStudents;
Variable Assignments and Ini;aliza;on
Ini;aliza;on
• Ini;alize a variable: assign it a value when it is defined:
int length = 12;
• Or ini;alize it later via assignment
• Can ini;alize some or all variables:
int length = 12, width = 5, area;
• A variable cannot be used before it is defined
Arithmetic Operators
• Used for performing numeric calculations
Basic Arithme;c Operators
SYMBOL OPERATION EXAMPLE VALUE OF ans
+ addi;on ans = 7 + 3; 10
- subtrac;on ans = 7 - 3; 4
* mul;plica;on ans = 7 * 3; 21
/ division ans = 7 / 3; 2
% modulus ans = 7 % 3; 1
/ Operator
• / (division) operator performs integer division if both operands are
integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
• If either operand is floa;ng point, the result is floa;ng point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
% Operator
• % (modulus) operator computes the remainder resul;ng from
integer division
cout << 13 % 5; // displays 3
• % requires integers for both operands
cout << 13 % 5.0; // error
Remainder Operator
Remainder is very useful in programming.
For example, an even number % 2 is always 0 and an odd number % 2 is
always 1.
So you can use this property to determine whether a number is even or
odd.
Suppose today is Saturday and you and your friends are going to meet in
10 days. What day is in 10 days? You can find that day is Tuesday using
the following expression:
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
Expressions
• Can create complex expressions using mul;ple mathema;cal
(and other) operators
• An expression can be a constant, a variable, or a combina;on of
constants and variables
• Can be used in assignment, with cout, and with other
statements:
area = 2 * PI * radius;
cout << "border length of rectangle is: " << 2*(l+w);
Expressions
Expressions are a grouping of variables, constants and operators.
C++ has a defined order of precedence for the order in which
operators are used in an expression
- It is not just a le#-to-right evalua;on
Brackets (aka parentheses) can be used to change the defined order
in which operators are used.
Example
#include <iostream>
using namespace std;
int main()
{
cout << (1 + 2 + 3) / 3 << endl; // not the same as 1+2+3/3
return 0;
}
Expressions
• Mul;plica;on requires an operator:
Area=lw is wriyen as Area = l * w;
• There is no exponen;a;on operator:
Area=s2 is wriyen as Area = pow(s, 2);
• Parentheses may be needed to specify the order of opera;ons
Example
y 2 − y
1 is wriyen as m = (y2-y1) /(x2-x1);
m=
x 2 − x1
Note the use of brackets to group variables into expressions and
inform the compiler the order of evalua;on.
Example
m = (y2-y1) /(x2-x1);
Compound Assignment
• C++ has a set of operators for applying an opera;on to an
object and then storing the result back into the object
• Examples
int i = 3;
i += 4; // i is now 7 Equivalent to i = i + 4
float a = 3.2;
a *= 2.0; // a is now 6.4 Equivalent to a = a * 2.0
Shorthand Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
Assignment Conversions
• Floa;ng-point expression assigned to an integer object is
truncated
• Integer expression assigned to a floa;ng-point object is
converted to a floa;ng-point value
• Consider
float y = 2.7;
int i = 15;
int j = 10;
i = y; // i is now 2
y = j; // y is now 10.0
Operators and Precedence
Consider m*x + b - Which of the following is it equivalent to?
n (m * x) + b - Equivalent
n m * (x + b) - Not equivalent but valid!
Operator precedence tells how to evaluate expressions
Standard precedence order
n () Evaluate first. If nested innermost
done first
n * / % Evaluate second. If there are several,
then evaluate from le#-to-right
n + - Evaluate third. If there are several,
then evaluate from le#-to-right
Operator Precedence
• Example
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
Increment and Decrement Operators
• C++ has special operators for incremen;ng or decremen;ng a
variable’s value by one – “strange”effects!
• Examples
int k = 4;
++k; // k is 5
k++; // k is 6 Nothing strange so far!
BUT
int i = k++; // i is 6, and k is 7
int j = ++k; // j is 8, and k is 8
Increment and Decrement Operators
The “strange”effects appear when the operators are used in an
assignment statement
Operator Name Descrip;on
a=++var pre-increment The value in var is incremented by 1 and
this new value of var is assigned to a.
a=var++ post-increment The value in var is assigned to a and then
the value in var is incremented by 1
Similar effects for the decrement operator
Operator Name Descrip;on
a=--var pre-decrement The value in var is
decremented by 1 and
this new value of var is
assigned to a.
a=var-- post-decrement The value in var is
assigned to a and then
the value in var is
decremented by 1
Some Standard Libraries
fstream
- File stream processing
assert
- Asser;on processing
iomanip
- Formayed input/output (I/O) requests
ctype
- Character manipula;ons
cmath
Trigonometric and logarithmic func;ons
Note
C++ has many other libraries
C++ cmath Library
• Typical mathema;cal func;ons
e.g. sqrt, sin, cos, log
• Func;on use in an assignment statement
Func;on call
y = sqrt(x);
Func;on Func;on
name argument
Some Mathema;cal Library Func;ons
Example
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "Enter Quadra;c coefficients: ";
double a, b, c;
cin >> a >> b >> c;
if ( (a != 0) && (b*b - 4*a*c > 0) ) {
double radical = sqrt(b*b - 4*a*c);
double root1 = (-b + radical) / (2*a);
double root2 = (-b - radical) / (2*a);
cout << "Roots: " << root1 << " " << root2;
}
else {
cout << "Does not have two real roots";
}
return 0;
}
/*
This program computes the volume (in liters) of a six-pack of
soda cans and the total volume of a six-pack and a two-
liter bottle.
*/
int main()
{
int cans_per_pack = 6;
const double CAN_VOLUME = 0.355; // Liters in a can
double total_volume = cans_per_pack * CAN_VOLUME;
cout << "A six-pack of 12 cans contains "
<< total_volume << " liters." << endl;
const double BOTTLE_VOLUME = 2; // Two-liter bottle
total_volume = total_volume + BOTTLE_VOLUME;
cout << "A six-pack and a two-liter bottle contain "
<< total_volume << " liters." << endl;
return 0;
}
Common Error – Omi-ng Semicolons
Common error
Omi-ng a semicolon (or two) Oh No!
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 cout << "Hello, World!" << endl
8 return 0;
9 }
Suppose you (accidentally of course) wrote:
cot << "Hello World!" << endl;
• This will cause a compile-time error and the compiler will
complain that it has no clue what you mean by cot.
The exact wording of the error message is dependent on
the compiler, but it might be something like
“Undefined symbol cot”.
Consider this:
cout << "Hollo, World!" << endl;
• Logic errors or run--me errors are errors in a program that
compiles (the syntax is correct), but executes without
performing the intended acCon.
not really an error?
Common Error – Using Undefined Variables
You must define a variable before you use it for the first Cme.
For example, the following sequence of statements would not
be legal:
double can_volume = 12 * liter_factor;
double liter_factor = 0.0296;
? ?
Statements are compiled in top to boJom order.
When the compiler reaches the first statement, it does not
know that liter_factor will be defined in the next line,
and it reports an error.
Common Error – Using Unini;alized Variables
IniCalizing a variable is not required, but there is always a
value in every variable, even uniniCalized ones.
Some value will be there, the flotsam leP over from some
previous calculaCon or simply the random value there
when the transistors in RAM were first turned on.
int bottles; // Forgot to initialize
int bottle_volume = bottles * 2; // Result is unpredictable
What value would be output from the following statement?
cout << bottle_volume << endl; // Unpredictable
Common Error – Unbalanced Parentheses
Consider the expression
(-(b * b - 4 * a * c) / (2 * a)
What is wrong with it?
?
The parentheses are unbalanced.
This is very common with complicated expressions.
Common Error – Roundoff Errors
This program produces the wrong output:
#include <iostream>
using namespace std;
int main()
{
double price = 4.35;
int cents = 100 * price;
// Should be 100 * 4.35 = 435
cout << cents << endl;
// Prints 434!
return 0;
}
Why?
Common Error – Roundoff Errors
• In the computer, numbers are represented in the binary
number system, not in decimal.
• In the binary system, there is no exact representaCon for
4.35, just as there is no exact representaCon for ⅓ in the
decimal system.
• The representaCon used by the computer is just a liJle less
than 4.35, so 100 Cmes that value is just a liJle less than 435.
• The remedy is to add 0.5 in order to round to the nearest
integer:
int cents = 100 * price + 0.5;