[go: up one dir, main page]

0% found this document useful (0 votes)
35 views28 pages

Computer PRG Chapter 1,2 & 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views28 pages

Computer PRG Chapter 1,2 & 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 0ne

1.1 Introduction to programming


Computer is a machine that needs instruction to perform a variety of tasks. A program is a set of
instruction that the computer to follow to perform a given job. To write the program a programming
language, a language for a communication between a person and a computer is required. C++ is
one of the most powerful programming languages available. Language translator software is used
by programmers to develop application software and translate programs into machine code (object
code). Language software is a generic name consisting of various programs that serves as editors
and translators to develop programs in different programming language. It includes translators and
high level language software’s.
Type of programming language

Machine language: lowest level of programming languages


usually referred to as first generation language. It is understood completely by computer;
Instruction in machine language is in the form of string of 0s and 1s.

 Assembly language: referred to as second generation language. These languages


use symbols or mnemonic codes to describe machine instructions. It is machine dependent
languages.
 High level language: language that look like natural language. High level language
are further subdivided into three generations:
o Third generation languages: need to spell out in detail each step and the
exact order of steps the computer system must take to accomplish a task.
 Procedure- oriented language: organize instructions into group
of functions and give little attention to the data that are used by various
function. FORTRAN,
PASCAL
 Object- oriented language: treat data as critical element in the
program development. Decompose a problem into a number of entities
called objects and build data and functions around these objects. E.g. Java,
C++ visual basic and so on.
o Fourth generation languages: allow computer user to retrieve, manipulate
and analyze data from computer storage without requiring step by step procedure.
Designed to solve specific problems. Example Query languages and report
generator.
o Fifth generation languages: close to natural languages. Program written in
5GLs tell the computer what to do not how to do.
A program written in assembly language or high level language is called the sources code and the
translated machine code program is called the object code.
Translator: is a program that converts one or more language to another language. There are three
types of translators such as:
 Assembler: translating assembly language into object code
 Compiler: translating the whole source codes written in high level languages into
the object code prior to loading the whole source code into main memory and executing.
 Interpreters: translate and executes and each instruction or source statements
before going onto the next instruction.
In the case of an assembler or a compiler, the source codes need only be translated once unless
the source code itself is modified. In the case of interpreter, the source code is translated every
time the program is executed.
1.2. CHARACTERISTICS OF A GOOD PROGRAM
Every computer requires appropriate instruction set (programs) to perform the required task. The
quality of the processing depends upon the given instructions. If the instructions are improper of
incorrect them it is obvious that the result will also be superfluous. Therefore, proper and correct
instructions should be provided to the computer so that it can fulfill its duties appropriately.
Hence, a program should be developed in such a way that it ensures proper functionality of the
computer. Even from the human point of view, a program should be written in such a manner
that it is easier to understand the underlying logic. A few important characteristics that a
computer program should possess are:
1. Portability: Portability refers to the ability of an application to run on different
platforms (operating systems) without or with minimal changes. Due to rapid
development in hardware and the software, nowadays platform change is a common
phenomenon. Hence, if a program is developed for a particular platform then the life
span of the program is severely affected.
2. Readability: The program should be written in such a way that it makes other
programmers or users follow the logic of the program is written structurally, it even helps
the programmer himself to follow his own program in a better way if he is away from in
for some time. Notice that even if you had to sacrifice some computational efficiency for
better readability then it is advisable to use more user-friendly approach unless the
application’s processing is of utmost importance.
3. Efficiency: Every program requires certain processing time and memory to
process the instructions and data. As you must have realized, processing power and
memory are the most precious resources of a computer, a program should be laid out in
such a manner that it utilizes the least amount of memory and processing time.
4. Structural: To develop a program, the task must be broken down into a number
of subtasks. These subtasks should be developed independently, that is each subtask
should be able to perform the assigned job without the help of any other subtask. If a
program is developed structurally, the program not only becomes more readable, but the
testing and documentation process also gets easier.
5. Flexibility: A program should be flexible enough to handle most of the changes
without having to rewrite the entire program. Most of the programs are developed for a
certain period and they require changes from time to time. For example, in case of
payroll management, as the time progresses, some employees may leave the company
while some may join. Hence, the payroll application should be flexible enough to
incorporate all the changes without having to reconstruct the entire application.
6. Generality: Apart from flexibility, the program should also be general. We mean
that if a program is developed for a particular task then it should also be used for all
similar tasks of the same domain. For example, if a program is developed for a particular
organization then should suit all the other similar organizations.
7. Documentation: Documentation is one of the most important components of an
application development Even if a program is developed following the best programming
practices, it will be rendered useless if the end user is not able to fully utilize the
functionality of the application A well-documented application is also useful for
programmers because even in the absence of the author, other programmers can
understand it.
Chapter two
Software development method
A program consists of a series of instructions that a computer processes to perform the required
operation. In addition, it also includes some fixed data, required to perform the instructions, and
the process of defining those instructions and data. Thus, in order to design a program, a
programmer must determine three basic rudiments:
the instructions to be performed.

