Elements of C++-1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 82

CHAPTER 2:

C++ PROGRAMMING

BASIC ELEMENTS OF C++


A QUICK LOOK AT A C++ PROGRAM

Example 2 – 1:
From Example 1 – 1, we design an
algorithm to find the perimeter and
area of a rectangle. Given the
length and the width of a rectangle,
the C++ program in this example
computes and displays the perimeter
and area.
INTRODUCTION

• A computer program, or a
program, is a sequence of
statements whose objective is to
accomplish a task.
• Programming is a process of
planning and creating a program.
A QUICK LOOK AT A C++ PROGRAM
A QUICK LOOK AT A C++ PROGRAM

Sample Run
A QUICK LOOK AT A C++ PROGRAM

The lines are displayed by the


execution of the following statements:
A QUICK LOOK AT A C++ PROGRAM

A C++ program can contain various


types of expressions such as arithmetic
and strings.
Example:
length + width is an arithmetic expression
"Program to compute and output the
perimeter and " and "area of a rectangle."
is a string (anything in double quotes)
A QUICK LOOK AT A C++ PROGRAM

Typically, a string evaluates to itself.


Arithmetic expression are evaluated
according to rules of arithmetic
operations.
Also note that in an output statement,
endl causes the insertion point to
move to the beginning of the next line.
A QUICK LOOK AT A C++ PROGRAM

This is an example of C++ output


statement.
It causes the computer to evaluate the
expression after the pair of symbols
<< and display the result on the
screen.
A QUICK LOOK AT A C++ PROGRAM

This output statement consists of two


expressions.
1st : After the first <<, “Length = ”
2nd : after the second <<, consists of
the identifier length.
A QUICK LOOK AT A C++ PROGRAM

The expression “Length = ” is a


string and evaluates to itself.
The second expression, which
consists of the identifier length,
evaluates to whatever the value of
length is.
A QUICK LOOK AT A C++ PROGRAM

Because the value assigned to


length in the program is 6.0,
length evaluates to 6.0. Therefore,
the output of the preceding statement
is:
Length = 6
A QUICK LOOK AT A C++ PROGRAM

The last statement, that is, return


0; returns the value 0 to the operating
system when the program terminates.
Example: string arithmetic
cout << “7 + 8 = ” << 7 + 8 << endl;
The output is: 7 + 8 = 15
A QUICK LOOK AT A C++ PROGRAM
A C++ program is a collection of
functions, one of which is the function
main. A function is a set of statements
whose objective is to accomplish
something.
The preceding program consists of
only the function main; all C++
programs require a function main.
A QUICK LOOK AT A C++ PROGRAM

The first four lines of the program


begins with #, which are comments.
Comments are for the user; they
typically explain the purpose of the
programs, that is, the meaning of the
statements.
A QUICK LOOK AT A C++ PROGRAM

#include <iostream>
allows us to use the (predefined
object) cout to generate output
and the (manipulator) endl.
A QUICK LOOK AT A C++ PROGRAM

using namespace std;


allows us to use cout and endl without
the prefix std::. It means that if you do
not include this statement, then cout
should be used as std::endl.

Note: In C++, << is an operator, called the


stream insertion operator.
A QUICK LOOK AT A C++ PROGRAM

int main ()
This is the heading of the function
main. The next line consists of a left
brace. This marks the beginning of the
(body) of the function main. The right
brace (at the last line of the program)
matches this left brace and marks the end
of the body of the function main.
A QUICK LOOK AT A C++ PROGRAM

Variable declarations. A statement such as


double length; instructs the system to
allocate memory space and name it length.

Assignment statement. This statement instructs the


system to store 6.0 in the memory space length.
Assignment statement. This
Output statement instructs the system to
Statements. An the expression length *
output statement width and store the result in
instructs the the memory space area.
system to display
results.
THE BASICS OF A C++ PROGRAM

• A C++ program is a collection of


one or more subprograms called
functions.
• A subprogram or a function is a
collection of statements, and when it
is activated, or executed, it
accomplishes something.
THE BASICS OF A C++ PROGRAM
• Some functions, called predefined or
standard functions, are already
written and are provided as part of the
system.
• Every C++ program has a function
called main.
• If the C++ program has only one
function, it must be the function
main.
THE BASICS OF A C++ PROGRAM
• The syntax rules determines which
statements (instructions) are legal or
valid, that is, which are accepted by
the programming language and which
are not.
• The semantic rules determines the
meaning of the instructions.
• Programming language is a set of
rules, symbols, and special words.
THE BASICS OF A C++ PROGRAM

