Basic Elements of C++
by Neil A. Basabe
The Basics of a C++ Program
A C++ program is a collection of one or more subprograms, called
functions. Some functions called predefined or standard functions,
are already written and are provided as part of the system. But to
accomplish most tasks, programmers must learn to write their own
functions(user-defined functions).
Syntax rules – tell you which statements (instructions) are
legal, or accepted by the programming
language, and which are not
Semantic rules – determine the meaning of instructions
Programming language – a set of rules, symbols, and special
words
Basics of a C++ Program
Comments – used for documentation purposes
// - single line comment
/* */ - multiple-line comment
Example:
//This is a single line comment
/*This is a multiple-line
comment……..
*/
Note: the text after the // and between /* */ will be ignored by the
compiler.
Token – is the smallest individual unit of a program written in any
language.
3 Types:
1. Special symbols
* / % + -
. ; ? ,
<= != == >=
2. Reserved words or keywords
intchar float
double string const
void return
3. Identifiers – are names of things that appear in programs, such
as variables, constants, and functions.
Reserved Words
and and_eq asm auto bitand
bitor bool break case catch char class compl const
const_cast
continue default delete do double
dynamic_cast else enum explicit
export extern false float for
friend goto if include inline
int long mutablenamespace new
not not_eq operator or or_eq
private protected public register
reinterpret_cast return short signed
sizeof staticstatic_cast struct switch
template this throw true try
typedef typeid typename union unsigned
usingvirtual void volatile wchar_t
while xor xor_eq
Rules in naming identifiers.
1. An identifier should be made up of letters, numbers, and
underscore (_) only.
2. It must start with a letter or _ only.
3. It should have no spaces.
4. It must not be a reserved word or a keyword.
Example of valid identifiers:
5. lastName
6. number1
7. second_Number
8. netIncome
Examples of Invalid Identifiers:
one+two Invalid because of the +
sign
2ndnumber Invalid because it cannot
begin with a number
const Invalid because this is a
keyword
gross Salary Invalid because it
contains a space
Declaring variables
Variable – a memory location whose content may
change during program execution
Syntax for declaring variables:
dataType identifier, identifier, . . . ;
Example:
int number1;
string firstname, lastname, middlename;
char mid_initial;
float salary, hourly_rate;
Whitespaces
Every C++ program contains whitespaces. Whitespaces include blanks,
tabs, and newline characters.
Data type: A set of values together with a set of
operations.
3 Major Categories of Data Types:
1. Simple data type
a. Integral – deals with numbers without a decimal
part
(char, short, int, long, bool, unsigned char,
unsigned short, unsigned int, unsigned long)
b. Floating-point – deals with decimal numbers
(float, double, long double)
c. Enumeration – a user-defined data type
2. Structured data type
3. Pointers
Simple Data Types (cont’d.)
• Different compilers may allow different ranges of values
int Data Type
* Examples:
-8912
25
+1234
* Cannot use a comma within an integer
◦ Commas are only used for separating items
in a list
bool Data Type
bool type
Two values: true and false
Manipulate logical (Boolean) expressions
true and false
Logical values
bool, true, and false
Reserved words
char Data Type
The smallest integral data type
Used for single characters: letters, digits, and
special symbols
Each character is enclosed in single quotes
'A', 'a', '0', '*', '+', '$', '&'
A blank space is a character
Written ' ', with a space left between the
single quotes
char Data Type (cont’d.)
Different character data sets exist
ASCII: American Standard Code for
Information Interchange
• Each of 128 values in ASCII code set
represents a different character
• Characters have a predefined ordering
based on the ASCII numeric value
Collating sequence: ordering of characters
based on the character set code
Floating-Point Data Types
C++ uses scientific notation to represent real
numbers (floating-point notation)
Floating-Point Data Types (cont’d.)
• float: represents any real number
• Range: -3.4E+38 to 3.4E+38 (four bytes)
• double: represents any real number
• Range: -1.7E+308 to 1.7E+308 (eight
bytes)
• Minimum and maximum values of data types
are system dependent
• Maximum number of significant digits
(decimal places) for float values: 6 or 7
• Maximum number of significant digits for
double: 15
• Precision: maximum number of significant
digits
◦ Float values are called single precision
◦ Double values are called double precision
Data Types, Variables, and Assignment Statements
• To declare a variable, must specify its data
type
• Syntax: dataType identifier;
• Examples:
int counter;
double interestRate;
char grade;
• Assignment statement: variable = expression
interestRate = 0.05;
Arithmetic Operators
% -> modulus operator ( to get the remainder)
-> can be used for whole numbers only
* -> multiplication operator
/ -> division operator
+ -> addition operator
- -> subtraction operator
Precedence Rules:
1. Multiplicative operators (%, *, /) should be evaluated first.
2. Additive operators (+,-) should be evaluated
after multiplicative operators.
3. Evaluate from left to right.
4. A pair of parentheses will override the usual
priority.
Example: Evaluate the following
arithmetic expression:
1. 5–3+7/3%4*2
=5–3+2%4*2
=5–3+2*2
=5–3+4
=2+4
=6
2. 5 – (3 + 7) / ((3 % 4) * 2) 3. 10. 5 % 3
= 5 – (3 + 7) / (3 * 2) = error
= 5 – 10 / (3 * 2)
= 5 – 10 /6
=5–1
=4
Mixed Expressions
Mixed expression:
Has operands of different data types
Contains integers and floating-point
Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
Mixed Expressions (cont’d.)
Evaluation rules:
If operator has same types of operands
Evaluated according to the type of the
operands
If operator has both types of operands
Integer is changed to floating-point
Operator is evaluated
Result is floating-point
Entire expression is evaluated according to
precedence rules
Type Conversion (Casting)
• Implicit type coercion: when value of one type
is automatically changed to another type
• Cast operator: provides explicit type
conversion
• static_cast<dataTypeName>(expression
)
Type Conversion (Casting) (cont’d.)
string Type
Programmer-defined type supplied in
ANSI/ISO Standard C++ library
Sequence of zero or more characters enclosed
in double quotation marks
Null (or empty): a string with no characters
Each character has a relative position in the
string
Position of first character is 0
Length of a string is number of characters in it
Example: length of "William Jacob" is 13
Allocating Memory with Constants and Variables
Named constant: memory location whose
content can’t change during execution
Syntax to declare a named constant:
const dataType identifier = value;
In C++, const is a reserved word
Assignment Statement
The assignment statement takes the form:
variable = expression;
Expression is evaluated and its value is assigned to the variable on the left
side.
A variable is said to be initialized the first time a value is placed into it
In C++, = is called the assignment operator.
Input (Read) Statement
cin is used with >> to gather input
This is called an input (read) statement
The stream extraction operator is >>
For example, if miles is a double variable
cin >> miles;
Causes computer to get a value of type double and places it in the
variable miles
Using more than one variable in cin allows more than one value to be
read at a time
Example: if feet and inches are variables of type int, this
statement:
cin >> feet >> inches;
Inputs two integers from the keyboard
Places them in variables feet and inches respectively
Output Statement
The syntax of cout and << is:
◦ Called an output statement
The stream insertion operator is <<
Expression evaluated and its value is printed at the current cursor
position on the screen
A manipulator is used to format the output
◦ Example: endl causes insertion point to move to beginning of next
line
Output (cont’d.)
Increment and Decrement Operators
Increment operator: increase variable by 1
Pre-increment: ++variable
Post-increment: variable++
Decrement operator: decrease variable by 1
Pre-decrement: --variable
Post-decrement: variable—
What is the difference between the following?
x = 5; x = 5;
y = ++x; y = x++;
Preprocessor Directives
C++ has a small number of operations
Many functions and symbols needed to run a
C++ program are provided as collection of
libraries
Every library has a name and is referred to by
a header file
Preprocessor directives are commands
supplied to the preprocessor program
All preprocessor commands begin with #
No semicolon at the end of these commands
Preprocessor Directives (cont’d.)
• Syntax to include a header file:
• For example:
#include <iostream>
– Causes the preprocessor to include the header file iostream in the
program
• Preprocessor commands are processed before the program goes through
the compiler
cin and cout are declared in the header file iostream, but within std
namespace
To use cin and cout in a program, use the following two statements:
#include <iostream>
using namespace std;
Using the string Data Type in a Program
To use the string type, you need to access
its definition from the header file string
Include the following preprocessor directive:
#include <string>
Creating a C++ Program
A C++ program is a collection of functions, one of
which is the function main
The first line of the function main is called the
heading of the function:
int main()
The statements enclosed between the curly braces
({ and }) form the body of the function
A C++ program contains two types of statements:
Declaration statements: declare things, such as
variables
Executable statements: perform calculations,
manipulate data, create output, accept input, etc.
Creating a C++ Program (cont’d.)
C++ program has two parts:
Preprocessor directives
The program
Preprocessor directives and program
statements constitute C++ source code (.cpp)
Compiler generates object code (.obj)
Executable code is produced and saved in a
file with the file extension .exe
Debugging: Understanding and Fixing Syntax Errors
Compile a program
◦ Compiler will identify the syntax errors
◦ Specifies the line numbers where the errors occur
Example2_Syntax_Errors.cpp
c:\chapter 2 source
code\example2_syntax_errors.cpp(9) : error
C2146: syntax error :
missing ';' before identifier 'num'
c:\chapter 2 source
code\example2_syntax_errors.cpp(11) :
error C2065: 'tempNum' :
undeclared identifier
Program Style and Form: Syntax
Syntax rules: indicate what is legal and what
is not legal
Errors in syntax are found in compilation
int x; //Line 1
int y //Line 2: error
double z; //Line 3
y = w + x; //Line 4: error
Use of Blanks
In C++, you use one or more blanks to
separate numbers when data is input
Blanks are also used to separate reserved
words and identifiers from each other and
from other symbols
Blanks must never appear within a reserved
word or identifier
Use of Semicolons, Brackets, and Commas
All C++ statements end with a semicolon
Also called a statement terminator
{ and } are not C++ statements
Can be regarded as delimiters
Commas separate items in a list
Semantics
Semantics: set of rules that gives meaning to
a language
Possible to remove all syntax errors in a
program and still not have it run
Even if it runs, it may still not do what you
meant it to do
Ex: 2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions,
but have different meanings
Naming Identifiers
Identifiers can be self-documenting:
CENTIMETERS_PER_INCH
Avoid run-together words :
annualsale
Solution:
Capitalizing the beginning of each new
word: annualSale
Inserting an underscore just before a new
word: annual_sale
Prompt Lines
Prompt lines: executable statements that inform
the user what to do
cout << "Please enter a number between
1 and 10 and "
<< "press the return key" << endl;
cin >> num;
Always include prompt lines when input is needed
from users
Documentation
A well-documented program is easier to
understand and modify
You use comments to document programs
Comments should appear in a program to:
◦ Explain the purpose of the program
◦ Identify who wrote it
◦ Explain the purpose of particular statements
More on Assignment Statements
• Two forms of assignment
– Simple and compound
– Compound operators provide more concise
notation
• Compound operators: +=, -=, *=, /=, %=
• Simple assignment
x = x * y;
• Compound assignment
x *= y;
cin and the Extraction Operator >>
used for input
Example:
cout << “Enter pay rate and hours worked: ”;
cin >> payRate >> hoursWorked;
Enter pay rate and hours worked: 15.50 48.30
cout and the Insertion Operator <<
Used for output
Example:
double hours = 35.45;
double rate = 15.00;
cout << “hours = “ << hours << “, rate = “ << rate
<< “, pay = “ << hours * rate << endl;
Output:
hours = 35.45, rate = 15, pay = 531.75
Use of \n and endl
To insert a new line
Example:
cout << “Hello!\nThis is my \nfirst program!”;
Output:
Hello!
This is my
first program!
Example:
cout << “Hello!” << endl << “This is my” << “\n”
<< “first” << ‘\n’ << “program!”;
Output:
Hello!
This is my
first
program!
The string data type and using
getline()
String – a collection of characters
Example:
string name;
cout << “Enter name: ”;
getline(cin,name);
Output:
Enter name: Neil A. Basabe