the order in which those instructions are to be


performed.

the data required to perform those instructions.

A, B C=A + B C

Input Processing Output


Programming involves many stages such as task analysis, planning the logic, program
flowcharting, coding, program testing, implementation, documentation and maintenance.
There are five steps for program/software development such as task analysis program (Algorithm)
design, coding testing, implementation, and maintenance.
1. Analysis: the steps at which defining and understanding the problem. In this phase work
out what must be done rather than how to do it. It include identifying

Which part of the problem is going to be solved

What input data are needed to the problem

What output data are expected

What procedure are needed to achieve the goal


2. Program (Algorithm) design: this phase design a solution to solve the problem. An
algorithm is a finite set of steps to a problem. To design an algorithm for specific problem we first
break down the problem into simpler and manageable tasks. This approach is said to be top down
approach. The algorithm that we select must be:
Simple and powerful,
There must be no ambiguity in any instruction
There should not be any uncertainty about which instruction is to be executed next
The description of the algorithm must be finite. Algorithm cannot be open ended
The execution of algorithm should conclude after a finite number of
steps The algorithm must be general enough to deal with any
contingency.

Correct: easy to maintain and correct


o Does the algorithm terminate?
o Do the appropriate input data produce expected output data?
o Does properly handle valid and extreme cases?
Efficient: it does not take too much space and time
There are different ways of describing an algorithm. These are narrative (or verbal form), flowchart
and pseudo code and so on.
Narrative
Example 1: Algorithm that determine the largest number out of three numbers A, B, and C
1. Start
2. Read three number let say A, B, and C
3. Find the largest number between A and B and store it in Max_AB
4. Find the largest number between Max_AB and C and store it in Max
5. Display Max
6. Stop
Example 2: the next algorithm finds the average of N numbers.
1. start
2. Initialize N, num, sum and average to zero
3. Read total number of integers, using which the average is to found and store it in N
4. While numbers to be added are less than N, follow these two sub tasks repeatedly.
Read number and store it in num.
Add num to sum (sum=sum + num)
5. calculate the average by using the formula: Average = sum/ N

6. Display the average


7. stop

Flowchart
A flowchart is a diagram consisting of labeled symbols, together with arrows connecting one
symbol to another. It is means of showing the sequence of steps of an algorithm. The primary
purpose of flowchart is to help the programmer in understanding the logic of the program. The
basic symbol of flowchart and their meaning are given as follow:

1. Terminal: - representing the beginning and end


of a program.

2. Flowline: - indicate the direction of logical flow

3. Input/output: - shows input or output data.

4. Process: - express arithmetic


operations and data movement instructions.

5. Connector: - is used for connecting two points in a program


without flowlines. A pair of identical labeled connector symbol denotes
that the indicated points of the flowchart are connected
6. Decision: - indicates logic/comparison operation. The
particular path that is chosen depends on the answer to a question or the
result of a test. There is at least one entry and two exits.

7. Predefined process: - indicates a process which


is defined elsewhere that is used several times in the same program.
8. Annotation flag: - is used to add clarifying comments or
descriptions. They do not represent a logical step or calculations in the
program.

Guide line to draw flow chart


 Every program flowchart should begin with the oval symbol containing
START or BEGIN and end with STOP or E ND
 In every program flowchart, crossing flow of lines should be avoided
 Only one flow of line should come from a process symbol
 Only one flow line should enter a decision symbol However, two or three