• Comments
- can be used to identify the authors of
the program, give the date when the
program is written or modified, give
a brief explanation of the program,
and explain the meaning of key
statements in a program
THE BASICS OF A C++ PROGRAM
• Comments
- are for reader, not for the compiler
- when a compiler compiles a
program to check for the syntax
errors, it completely ignores
comments.
- two type of comments: single-line
and multiple-line comments
THE BASICS OF A C++ PROGRAM
• Single – Line Comments
- single-line comments begin with //
and can be placed anywhere in the
line
- everything encountered in that line
after // is ignored by the compiler
cout << “7 + 8 = ” << 7 + 8 << endl; //prints: 7 + 8 = 15
THE BASICS OF A C++ PROGRAM

• Multiple – Line Comments


- multiple-line comments are enclosed
between /* and */.
- the compiler ignores anything that
appears between /* and */.
/*
You can include comments that can
occupy several lines.
*/
THE BASICS OF A C++ PROGRAM

• Special Symbols
- the smallest individual unit of a
program written in any language is
called a token.
- C++’s tokens are divided into
special symbols, word symbols, and
identifiers.
THE BASICS OF A C++ PROGRAM
• Special Symbols
- the following are some of the special
symbols:
+ - *
/ (mathematical symbols)

. ; ?
, (punctuation marks)

<= != ==
>= (two characters regarded as a single symbol)
THE BASICS OF A C++ PROGRAM
• Special Symbols
- commas are used to separate items
in
- semicolons are used to end a C++
statement
- blank is also a special symbol
created by pressing a space bar (only
once) on the keyboard
THE BASICS OF A C++ PROGRAM
• Reserved Words (Keywords)
- a second category of tokens reserved
word symbols
- some of the reserved word symbols
include the following:
int, float, double, char, const, void, return
- reserved words are also called
keywords
THE BASICS OF A C++ PROGRAM
• Reserved Words (Keywords)
- the letters that make up a reserved word
are always lowercase
- like special symbols, each is considered
to be a single symbol
- reserved words cannot be redefined
within any program; they cannot be used
for anything other than their intended
use
THE BASICS OF A C++ PROGRAM
• Reserved Words (Keywords)
THE BASICS OF A C++ PROGRAM

• Identifiers
- are names of things that appear in
programs, such as variables,
constants, and functions
- all identifiers must obey C++’s
rules for identifiers
THE BASICS OF A C++ PROGRAM

• Identifiers
- a C++ identifier consists of letters,
digits, and the underscore character
(_) and must begin with a letter or
underscore
- some identifiers are predefined;
others are defined by the user
THE BASICS OF A C++ PROGRAM

• Identifiers
- can be made of only letters, digits,
and the underscore character; no
other symbols are permitted to form
an identifier
THE BASICS OF A C++ PROGRAM

Example:
The following are legal identifiers in
C++:
first
conversion
payRate
counter1
THE BASICS OF A C++ PROGRAM
Examples of illegal identifiers in C+
+:Illegal Identifier Reason A Correct Identifier
employee Salary There can be no employeeSalary
space between
employee and
salary
Hello! The exclamation Hello
mark cannot be used
in an identifier.
one+two The symbol + cannot onePlusTwo
be used in an
identifier.
2nd An identifier cannot second
begin with a digit.
THE BASICS OF A C++ PROGRAM
Note:
Compiler vendors usually begin
certain identifiers with an underscore (_).
When the linker links the object program
with the system resources provided by the
integrated development environment
(IDE),certain errors could occur.
Therefore, it is advisable that you should
not begin identifiers in your program with
an underscore (_).
THE BASICS OF A C++ PROGRAM
• Whitespaces
- every C++ program contains
whitespaces
- it include blanks, tabs, and newline
characters
- In C++, they are used to separate
special symbols, reserved words,
and identifiers.
THE BASICS OF A C++ PROGRAM
• Whitespaces
- are nonprintable in the sense that
when they are printed on a white
sheet of paper, the space between
special symbols, reserved words,
and identifiers is white.
- proper utilization of whitespaces in a
program is important.
THE BASICS OF A C++ PROGRAM
• Data Types
- Data type is a set of values together
with a set of allowed operations.
- C++ data types fall into the
following three categories:
 Simple data type
 Structured data type
 Pointers
THE BASICS OF A C++ PROGRAM
• Simple Data Types
- is the fundamental data type in C++
because it becomes a building block
for the structured data type
- Three categories of simple data:
 Integral
 Floating-point
 Enumeration