flow lines (one for each possible answer) may leave the decision symbol.
 Only one flow line is used with a terminal symbol.
 The direction of the flow of procedure should always be from left to right
or top to bottom.
Flow chart structure
There are three key constructs which are used in drawing flowcharts
1. Sequence where information flow in straight line, on a flow chart the symbol
representing each instruction has only a single entering path and a single existing path.
Typical sequence operations consist of process and input/output steps.

Sequence structure Example Instruction

Begin the flow chart

Initiate value for variable x and y

Add x and y and store the result in


variable z
Output the value of variable z

Terminate the flow chart


2. Selection: where the decision are made according to some to some predefined
condition

3. Repetition: where the logic can be repeated in a loop, that is, where a sequence of
steps is repeated until the desired output is obtained.

Exercise: -
I. Draw a flow chart for an algorithm of a program that will add two numbers
II. Draw a flowchart of an algorithm for solving a quadratic equation ax2 + bx + C=0
where the coefficient a, b, and c are real numbers and a≠ 0
3. Coding: At this step the language independent algorithm is implemented /translated to an
equivalent instruction of certain programming language.
4. Implementation: - consist of three steps such as debugging, testing and documenting
the problem.
Debugging: The process of removing errors in a program is called debugging. Errors in a program
are called bugs.
Testing: a process of checking a program is correct that is, it does what it is supposed to do. Testing
data should be organized and prepared which include valid data that check the validity of main
flow of the logic and invalid data that checks the capability of the program of handling exceptional
cases. Testing involve three stages unit testing, integration testing and system testing.
Program documentation: A complete program should be documented.

C++ programming environment


Compiling C++ program
The only language really understood by a computer is its own machine language. Programs
expressed in the machine language are said to be executable. A program written in any other
language needs to be first translated to the machine language before it can be executed. A
program written in a high-level language is translated to machine language by a translator called
a compiler. This process is said to compiling.
How you will compile C++ source code depends upon your compiler and what options you are
using. Many compilers provide two different ways for compiling a program: the command-line
compiler and the Integrated Development Environment (IDE). Thus, it is not possible to give
generalized instructions for compiling a C++ program. You must consult your compiler’s
instructions. The output from a C++ compiler is executable object code.
Compiling a C++ program involves a number of steps (most of which are transparent to the user):

First, the C++ preprocessor goes over the program text and carries out the instructions
specified by the preprocessor directives (e.g., #include). The result is a modified program text
which no longer contains any directives.

Then, the C++ compiler translates the program code. The compiler may be a true C++
compiler which generates native (assembly or machine) code, the outcome may be incomplete
due to the program referring to library routines which are not defined as a part of the program.
For example, example above refers to the << operator which is actually defined in a
separate IO library.

Finally, the linker completes the object code by linking it with the object code of any
library modules that the program may have referred to. The final result is an executable file.
Figure below illustrates the above steps for both a C++ translator and a C++ native compiler. In
practice all these steps are usually invoked by a single command (e.g., CC) and the user will not
even see the intermediate files generated.
FIGURE 1.1 C++ COMPILATION
C++
C++
Program
TRANSLATOR Object
Linker
Code

Co

Execute Executable
code

Running a program
To run or execute a program we need to transform the source file into an executable file. This
is done using the following two steps.

You must compile the source file. Compiling the source file generates an object file.

You must create an executable program file by combining different object files. This step is
called linking.
An executable program file consists of more than one object file. This is due to the following two
major reasons
1. The programmer may have divided the program into several source files and each source
file is then compiled into a separate object file
2. The library routines come in object file form.
Type of program errors
Syntax errors: are errors which occur due to violation of the syntax of grammar rule of the
programming language. It is detected by the compiler during compiling time.
E.g. forgetting a semicolon at the end of each statement of C++, Miss Spell of key
word

Linker time error: Are an error which are detected during linking.

E.g. miss spell of the name main function, Missing object file
Run time error: are errors which occur while executing or running the program. It is
difficult to identify and correct. It also includes logical errors. Logical errors is an error in
which the program compile and run normally, but would give the wrong answer.
E.g. infinite loop, dividing a number by the zero
Chapter Three
1. Fundamental of the c++ programming language

C++ has a large number of fundamental or built-in object types

The fundamental object types fall into one of three categories

■ Integers objects
■ Floating-point objects Z
■ Character objects

51.28345

1P3.14

 The basic integer object type is int

■ The size of an int depends on the machine and the compiler–

On PCs it is normally 16 or 32 bits

●Other integers object types

■ short: typically uses less bits

■ long: typically uses more bits

Different types allow programmers to use resources more efficiently

Standard arithmetic and relational operations are available for these types
Character object type
Character type char is related to the integer types

Characters are encoded using a scheme where an integer represents a particular


character

ASCII is the dominant encoding scheme

■ Examples

– ' ' encoded as 32

– '+' encoded as 43

– 'A' encoded as 65

– 'Z' encoded as 90

– 'a' encoded as 97

- 'z' encoded as 122


Arithmetic and relational operations are defined for characters types

■ 'a'< 'b' is true

■ '4' > '3' is true

Character constant
Explicit characters within single quotes

'a' , 'D', '*'

Special characters - delineated by a backslash \

■ Two character sequences (sometimes called escape codes) within single


quotes

■ important special characters

'\t' denotes a tab

'\n' denotes a new line

'\\' denotes a backslash


Literal String Constant
There also exist non-numerical constants, like:
'z'
'p'
"Hello world"
"How do you do?"
The first two expressions represent single character constants, and the following two represent
string literals composed of several characters. Notice that to represent a single character we
enclose it between single quotes (') and to express a string (which generally consists of more than
one character) we enclose it between double quotes (").

When writing both single character and string literals, it is necessary to put the quotation marks
surrounding them to distinguish them from possible variable identifiers or reserved keywords.
Notice the difference between these two expressions:

x
'x'
x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single
quotation marks) would refer to the character constant 'x'. Back slash character constant
Character and string literals have certain peculiarities, like the escape codes. These are special
characters that are difficult or impossible to express otherwise in the source code of a program,
like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of
some of such escape codes:

\a alert
(beep)

\' single quote (')

\" double quote (")

\? question mark
(?)

\\ backslash (\)
\n newline

\r carriage return

\t tab Forexample:
\v vertical Cout<<'\n'
tab
Cout<<'\t'
Cout<<"Left \t Right"
\b backspace
Cout<<"one\ntwo\nthree"
\f form feed (page feed)

Floating point type


Floating-point object types represent real numbers

■ Integer part

■ Fractional part

● The number 108.1517 breaks down into the following parts

■ 108 - integer part

■ 1517 - fractional part

● C++ provides three floating-point object types

 float
 double
 long double

● Standard decimal notation


■ Digits . Digits [ f | F | l | L]

134.123

0.15 F

● Standard scientific notation


■ Digits . Digits Exponent [ f | F | l | L]

■ Where

– Exponent is (e | E) [ + | -] Digits

1.45E6

0.979e-3 L

When not specified, floating-point constants are of type double


C++ Basic Elements

Programming language is a set of rules, symbols, and special words used to construct programs.
There are certain elements that are common to all programming languages. Now, we will discuss
these elements in brief:

C++ Character Set

Character set is a set of valid characters that a language can recognize.

Letters A-Z, a-z


Digits 0-9
Special Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ?
Characters _ # <= >= @
Formatting backspace, horizontal tab, vertical tab, form feed, and carriage
characters return

Tokens

A token is a group of characters that logically belong together. The programmer can write a
program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

Keywords

Keywords are words reserved as part of the language

– int, return, float, double

■ They cannot be used by the programmer to name things

■ They consist of lowercase letters only

■ They have special meaning to the compiler

asm do if return
auto double inline short

bool dynamic_cast int signed

break delete long sizeof union


case else mutable static unsigned

catch enum namespace static_cast using

char explicit new struct virtual

class extern operator switch void

const false private template volatile

const_cast float protected this wchar_t

continue for public throw while

default friend register true union


delete goto try unsigned

Identifiers

● Identifiers should be

■ Short enough to be reasonable to type (single word is norm)

– Standard abbreviations are fine (but only


standard abbreviations)

■ Long enough to be understandable

– When using multiple word identifiers capitalize


the first letter of each word

● Examples

 Min
 Temperature
 CameraAngle
 CurrentNbrPoints
2. The structure of C++ programs

Program comment
 Allow prose or commentary to be included in program
 Importance

■ Programs are read far more often than they are written