THE BASICS OF A C++ PROGRAM
• Note:
The enumeration type is C++’s
method for allowing programmers to
create their own simple data types.
Integral data types are further
classified into the following
categories:
char, short, int, long, bool, unsigned char,
unsigned short, unsigned int, unsigned long, long
long, and unsigned long long.
THE BASICS OF A C++ PROGRAM
Values and Memory Allocation for Simple Data Types
Data Type Values Storage (in bytes)
int -2147483648 (= – 231) to 4
2147483648 (=231–1)
bool true and false 1
Char -128 (= – 27 ) to 127 (= 27 – 1) 1
long long -9223372036854775808 (–263) to 64
9223372036854775807 (263 – 1)

Note: Use this table only as a guide.


Different compilers may allow
different ranges of values.
THE BASICS OF A C++ PROGRAM

• Floating – Point Data Types


- a form of scientific notation in C++
to represent decimal numbers
- in the C++ floating-point notation,
the letter E stands for the exponent
THE BASICS OF A C++ PROGRAM
Examples of Decimal Numbers in Scientific and C++
Floating-Point Notations
Decimal Scientific Notation C++ Floating-Point
Number Notation
75.924 7.5924 * 101 7.592400E1
0.18 1.8 * 10-1 1.800000E-1
0.0000453 4.53 * 10-5 4.530000E-5
-1.482 -1.482 * 100 -1.482000E0
7800.0 7.8 * 103 7.800000E3

C++ provides three data types to manipulate


decimal numbers: float, double, and long
double.
THE BASICS OF A C++ PROGRAM

• int Data Type


Two rules:
1. Positive integers do not need a +
sign in front of them.
2. No commas are used within an
integer. (In C++, commas are
used to separate items)
THE BASICS OF A C++ PROGRAM

• bool Data Type


- has only two values: true and
false
- true and false are called logical
(Boolean) values
- central purpose: to manipulate
logical (Boolean) expressions
THE BASICS OF A C++ PROGRAM
• char Data Type
- mainly used to represent single
characters – that is, letters, digits,
and special symbols
- can represent any key on the
keyboard
- when using it, each character
represented is enclosed within single
quotation marks
THE BASICS OF A C++ PROGRAM

• float Data Type


- used to represent any decimal
number between -3.4*1038 and
3.4*1038
- the memory allocated for a value of
the float data type is four bytes
THE BASICS OF A C++ PROGRAM

• double Data Type


- used to represent any decimal
number between -1.7*10308 and
1.7*10308
- the memory allocated for a value of
the double data type is eight bytes
THE BASICS OF A C++ PROGRAM

The maximum and minimum


values of the data types float and
double are system dependent.
Other than the set of values, there
is one more difference between the
data types float and double .
THE BASICS OF A C++ PROGRAM

The maximum number of


significant digits – that is, the number
of decimal places – in float values
is six or seven.
The maximum number of
significant digits in values belonging
to the double type is 15.
THE BASICS OF A C++ PROGRAM

The maximum number of


significant digits is called the
precision. Sometimes float values are
called single precision, and values of
type double are called double
precision.
DATA TYPES, VARIABLES AND ASSIGNMENT
STATEMENTS
When we declare a variable, not
only do we specify the name of the
variable, we also specify what type of
data a variable can store.
A syntax rule to declare a
variable is:
dataType
identifier;
Example: int counter;
double interestRate;
char grade;
DATA TYPES, VARIABLES AND ASSIGNMENT
STATEMENTS

- first statement: allocate four bytes of memory


space to store an int value and name that
memory space counter; counter is a
variable that can store an int value
- interestRate is a variable that can store
a value of type double
- grade is a variable that can store a value of
type char
DATA TYPES, VARIABLES AND ASSIGNMENT
STATEMENTS

One way to store a value in a variable is


by using an assignment statement, which takes
the following form:
variable = expression;
where expression is evaluated and its value
is assigned to variable.
In C++, = is called the assignment
operator.
DATA TYPES, VARIABLES AND ASSIGNMENT
STATEMENTS

For example:
counter = 5;
interestRate = 0.05;
grade = ‘A’;
The first statement stores 5 in the
variable counter, the second statement
stores 0.05 in interestRate, and the
third statement stores the character ‘A’
in grade.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

One of the important use of a


computer is its ability to calculate. You
can use the standard arithmetic operators
to manipulate integral and floating-point
data types.
There are five arithmetic operators:
Arithmetic Operators: +(addition),
–(subtraction or negation),
*(multiplication), /(division), %
(mod, (modulus or remainder))
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