■ Programs need to be understood so that they can be maintained

 C++ has two conventions for comments

■ // single line comment ( preferred )

■ /* long comment */ (save for


debugging)

● Typical uses

■ Identify program and who wrote it

■ Record when program was written

■ Add descriptions of modifications


Preprocessor directive
Pre-processor directives are instructions to the compiler. It is not program statements. Pre-
processor directives in a program always start with # E.g. # include
Include is a preprocessor instruction that says “what follow is a filename find that file and read
it in right here” the angle brackets around the file name tell the preprocessor to look in the entire
usual place for this file. The # include directive tells the compiler to insert the specified header
file into the source file. Header file contain declaration that are needed by most pre-defined
library functions.
The second part contains the main ( ) functions. The functions are building blocks of C++. The
main function is composed of variables declaration n and statements. If the main function does
not return anything, then it should be preceded by the key word void otherwise it should be
preceded by one of the data types.
Include can be used with the o Angle bracket < > surrounding the header file name. This tells the
compiler should begin searching for the specified header file in the standard “Include”
directory
o Quotation mark (“ “) surrounding the header file name. This instructs the compiler to start
searching for the specified header file in the current directory. Usually the directory that
contains the source file.
# include<header-file>
# include “stack.h”
Int/void main ()
{
Variable declaration;
Statement 1;
Statement 2;

Statement n;
[return 0;]
}

Annotation
1 This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behaviour of the program. The programmer can
use them to include short explanations or observations within the source code itself. In this
case, the line is a brief description of what our program is. C++ supports two ways to insert
comments:
• // line comment
• /* block comment */
The first of them, known as line comment, discards everything from where the pair of slash
signs (//) is found up to the end of that same line. The second one, known as block comment,
discards everything between the /* characters and the first appearance of the */ characters, with
the possibility of including more than one line.
2 Lines beginning with a pound sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In this case
the directive #include <iostream.h> tells the preprocessor to include the iostream and conio.h
standard file to the program. This specific file (iostream) includes the declarations of the basic
standard input-output library in C++, and it is included because its functionality is going to be
used later in the program. Conio.h file include the declaration for getch(), clrscr() command.
Preprocessor directives must be specified in their own line and do not have to end with a
semicolon (;).
3 This line defines a function called main. A function may have zero or more parameters;
these always appear after the function name, between a pair of brackets. The word void
appearing between the brackets indicates that main has no parameters. A function may also
have a return type; this always appears before the function name. The return type for main is
int (i.e., an integer number) or void. All C++ programs must have exactly one main function.
Program execution always begins from main.
4 This brace marks the beginning of the body of main.
5 Clear the screen, Remove what is displayed on the screen before this statement
6 This line is a statement. A statement is a computation step which may produce a value.
cout represents the standard output stream in C++, and the meaning of the entire statement is
to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen). The end of a statement is always marked
with a semicolon (;). This statement causes the string "Hello World\n" to be sent to the cout
output stream. A string is any sequence of characters enclosed in double-quotes. The last
character in this string (\n) is a newline character which is similar to a carriage return on a type
writer. A stream is an object which performs input or output. Cout is the standard output stream
in C++ (standard output usually means your computer monitor screen). The symbol << is an
output operator which takes an output stream as its left operand and an expression as its right
operand, and causes the value of the latter to be sent to the former. In this case, the effect is
that the string "Hello World\n" is sent to cout, causing it to be printed on the computer monitor
screen.
7 Pause the output displayed to the screen 8 this brace marks the end of the body of main.

Variables and Data type


A variable is a container for information you want to store. A variable’s value can change while
the program is running. In c++ the name of variable is called an identifier. A variable is a symbolic
name for a memory location in which data can be stored and subsequently recalled. Variables are
used for holding data values so that they can be utilized in various computations in a program.
All variables have two important attributes:

A type which is established when the variable is defined (e.g., int, float, char). Once
defined, the type of a C++ variable cannot be changed. Used to specify the type of data
that is going to be stored in variable.

A value which can be changed by assigning a new value to the variable, the kind of
values a variable can assume depends on its type. For example, an integer variable can
only take integer values (e.g., 2, 100, -12).