These operators work as follows:


• You can use the operators +, -, *, and /
with both integral and floating-point data
types. These operators work with
integral and floating-point data the same
way as you learned in algebra.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

These operators work as follows:


• When you use / with the integral data
type, it gives the quotient in ordinary
division. That is, integral division
truncates any fractional part; there is no
rounding.
• You can use % with only the integral data
type, to find the remainder in ordinary
division.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND EXPRESSIONS
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

Example 2 – 2:
Given length in inches, write a
program that determines and outputs
the equivalent length in feet and
(remaining) inches.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

Example 2 – 2:

100 inch(es) = 8 feet (foot) and 4 inch(es)


ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

Example:
–5, 8 – 7, 3 + 4, 2 + 3 * 5, 5.6 + 6.2 *
3, and x + 2 * 5 + 6 / y where x and y
are unknown numbers are called
arithmetic expressions.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

The numbers appearing in the


expressions are called operands.
The numbers that are used to
evaluate an operator are called the
operands for that operator.
ARITHMETIC OPERATORS, OPERATOR PRECEDENCE, AND
EXPRESSIONS

• Unary operator – an operator that has


only one operand (i.e. –5, +27)
• Binary operator – an operator that has
two operands (i.e. 8 – 7)
• – and + are both unary and binary
arithmetic operators
• *, /, and % are binary arithmetic
operators
ORDER OF PRECEDENCE
When more than one arithmetic
operator is used in an expression, C++
uses the operator precedence rules to
evaluate the expression.
According to the order of
precedence rules for arithmetic
operators, *, /, % are at higher level
of precedence than +, and –.
ORDER OF PRECEDENCE

Note that the operators *, /, and %


have the same level of precedence.
Similarly, the operators + and – have
the same level of precedence.
When operators have the same
level of precedence, the operations are
performed from left to right.
ORDER OF PRECEDENCE

To avoid confusion, you can use


parentheses to group arithmetic
expressions.
Example:
3*7–6+2*5/4+6
means the following:
((( 3 * 7 ) – 6 )+(( 2 * 5 ) / 4 )) + 6
ORDER OF PRECEDENCE
Note that the use of parentheses
in the second example clarifies the
order of precedence. Parentheses can
also be used to override the order of
precedence rules.
The associativity of the
arithmetic operators is said to be from
left to right.
ORDER OF PRECEDENCE
Example 2 – 3:
#include <iostream>
using namespace std;
int main()
{
cout<<"2 + 5 ="<< 2 + 5<<endl;
return 0;
}
ORDER OF PRECEDENCE
Expressions
There are three types of arithmetic
expression in C++:
• Integral expressions – all operands in the
expression are integers
• Floating-point (decimal) expressions – all
operands in the expression are floating-
point (decimal numbers).
• Mixed expressions – the expression
contains both integers and decimal
numbers
ORDER OF PRECEDENCE
Example
Consider the following C++ integral
expressions:
2+3*5
3+x–y/7
x + 2 * ( y – z ) + 18
In these expressions, x, y, and z are
variables of type int.
ORDER OF PRECEDENCE

Example
Consider the following C++ integral
expressions:
12.8 * 17.5 – 34.50
x * 10.5 + y – 16.2
In these expressions, x and y are
variables of type double.
ORDER OF PRECEDENCE
Mixed Expressions
- an expression that has operands of
different data types
- contains both integers and
floating-point numbers
Examples:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
ORDER OF PRECEDENCE
Two rules apply when evaluating a
mixed expression:
1. When evaluating an operator in
a mixed expression:
a. If the operator has the same
types of operands, the operator
is evaluated according to the
type of the operands
ORDER OF PRECEDENCE
Two rules apply when evaluating a
mixed expression:
1. When evaluating an operator in
a mixed expression:
b. If the operator has both types of
operands, then during calculation,
the integer is changed to a floating-
point number with the decimal part
of zero and the operator is
evaluated.
ORDER OF PRECEDENCE
2. The entire expression is evaluated
according to the precedence rules;
the multiplication, division, and
modulus operators are evaluated
before the addition and subtraction
operators. Operators having the
same level of precedence are
evaluated from left to right.
Grouping using parentheses is
allowed for clarity.
ORDER OF PRECEDENCE
Two rules apply when evaluating a
mixed expression:
1. When evaluating an operator in
a mixed expression:
a. If the operator has the same
types of operands, the operator
is evaluated according to the
type of the operands

You might also like