We could have called the variables any names we wanted to invent, as long as they were valid
identifiers. A valid identifier is a sequence of one or more letters, digits or underscores characters
(_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters,
digits and single underscore characters are valid. In addition, variable identifiers always have to
begin with a letter. They can also begin with an underline character (_), but in some cases these
may be reserved for compiler specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters. In no case they can begin with a digit.
Variable Declaration
In order to use a variable in C++, we must first declare it specifying which data type we want it
to be. The syntax to declare a new variable is to write the specifier of the desired data type (like
int, bool, float...) followed by a valid variable identifier.
Syntax (Declaration):
Data-Type Variable-Name;

Example:

int a;
float
mynumber; int
x_y; char xx2;
These are two valid declarations of variables. The first one declares a variable of type int with the
identifier a, the second one declares a variable of type float with the identifier mynumber and so
on. Once declared, the variables can be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can declare all of them in
a single statement by separating their identifiers with commas. For example:

int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning
as:

int a;
int b;
int c;

Initialization

To assign value to variable we use equal sign. The assigning of a value to a variable for the first
time is called initialization. It is important to ensure that a variable is initialized before it is used
in any computation. It is possible to define a variable and initialize it at the same time. This is
considered a good programming practice, because it pre-empts the possibility of using the
variable prior to it being initialized. int a, b, c; a=5; b=6; c=7; or simply as int a=5, b=6, c=7; at
the time of declaration.

Operators

FORMATTING INPUT/OUTPUT
The most common way in which a program communicates with the outside world is through
simple, character-oriented Input/Output (IO) operations. C++ provides two useful operators for
this purpose: >> for input and << for output. Both << and >> return their left operand as their
result, enabling multiple input or multiple output operations to be combined into one statement.
Example
cin >> workHours >> payRate;
cout << "Weekly Pay = " <<
weeklyPay << “\n”;
EXPRESSIONS
An expression is any valid combination of operators, constants and variable. An expression is
any computation which yields a value. C++ provides operators for composing arithmetic,
relational, logical, bitwise, and conditional expressions. It also provides operators which
produce useful side-effects, such as assignment, increment, and decrement. We will look at each
category of operators in turn. We will also discuss the precedence rules which govern the order
of operator evaluation in a multi-operator expression.
ARITHMETIC OPERATORS
C++ provides five basic arithmetic operators. These are summarized in Table below
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 // gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real
operands. Generally, if both operands are integers then the result will be an integer. However,
if one or both of the operands are reals then the result will be a real (or double to be exact).
Integer division always results in an integer outcome (i.e., the result is always rounded down).
For example: 9 / 2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
To obtain a real division when both operands are integers, you should cast one of the operands
to be real: int cost = 100;
int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder
of integerdividing the operands.
It is possible for the outcome of an arithmetic operation to be too large for storing in a designated
variable. This situation is called an overflow. The outcome of an overflow is machine-
dependent and therefore undefined. For example:
unsigned char k = 10 * 92; // overflow: 920 > 255
It is illegal to divide a number by zero. This results in a run-time division-by-zero failure which
typically causes the program to terminate.
Examples 1 Div. Operator

 3 / 2 evaluates to 1
 4 / 6 evaluates to 0
 10 / 3 evaluates to 3
Examples 2 Mod

o 5 % 2 evaluates to 1
o 12 % 4 evaluates to 0
o 4 % 5 evaluates to 4
RELATIONAL (COMPARISON) OPERATORS
C++ provides six relational operators for comparing numeric quantities. These are summarized
in Table below. Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Note that the <= and >= operators are only supported in the form shown. In particular, =< and
=> are both invalid and do not mean anything.
The operands of a relational operator must evaluate to a number. Characters are valid operands
since they are represented by numeric values. For example (assuming ASCII coding): 'A' < 'F'
// gives 1 (is like 65 < 70)
The relational operators should not be used for comparing strings, because this will result in the
string addresses being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses
are determined by the compiler (in a machine-dependent manner), the outcome may be 0 or
may be 1, and is therefore undefined. C++ provides library functions (e.g., strcmp) for the
lexicographic comparison of string.
LOGICAL OPERATORS
C++ provides three logical operators for combining logical expression. These are summarized
in Table below. Like the relational operators, logical operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 0
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical negation is a unary operator, which negates the logical value of its single operand. If
its operand is nonzero it produce 0, and if it is 0 it produces 1.
Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero
value can be used to represent the logical true, whereas only zero represents the logical false.
The following are, therefore, all valid logical expressions:
!20
// gives 0 10 && 5
// gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
C++ does not have a built-in boolean type. It is customary to use the type int for this purpose
instead. For example:
int sorted = 0;
// false int
balanced = 1; // true

INCREMENT/DECREMENT OPERATORS
The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in Table
below. The examples assume the following variable definition: int k = 5;
Operator Name Example
++ Auto Increment ++k + 10 // gives 16
(prefix)
++ Auto Increment k++ + 10 // gives 15
(postfix)
-- Auto Decrement --k + 10 // gives 14
(prefix)
-- Auto Decrement k-- + 10 // gives 15
(postfix)
Both operators can be used in prefix and postfix form. The difference is significant. When used
in prefix form, the operator is first applied and the outcome is then used in the expression. When
used in the postfix form, the expression is evaluated first and then the operator applied.

ASSIGNMENT OPERATOR
The assignment operator is used for storing a value at some memory location (typically denoted
by a variable). Its left operand should be an lvalue, and its right operand may be an arbitrary
expression. The latter is evaluated and the outcome is stored in the location denoted by the
lvalue. An lvalue (standing for left value) is anything that denotes a memory location in which
a value may be stored.
The assignment operator has a number of variants, obtained by combining it with the arithmetic
operators. These are summarized in Table below. The examples assume that n is an integer
variable.
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
An assignment operation is itself an expression whose value is the value stored in its left
operand. An assignment operation can therefore be used as the right operand of another
assignment operation. Any number of assignments can be concatenated in this fashion to form
one expression. For example:
int m, n, p;
m = n = p = 100; //
means: n = (m = (p = 100)); m = (n = p =
100) + 2; // means: m = (n = (p =
100)) + 2;
This is equally applicable to other forms of assignment. For
example: m = 100; m += n = p = 10; //
means: m = m + (n = p = 10);
COMMA OPERATOR
Multiple expressions can be combined into one expression using the comma operator. The
comma operator takes two operands. It first evaluates the left operand and then the right
operand, and returns the value of the latter as the final outcome. For example:
int m, n, min;
int mCount = 0, nCount = 0;

THE SIZEOF OPERATOR


C++ provides a useful operator, sizeof, for calculating the size of any data item or type. It takes
a single operand which may be a type name (e.g., int) or an expression (e.g., 100) and returns
the size of the specified entity in bytes. The outcome is totally machine-dependent.
OPERATOR PRECEDENCE
The order in which operators are evaluated in an expression is significant and is determined by
precedence rules. These rules divide the C++ operators into a number of precedence levels (see
Table below). Operators in higher levels take precedence over operators in lower levels.

Level Operator Kind Order

Highest () [] Binary Left to Right

! ++ -- Unary Right to Left

* / % Binary Left to Right

+ - Binary Left to Right

< <= > >= Binary Left to Right

== != Binary Left to Right

&& Binary Left to Right


|| Binary Left to Right

?= Ternary Left to Right

= += *= %= Binary Right to Left


Lowest -= /=
For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then added to b
because + has a higher precedence than ==, and then == is evaluated. Precedence rules can be
overridden using brackets. For example, rewriting the above expression as a == (b + c) * d
causes + to be evaluated before *. Operators with the same precedence level are evaluated in the order
specified by the last column of Table above. For example, in a = b += c
the evaluation order is right to left, so first b += c is evaluated, followed by a = b.
SIMPLE TYPE CONVERSION
A value in any of the built-in types we have seen so far can be converted (type-cast) to any of the other
types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to
give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is
122
(unsigned short) 3.14 // gives 3 as an unsigned short
As shown by these examples, the built-in type identifiers can be used as type operators. Type operators
are unary (i.e., take one operand) and appear inside brackets to the left of their operand. This is called
explicit type conversion. When the type name is just one word, an alternate notation may be used in
which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This happens when values of different types
are mixed in an expression. For example:
double d = 1;
// d receives 1.0 int i = 10.5;
// i receives 10

i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to double (promoted) and
then added to d. The result is a double which does not match the type of i on the left side of the
assignment, so it is converted to int (demoted) before being assigned to i.

You might also like