0% found this document useful (0 votes)
7 views

C++ Sanjoy Sir Slides

The document provides an overview of computer programming and numerical methods in civil engineering, detailing the components of a computer system, including input, storage, processing, and output units. It explains data representation in binary form, conversion between decimal and binary, and the structure of a C++ program, including the use of compilers and text editors. Additionally, it covers the importance of algorithms, flowcharts, and the representation of signed and floating-point integers.

Uploaded by

u2101026
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)
7 views

C++ Sanjoy Sir Slides

The document provides an overview of computer programming and numerical methods in civil engineering, detailing the components of a computer system, including input, storage, processing, and output units. It explains data representation in binary form, conversion between decimal and binary, and the structure of a C++ program, including the use of compilers and text editors. Additionally, it covers the importance of algorithms, flowcharts, and the representation of signed and floating-point integers.

Uploaded by

u2101026
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/ 301

CE 205

Computer Programming & Numerical Methods in Civil Engineering

Sanjoy Das
Assistant Professor

Department of Civil Engineering


Chittagong University of Engineering & Technology
COMPUTER AND ITS COMPONENTS
A computer system consists of mainly four basic units;
namely
 input unit
 storage unit
central processing unit (cpu) and
output unit
Central Processing unit further includes
Arithmetic logic unit and
control unit
A computer performs five major operations or
functions irrespective of its size and make. These
are:
• it accepts data or instructions as input,
• it stores data and instruction,
• it processes data as per the instructions,
• it controls all operations inside a computer, and
• it gives results in the form of output.
Functional Units:
a. Input Unit: This unit is used for entering data and
programs into the computer system by the user for
processing.
b. Storage Unit: The storage unit is used for storing
data and instructions before and after processing.
c. Output Unit: The output unit is used for storing the
result as output produced by the computer after
processing.
d. Processing:
The task of performing operations like arithmetic and logical
operations is called processing.
The Central Processing Unit (CPU) takes data and instructions from
the storage unit and makes all sorts of calculations based on the
instructions given and the type of data provided.
It is then sent back to the storage unit.

CPU includes Arithmetic logic unit (ALU) and control unit (CU)
• Arithmetic Logic Unit:
All calculations and comparisons, based on the instructions provided,
are carried out within the ALU.
It performs arithmetic functions like addition, subtraction,
multiplication, division and also logical operations like greater than,
less than and equal to etc.
• Control Unit:
Controlling of all operations like input, processing and output are
performed by control unit.
Memory
Computer’s memory can be classified into two types:
a. primary memory and
b. secondary memory

a. Primary Memory can be further classified as RAM and ROM


(internal storage unit).

• RAM or Random Access Memory


• ROM or Read Only Memory
b. Secondary Memory
Secondary storage devices are of two types;
• magnetic and
• optical.
Magnetic devices include hard disks and
Optical storage devices are Compact Disk (CD), Digital Video Disk
(DVD), Pen drive, Zip drive etc.

HDD=Hard Disk Drive


SSD=Solid State Drive
Input / Output Devices:
Input Devices
• Keyboard
• Mouse
• Trackball
 Touchpad
• Touch Screen
• Light Pen (stylus)
• Magnetic ink character recognition (MICR)
• Optical mark recognition (OMR) or Mark Sense Reader
• Bar code reader (Photoelectric Scanner)
• Scanner
Output Devices:

•Monitor
• Printer
• Plotter
• Facsimile (FAX)
• Sound cards and Speaker(s)
Algorithm & Flowchart
• An algorithm is a set of instructions, sometimes called a procedure or
a function that is used to perform a certain task.
• An algorithm generally takes some input, carries out a number of
effective steps in a finite no.
• an algorithm is a set of instructions for solving a problem.
• Each operation in an algorithm must be doable.
• Algorithms should be composed of a finite number of operations and
they should complete their execution in a finite amount of time.
• By using an algorithm, decision-making becomes a more rational
process.
• A flow chart, or flow diagram, is a graphical
representation of a process or system that
details the sequencing of steps required to
create output.
• A typical flow chart uses a set of basic
symbols to represent various functions,
and shows the sequence and interconnection
of functions with lines and arrows.
Any Questions???
CE 205
Computer Programming

Sanjoy Das
Assistant Professor

Department of Civil Engineering


Chittagong University of Engineering & Technology
Data Representation

 In our familiar number system we have symbols ( to


) to represent a number.
 We call it decimal system or base system.
 To process data in a computer, we need to represent
them in the registers of the processor.
 A register consists of several circuits.
Data Representation

 Can we represent 10 symbols using an electric circuit?


Obviously no.
 We can symbolize an electric circuit into two states such
as-
(a) contains current (1)
(b) no current(0)
 Similarly for a magnetic media such as a disk we may
consider two states-
(a) magnetized clockwise
(b) magnetized counterclockwise
Data Representation

 We may think these two states as two symbols (say one


is and the other is ) to represent a number.
 Thus we have only two digits to represent a number in
the computer processor, in the memory or in the data
storage devices.
 Each individual circuit represents a digit and we term it as
a bit (it is an abbreviation from binary digit).
 Thus, at circuit level, we can represent a number in the
computer in binary form.
Data Representation

 Computers work with the binary or base-two system of


numbers that uses the two digits and instead of the
ten digits – of the more familiar decimal or base-ten
system.
 In the binary system, a number is denoted as-
…… …… (1)

 Where and are two integer indices.


 The binary digits or bits, take the value of or , and
the period (.) is the binary point.
Data Representation

 The implied value is equal to-


× + × +⋯+ ×
+ × +⋯ × (2)

 In the decimal system, the same number is expressed


as-
…… …… (3)

 Where and are two integer indices.


 The decimal digits, take values in the range − ,
and the period (.) is the decimal point.
Data Representation

 The implied value is equal to-


× + × + ⋯+ ×
+ × +⋯ × (4)

 Which is identical to that computed from the base-two


expansion.
 Since bits can be represented by the on-off positions of
electrical switches that are built in the computer’s
electrical circuitry, and since bits can be transmitted by
positive or negative voltage as a Morse code, the
binary system is ideal for developing a computer
architecture.
Data Representation

Conversion from Decimal to Binary


 The conversion from a decimal number to a binary
number can be explained by the following example-



− =









Data Representation

Conversion from Decimal to Binary


 The conversion from a decimal number (non - integer) to
a binary number can be explained by the following
example-

. × = .

− . × = .
− . × = .
− . × = .

− . × = .

. 28125 = .
Data Representation

Conversion from Binary to Decimal


 The conversion from a binary number to a decimal
number can be explained by the following example-
× =
× =
× =
× =
× = =
× =
× =
× =
× =
× =
× =
× =
× =
Data Representation

Conversion from Binary to Decimal


 The conversion from a binary number (non – integer) to a
decimal number can be explained by the following
example-
× =
× = × =
× = × = .
× = × =
× = × =
× = × = .
× =
× = .
× =

. = . 28125
Data Representation

The Largest Integer Encoded by Bits


 Each individual circuit represents a digit and we term it
as a bit (it is an abbreviation from binary digit).
 As you all know, the largest number for a given number of
digits can be obtained by filling out each position with the
largest symbol.
 Such as :
 in decimal, largest number with 3 digits = 999

 similarly, in binary, largest number with 3 digits = 111


Data Representation

The Largest Integer Encoded by Bits


 So, the largest integer that can be represented with
bits is-
… (5)

 Where the ones are repeated times.


 The decimal - number equivalent is-
× + × + × +⋯
+ × + × + × = − (6)
Data Representation

The Largest Integer Encoded by Bits


 To demonstrate this equivalence, we recall from our
college years-

− = ( − )( + +⋯ + )(7)

 Where and are two variables and set = and


= .
Data Representation

The Largest Integer Encoded by Bits


 When one bit is available, we can describe only the
integers and , and the largest integer is .
 With two bits the maximum is − = .
 With three bits the maximum is − = .
 With eight bits the maximum is − = .
 With thirty-onebits the maximum is
− = .
Data Representation

Signed Integers
 To encode a signed integer, we allocate the first bit to
the sign.
 If the leading bit is , the integer is positive; if the
leading bit is , the integer is negative.
 The largest signed integer that can be represented with
bits is then-

 According to this convention, the integer − = −


is stored as the binary string .
Data Representation

Signed Integers
Data Representation Scheme for Integers
………………………………………………………..

Sign Bit

………………………………………………………..

1 1 0 1

− =−
Sign Bit is stored as the binary string
Data Representation

Signed Integers
Data Representation Scheme for Non-Integers (Floating
Point Numbers)
 The floating-point representation allows us to store real
numbers (non-integers) with a broad range of
magnitudes, and carry out mathematical operations
between numbers with disparate magnitudes.
Data Representation

Signed Integers
Data Representation Scheme for Non-Integers (Floating
Point Numbers)
 Consider the binary number-
.
 To develop the floating-point representation, we recast
this number into the product-
. ×
 Note that the binary point has been shifted to the left by
tan places, and the resulting number has been multiplied
by the binary equivalent of .
 The binary string is the
mantissa or significand, and 10 is the exponent.
Data Representation

Signed Integers
Data Representation Scheme for Non-Integers (Floating
Point Numbers)
 To develop the floating-point representation of an
arbitrary number, we express it in the form-
± × (9)
 Where is a real number called the mantissa or
significand, and is the integer exponent.
 This representation requires one bit for the sign, a set
of bytes for the exponent, and another set of bytes
for the mantissa.
Data Representation

Signed Integers
Data Representation Scheme for Non-Integers (Floating
Point Numbers)
 In memory, the bits are arranged sequentially in the
following order-
………………………………………………………..

Exponent Mantissa
Sign Bit

 The exponent determines the shift of the binary point in


the binary representation of the mantissa.
Data Representation

• For a 32-bit float type, the mantissa is stored in a


23-bit segment and the exponent in an 8-bit
segment, leaving 1 bit for the sign of the number.
For a 64-bit double type, the mantissa is stored in
a 52-bit segment and the exponent in an 11-bit
segment.
Object Oriented Programming
with C++

Prepared by
Sanjoy Das
Assistant Prof.
Dept. of CE, CUET
Structure of C++ Program

Include Files

Class Definition

Class Function Definition

Main Function Program


Simple C++ Program
// Hello World program
comment
#include <iostream>
Allows access to an I/O
library
int main() {
Starts definition of special
cout << "Hello World\n"; function main()

output (print) a
string
return 0;
} Program returns a status
code (0 means OK)
Preprocessing

Temporary file
C++ (C++ program) C++
Preprocessor Compiler

Executable
C++ Program Program
CE 218
Computer Programming Sessional

Sanjoy Das
Lecturer

Department of Civil Engineering


Chittagong University of Engineering & Technology
Introduction to Programming

 To write and run C++ programs, you need to have a text editor and
a C++ compiler installed on your computer.
 A text editor is a software system that allows you to create and edit
text files on your computer.
 A compiler is a software system that translates programs into the
machine language (called binary code) that the computer’s
operating system can then run.
 That translation process is called compiling the program.
 A C++ compiler compiles C++ programs into machine language.
Introduction to Programming

 Windows Text Editors are –


 Word Pad
 Note Pad
 The compiler has to be installed in Computer in which both text
editing and compiling can be done.
 The common compilers are –
 Microsoft Visual C++
 Turbo C++
 Borland C++
 Dev C++ (Will be used in class)
 Quincy C++
Introduction to Programming

#include <iostream>
int main()
{
// prints “Boring Class!”
cout << “Boring Class!\n”;
return 0;
}
Introduction to Programming

 The first line of this source code is a preprocessor directive that


tells the C++ compiler where to find the definition of the cout
object that is used on the fourth line.
 The identifier iostream is the name of a file in the Standard C++
Library. Every C++ program that has standard input and output
must include this preprocessor directive.
 The sign # is required to indicate that the word include is a
preprocessor directive; the angle brackets <> are required to
indicate that the word iostream (which stands for input/output
stream) is the name of a Standard C++ Library file.
 The expression <iostream> is called a standard header.
Introduction to Programming

#include <iostream>
int main()
{
// prints “Boring Class!”
cout << “Boring Class!\n”;
return 0;
}
Introduction to Programming

 The second line is also required in every C++ program. It tells


where the program begins.
 The identifier main is the name of a function, called the main
function of the program.
 Every C++ program must have one and only one main() function.
 The required parentheses that follow the word main indicate that it
is a function.
 The keyword int is the name of a data type in C++. It stands for
integer. It is used here to indicate the return type for the main()
function.
Introduction to Programming

 The fourth line //prints “Boring Class!” includes the comment


prints “Boring Class!”.
 A comment in a program is a string of characters that the
preprocessor removes before the compiler compiles the programs.
 It is included to add explanations for human readers.
 In C++, any text that follows the double slash symbol //,up to the
end of the line, is a comment.
 You can also use C style comments, like this: /* prints "Boring
Class!" */.
Introduction to Programming

 The last two lines constitute the actual body of the program.
 A program body is a sequence of program statements enclosed in
braces { }. In this example there is only one statement cout <<
“Boring Class!\n”;
 It says to send the string “Boring Class!\n” to the standard output
stream object cout.
 The single symbol << represents the C++ output operator.
 When this statement executes, the characters enclosed in
quotation marks “ ”are sent to the standard output device which is
usually the computer screen.
Introduction to Programming

 The last two characters \n represent the newline character.


 When the output device encounters that character, it advances to
the beginning of the next line of text on the screen.
 Finally, note that every program statement must end with a
semicolon (;).
Introduction to Programming

 The symbol << is called the output operator in C++.


 It is also called the put operator or the stream insertion operator.
 It inserts values into the output stream that is named on its left.
 We usually use the cout output stream, which ordinarily refers to
the computer screen.
 So the statement
cout << 66;
would display the number 66 on the screen.
Introduction to Programming

 In C++, input is almost as simple as output.


 The input operator >> (also called the get operator or the
extraction operator) works like the output operator <<.
Introduction to Programming

 A variable is a symbol that represents a storage location in the


computer’s memory.
 The information that is stored in that location is called the value of
the variable.
 One common way for a variable to obtain a value is by an
assignment.
 This has the syntax
variable = expression ;
 First the expression is evaluated and then the resulting value is
assigned to the variable.
 The equals sign “=” is the assignment operator in C++.
Introduction to Programming

 A computer program is a sequence of elements called tokens.


These tokens include keywords such as int, identifiers such as
main, punctuation symbols such as {, and operators such as <<.
 When you compile your program, the compiler scans the text in
your source code, parsing it into tokens.
 If it finds something unexpected or doesn’t find something that was
expected, then it aborts the compilation and issues error
messages.
 For example, if you forget to append the semicolon that is required
at the end of each statement, then the message will report the
missing semicolon.
Introduction to Programming

 Some syntax errors such as a missing second quotation mark or a


missing closing brace may not be described explicitly; instead, the
compiler will indicate only that it found something wrong near that
location in your program.
int main ()
{ // prints "n = 44":
int n=44;
cout << "n="<<n<< endl;
}
The output is n=44
 This source code has 19 tokens: “int”, “main”, “(”, “)”, “{”, “int”, “n”,
“=”, “44”, “;”, “cout”, “<<”, “"n="”, “<<”, “n”, “<<”, “endl”, “;”,and “}”.
 Note that the compiler ignores the comment symbol // and the
text that follows it on the second line.
Introduction to Programming

Let us look at a simple code that would print the words


Hello World.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{ cout << "Hello World"; // prints Hello World
return 0;
}
Introduction to Programming

Let us look various parts of the above program:


The C++ language defines several headers, which contain
information that is either necessary or useful to your program. For
this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std
namespace. Namespaces are a relatively recent addition to C++.
The next line // main() is where program execution begins. is a
single-line comment available in C++. Single-line comments begin
with // and stop at the end of the line.
The line int main() is the main function where program execution
begins.
The next line cout << "This is my first C++ program."; causes
the message "This is my first C++ program" to be displayed on the
screen.
The next line return 0; terminates main( )function and causes it to
return the value 0 to the calling process.
Introduction to Programming

Semicolons & Blocks in C++:


In C++, the semicolon is a statement terminator. That is,
each individual statement must be ended with a
semicolon. It indicates the end of one logical entity.
For example, following are three different statements:
x = y;y = y+1;add(x, y); A block is a set of logically
connected statements that are surrounded by opening
and closing braces. For example:
{ cout << "Hello World"; // prints Hello World return 0;}
Introduction to Programming

Semicolons & Blocks in C++:


C++ does not recognize the end of the line as a
terminator. For this reason, it does not matter where on a
line you put a statement. For example:
x = y;y = y+1;add(x, y); is the same as
x = y; y = y+1; add(x, y);
Introduction to Programming

Have you any


Questions
????
CE 205
Computer Programming

Sanjoy Das
Assistant Professor

Department of Civil Engineering


Chittagong University of Engineering & Technology
Fundamental Types

 Standard C++ has 14 different fundamental data types:


 11 integral types and
 3 floating-point types.
 These are outlined in the diagram shown below..
Fundamental Types

C++ offer the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types:

Several of the basic types can be modified using one or more of these type
modifiers:
signed
unsigned
short
long
Fundamental Types

Fundamental Types

Integral Types Floating Point Types


Boolean Type Float -4 bytes
bool double -8 bytes
Enumeration Type long double - >=4 bytes
enum
Character Types-1 Byte
char
unsigned char
Signed char
Integer Types
(signed)short -2byte
(signed)int-4 bytes
(signed)long- >=4 bytes
(unsigned) short-2 byte
(unsigned) int-4 bytes
(unsigned) long- >=4 bytes
Fundamental Data Types
Fundamental Data Types

Following is the example, which will produce correct size of various data
types on your computer.

#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Fundamental Data Types

This example uses endl, which inserts a new-line character after every line and <<
operator is being used to pass multiple values out to the screen.

We are also using sizeof() function to get size of various data types.

When the above code is compiled and executed, it produces the following result which
can vary from machine to machine:

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
Fundamental Data Types

typedef Declarations:
You can create a new name for an existing type using typedef. Following
is the simple syntax to define a new type using typedef:

typedef type newname;

For example, the following tells the compiler that feet is another name for
int:

typedef int feet;

Now, the following declaration is perfectly legal and creates an integer


variable called distance:

feet distance;
Fundamental Data Types

Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant whose
type is the enumeration.
To create an enumeration requires the use of the keyword enum. The general form of
an enumeration type is:
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is comma
separated.
For example, the following code defines an enumeration of colors called colors and the
variable c of type color. Finally, c is assigned the value "blue“.
enum color { red, green, blue } c;
c = blue;
By default, the value of the first name is 0, the second name has the value 1, the third
has the value 2, and so on. But you can give a name a specific value by adding an
initializer. For example, in the following enumeration, green will have the value 5.
enum color { red, green=5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one
that precedes it.
Fundamental Types

The Boolean Type


 A boolean type is an integral type whose variables can
have only two values: false and true.
 These values are stored as the integers 0 and 1.
 The boolean type in Standard C++ is named bool.
Fundamental Types

The Boolean Type


int main ()
{
// prints the value of a boolean variable
bool flag = false;
cout << “flag =“<< flag << endl;
flag = true;
cout << “flag =“<< flag << endl;
}
Output:
Flag=0
Flag=1
Note that the value false is printed as the integer 0 and
the value true is printed as the integer 1.
Fundamental Types

The Character Types


 A character type is an integral type whose variables
represent characters like the letter 'A' or the digit '8'.
 Character literals are delimited by the apostrophe (').
 Like all integral type values, character values are stored
as integers.
Fundamental Types

The Character Types


int main ()
{
// prints the character and its internally stored
integer value
char c='A'; Output:
cout << "c="<<c<<", int (c)="<< int (c) << endl; c=A, int(c)=65
c=t, int(c)=116
c='t'; c= , int(c)=9
cout << "c="<<c<<", int (c)="<< int (c) << endl; c=!, int(c)=33
c='\t'; // the tab character
cout << "c="<<c<<", int (c)="<< int (c) << endl;
c='!';
cout << "c="<<c<<", int (c)="<< int (c) << endl;
}
Fundamental Types

The Character Types


 Since character values are used for input and output,
they appear in their character form instead of their
integral form: the character 'A' is printed as the letter
“A”, not as the integer 65 which is its internal
representation.
 The type cast operator int () is used here to reveal the
corresponding integral value.
 These are the characters’ ASCII codes. (See Appendix
A.), Schaum’s Outline of Theory and Problems of Programming with C++,
Second Edition
Fundamental Types

The Integer Types


 There are 6 integer types in Standard C++:
 These types actually have several names.
 For example, short is also named short int, and int is
also named signed int.
Fundamental Types

The Floating-point Types


 C++ supports three real number types: float, double,
and long double.
 On most systems, double uses twice as many bytes as
float.
 Typically, float uses 4 bytes, double uses 8 bytes, and
long double uses 8, 10, 12, or 16 bytes.
Fundamental Types

The Floating-point Types


int main ()
{
// tests the floating-point operators +, - , * and /
double x = 44.0; Output:
double y = 8.0; x= 44 and y=8
cout << "x = "<<x<<" and y = "<<y<< endl; x+y=52
x-y=36
cout << "x+y = "<< x+y << endl; // 44.0+8.0 = 52.0
x*y=352
cout << "x-y = "<< x-y << endl; // 44.0-8.0 = 36.0 x/y=5.5
cout << "x*y = "<< x*y << endl; // 44.0*8.0 = 352.0
cout << "x/y = "<< x/y << endl; // 44.0/8.0 = 5.5
}
Fundamental Types

The Floating-point Types


int main ()
{
// tests the floating-point operators +, - , * and /
Int x = 44.0; Output:
int y = 8.0; x= 44 and y=8
cout << "x = "<<x<<" and y = "<<y<< endl; x+y=52
x-y=36
cout << "x+y = "<< x+y << endl; // 44.0+8.0 = 52.0
x*y=352
cout << "x-y = "<< x-y << endl; // 44.0-8.0 = 36.0 x/y=5
cout << "x*y = "<< x*y << endl; // 44.0*8.0 = 352.0
cout << "x/y = "<< x/y << endl; // 44.0/8.0 = 5.5
}
Fundamental Types

 Computers were invented to perform numerical


calculations.
 Like most programming languages, C++ performs its
numerical calculations by means of the five arithmetic
operators +, –, *, / and %.
+ Addition
– Subtraction
∗ Multiplication
/ Division
% Remainder
Fundamental Types

int main ()
{
// tests the floating-point operators +,-,*,/ and %:
Output:
int a = 44.0;
a= 44 and b=8
int b = 8.0; a+b=52
cout << "a = "<<a<<" and b = "<<b<< endl; a-b=36
cout << "a+b = "<< a+b << endl; // 44.0+8.0 = 52.0 a*b=352
cout << "a-b = "<< a-b << endl; // 44.0-8.0 = 36.0 a/b=5
cout << "a*b = "<< a*b << endl; // 44.0*8.0 = 352.0 a%b=4
cout << "a/b = "<< a/b << endl; // 44.0/8.0 = 5.5
cout << "a%b = "<< a%b << endl; // 44.0%8.0 = 4.0
}
Fundamental Types

 The values of integral objects can be incremented and


decremented with the + + and − − operators,
respectively.
 Each of these operators has two versions: a preversion
and a post version.
 The pre version performs the operation (either adding 1 or
subtracting 1) on the object beforethe resulting value is
used in its surrounding context.
 The postversion performs the operation after the object’s
current value has been used.
Fundamental Types

int main ()
{
// shows the difference between m++ and ++m
int m, n;
m = 20;
n= ++m; // the pre-increment operator is applied to m
cout << " m= "<<m<<", n= "<<n<< endl;
m = 20;
n= m++; // the post-increment operator is applied to m
cout << " m= "<<m<<", n= "<<n<< endl;
}

Output:
m=21, n=21
m=21, n=20
Fundamental Types

 The line n = ++m; // the pre-increment operator is applied


to m increments m to 21 and then assigns that value to n.
 So both variables have the same value 21 when the next
output line executes.
 The line n = m++; // the post-increment operator is applied
to m increments m to 21 only after it has assigned the
value of m to n.
 So n has the value 20 when the next out-put line
executes.
Fundamental Types

 The standard assignment operator in C++ is the equals


sign =.
 In addition to this operator, C++ also includes the
following composite assignment operators: +=, −=, ∗
=,/= and % =.
 When applied to a variable on the left, each applies the
indicated arithmetic operation to it using the value of the
expression on the right.
Fundamental Types

int main ()
{
// tests arithmetic assignment operators Output:
int n=45; n=45
cout << "n = "<<n<< endl; After n+=5, n=50
n+=5; // adds 5 to n After n-=8, n=42
cout << "After n+ = 5, n = "<<n<< endl;
n-=8; // subtracts 8 from n After n*=2, n=84
cout << "After n- = 8, n = "<<n<< endl;
n*=2; // multiplies n by 2 After n/=4, n=21
cout << "After n* = 2, n = "<<n<< endl;
n/=4; // divides n by 4 After n%=5, n=1
cout << "After n/ = 4, n = "<<n<< endl;
n%=5; // reduces n to the remainder from dividing by 5
cout << "After n% = 5, n = "<<n<< endl;
}
Fundamental Types

n+=5 n=n+5
n-=8 n=n-8
n*=2 n=n*2
n/=4 n=n/4
n%=5 n=n%5
Fundamental Types

 On most computers the long int type allows


4,294,967,296 different values.
 That's a lot of values, but it’s still finite.
 Computers are finite, so the range of any type must also
be finite.
 But in mathematics there are infinitely many integers.
 Consequently, computers are manifestly prone to error
when their numeric values become too large.
 That kind of error is called numeric overflow.
Fundamental Types

Integer Overflow
This program repeatedly multiplies n by
1000 until it overflows.
int main() Output:
{ n=1000
// prints n until it overflows: n=1000000
n=1000000000
int n=1000;
n=727379968
cout << "n="<<n<< endl;
n *= 1000; // multiplies n by 1000
cout << "n="<<n<< endl;
n *= 1000; // multiplies n by 1000
cout << "n="<<n<< endl;
n *= 1000; // multiplies n by 1000
cout << "n="<<n<< endl;
} This shows that the computer that ran this program
cannot multiply 1,000,000,000 by 1000 correctly.
Fundamental Types

Floating-point Overflow
This program repeatedly squares x until it
overflows.
int main ()
{
Output:
// prints x until it overflows:
x=1000
float x=1000.0;
x=1e+06
cout << "x="<<x<< endl;
x=1e+12
x *= x; // multiplies x by itself; i.e.,it squares x
x=1e+24
cout << "x="<<x<< endl;
x=infinity
x *= x; // multiplies x by itself; i.e.,it squares x
cout << "x="<<x<< endl;
x *= x; // multiplies x by itself; i.e.,it squares x
cout << "x="<<x<< endl;
x *= x; // multiplies x by itself; i.e.,it squares x
cout << "x="<<x<< endl;
}
This shows that, starting with x = 1000, this computer cannot square x correctly more than
three times. The last output is the special symbol inf which stands for “infinity.”
Fundamental Types

 Round-off error is another kind of error that often occurs


when computers do arithmetic on rational numbers.
 For example, the number 1/3 might be stored as
0.333333, which is not exactly equal to 1/3.
 The difference is called round-off error.
 In some cases, these errors can cause serious problems.
Fundamental Types

This program does some simple arithmetic to illustrate round off error:
int main ()
{
// illustrates round-off error
double x = 1000/3.0; cout << "x="<<x<< endl; // x = 1000/3
double y=x- 333.0; cout << "y="<<y<< endl; //y=1/3
double z = 3*y - 1.0; cout << "z="<<z<< endl; // z = 3(1/3) - 1
if (z == 0) cout << "z == 0.\n";
else cout << "z does not equal 0.\n"; // z != 0
}

Output:
x=333.333
y=0.333333
z=-5.68434e-14
z does not equal 0.
Fundamental Types

 In exact arithmetic, the variables would have the values


x = 333 1/3, y =1/3, and z = 0.
 But 1/3 cannot be represented exactly as a floating-point value.
 The inaccuracy is reflected in the residue value for z.
 The previous example illustrates an inherent problem with using
floating-point types within conditional tests of equality.
 The test (z == 0) will fail even if z is very nearly zero, which is likely
to happen when z should algebraically be zero.
 So it is better to avoid tests for equality with floating-point
types.
Fundamental Types

 The scope of an identifier is that part of the program


where it can be used.
 For example, variables cannot be used before they are
declared, so their scopes begin where they are declared.
 This is illustrated by the next example.
Fundamental Types

int main ()
{
// illustrates the scope of variables:
x = 11; // ERROR: this is not in the scope of x
int x;
{ x = 22; // OK: this is in the scope of x
y = 33; // ERROR: this is not in the scope of y
int y;
x = 44; // OK: this is in the scope of x
y = 55; // OK: this is in the scope of y
}
x = 66; // OK: this is in the scope of x
y = 77; // ERROR: this is not in the scope of y
}
The scope of x extends from the point where it is declared to the end
of main(). The scope of y extends from the point where it is declared
to the end of the internal block within which it is declared.
C++ Identifiers:
A C++ identifier is a name used to identify a
variable, function, class, module, or any other
user-defined item.
An identifier starts with a letter A to Z or a to z
or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such
as @, $, and % within identifiers.
C++ is a case-sensitive programming language.
Thus, Manpower and manpower are two
different identifiers in C++.
C++ Identifiers:
The rules of naming identifiers in C++ :
C++ is case-sensitive so that Uppercase Letters
and Lower Case letters are different
The name of identifier cannot begin with a
digit. However, Underscore can be used as first
character while declaring the identifier.
Only alphabetic characters, digits and
underscore (_) are permitted in C++ language for
declaring identifier.
Other special characters are not allowed for
naming a variable / identifier
Keywords cannot be used as Identifier.
C++ Keyword:
In C++, keywords are reserved identifiers which cannot be used as names for
the variables in a program. The following list shows the reserved words in C++.
These reserved words may not be used as constant or variable or any other
identifier names.
C++ Keyword:
Keywords cannot be used for the -
Declaring Variable Name
Declaring Class Name
Declaring Function Name
Declaring Object Name
Operators in C++
An operator is a symbol that tells the compiler to
perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and
provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
C++ Operators
An operator is a symbol which tells compiler to take an
action on operands and yield a value. The Value on which
operator operates is called as operands. C++ supports
wide verity of operators. Supported operators are listed
below –
C++ Operators
Arithmetic Operators:
There are following arithmetic operators supported by C++ language:

Assume variable A holds 10 and variable B holds 20, then:


C++ Operators
Relational Operators:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
C++ Operators
Logical Operators:
There are following logical operators supported by C++ language
Assume variable A holds 1 and variable B holds 0, then:
C++ Operators
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:
C++ Operators
Bitwise Operators:
Assume if A = 60; and B = 13; now in binary format they
will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are
listed in the following table. Assume variable A holds 60
and variable B holds 13, then:
C++ Operators
Bitwise Operators:
C++ Operators
Assignment Operators:
There are following assignment operators supported by C++ language:
C++ Operators
Operators Precedence in C++:
Operator precedence determines the grouping of terms
in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has
higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20
because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at
the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence
operators will be evaluated first.
C++ Operators
C++ Constants :
Selection

CE 205: Computer Programming and


Numerical Analysis in CE
Topics: Selection
• if statement
• if….else statement
• keywords
• Comparison operator
• Statement blocks
• Compound condition
• Short circuiting
• Boolean expression
• Nested selection statement
• else if construct
• switch statement
• The conditional expression operator
Selection
• sequential execution: each statement in the
program executes once, and they are executed in the same
order that they are listed.

• Selection statements allow to bypass certain statements


depending on condition.
For example: if A>B, do activity 1, otherwise (A<B), do
activity 2. Activity 2 will not be executed if the first
condition (A>B) is true.

• This chapter shows how to use selection statements for


more flexible programs.
if statement

• The if statement allows conditional execution. Its


syntax is
if (condition) statement;
where condition is an integral expression and
statement is any executable statement.

• The statement will be executed only if the value


of the integral expression is nonzero. Notice the
required parentheses around the condition.
Selection: if statement

EXAMPLE 3.1: Testing for Divisibility


This program tests if one positive integer is not
divisible by another:
int main()
{ int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (n%d) cout << n << " is not divisible by " << d <<
endl;
}
Selection: if statement
On the first run, we enter 66 and 7:
The value 66%7 is computed to be 3. Since that integral value
is not zero, the expression is interpreted as a true condition
and consequently the divisibility message is printed.

On the second run, we enter 56 and 7:


The value 56%7 is computed to be 0, which is interpreted to mean
“false,” so the divisibility message is not printed.

In C++, whenever an integral expression is used as a condition, the


value 0 means “false” and all other values mean “true.”
The program in Example 1 is inadequate because it provides no
affirmative information when n is divisible by d. That fault can be
remedied with an if..else statement.
If….else statement
• The if..else statement causes one of two
alternative statements to execute depending
upon whether the condition is true. Its syntax is
if (condition) statement1;
else statement2;
• where condition is an integral expression and
statement1 and statement2 are executable
statements.
• If the value of the condition is nonzero then
statement1 will execute; otherwise statement2
will execute.
Selection: if….else statement

EXAMPLE 3.2 Testing for Divisibility Again


This program is the same as the program in Example 3.1
except that the if statement has been replaced
by an if..else statement:
int main()
{ int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (n%d) cout << n << " is not divisible by " << d << endl;
else cout << n << " is divisible by " << d << endl;
}
Selection: if….else statement

Now when we enter 56 and 7, we get an affirmative


response:

Since 56%7 is zero, the expression is interpreted as


being a false condition and consequently the
statement after the else is executed.

• Note that the if..else is only one statement, even


though it requires two semicolons.
KEYWORDS
A keyword in a programming language is a word that is
already defined and is reserved for a unique purpose in
programs written in that language. Standard C++ now
has 74 keywords:
And delete do double
bool break case
char class const
continue default
else enum export
float for
goto if int long………………………
Selection: Keywords

Keywords like if and else are found in nearly every programming


language. Other keywords such as dynamic_cast are unique to
C++. The 74 keywords of C++ include all 32 of the keywords of
the C language.
There are two kinds of keywords: reserved words and standard
identifiers.
A reserved word is a keyword that serves as a structure marker,
used to define the syntax of the language. The keywords if and
else are reserved words.
A standard identifier is a keyword that names a specific element of
the language. The keywords bool and int are standard identifiers
because they are names of standard types in C++.
See Appendix B for more information on the C++ keywords.
COMPARISON OPERATORS
• x < y // x is less than y
• x > y // x is greater than y
• x <= y // x is less than or equal to y
• x >= y // x is greater than or equal to y
• x == y // x is equal to y
• x != y // x is not equal to y

These can be used to compare the values of expressions of any


ordinal type. The resulting integral expression is interpreted as a
condition that is either false or true according to whether the
value of the expression is zero. For example, the expression 7*8 <
6*9 evaluates to zero,which means that the condition is false.
EXAMPLE 3.3 The Minimum of Two Integers
This program prints the minimum of the two integers entered:
int main()
{ int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
if (m < n) cout << m << " is the minimum." << endl;
else cout << n << " is the minimum." << endl;
}
Output:
Enter two integers: 77 55
55 is the minimum.
Note that in C++ the single equal sign “=” is the
assignment operator, and the double equal sign
“==” is the equality operator:

x = 33; // assigns the value 33 to x

x == 33; // evaluates to 0 (for false) unless 33 is the


value of x

This distinction is critically important.


EXAMPLE 3.4 A Common Programming Error
This program is erroneous:
int main()
{ int n;
cout << "Enter an integer: ";
cin >> n;
if (n = 22) cout << n << " = 22" << endl; // LOGICAL
ERROR!
else cout << n << " != 22" << endl;
}

Output:
Enter an integer: 77
22 = 22
The expression n = 22 assigns the value 22 to n,
changing it from its previous value of 77. But the
expression n = 22 itself is an integral expression that
evaluates to 22 after it executes. Thus the condition (n
= 22) is interpreted as being true, because only 0 yields
false, so the statement before the else executes. The
line should have been written as

if (n == 22) cout << n << " = 22" << endl; // CORRECT

The error illustrated in Example 3.4 is called a logical


error. This is the worst kind of error. Compile-time
errors (e.g., omitting a semicolon) are caught by the
compiler. Run-time errors (e.g., dividing by zero) are
caught by the operating system. But no such help exists
for catching logical errors.
EXAMPLE 3.5 The Minimum of Three Integers
This program is similar to the one in Example 3.3 except that it applies
to three integers:
int main()
{ int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
int min=n1; // now min <= n1
if (n2 < min) min = n2; // now min <= n1 and min <= n2
if (n3 < min) min = n3; // now min <= n1,min <= n2,and min <= n3
cout << "Their minimum is " << min << endl;
}

Output:
Enter two integers: 77 33 55
Their minimum is 33
The three comments track the progress of the program: min is
initialized to equal n1, so it is the minimum of the set {n1}.
After the first if statement executes, min is equal to either n1
or n2, whichever is smaller, so it is the minimum of the set
{n1, n2}. The last if statement changes the value of min to n3
only if n3 is less than the current value of min which is the
minimum of the set {n1, n2}. So in either case, min becomes
the minimum of the set {n1, n2, n3}.
Statement Blocks
A statement block is a sequence of statements
enclosed by braces{ }, like this:
{ int temp=x; x = y; y = temp; }
In C++ programs, a statement block can be used
anywhere that a single statement can be used.
EXAMPLE 3.6 A Statement Block within an if Statement
This program inputs two integers and then outputs them in
increasing order:
int main()
{ int x,y;
cout << "Enter two integers: ";
cin >> x >> y;
if (x > y) { int temp=x; x = y; y = temp; } // swap x and y
cout << x << " <= " << y << endl;
}
Output: Enter two integers: 66 44
44 <= 66
The three statements within the statement block sort the values
of x and y into increasing order by
swapping them if they are out of order. Such an interchange
requires three separate steps along with the temporary
storage location named temp here. The program either should
execute all three statements or it should execute none of
them. That alternative is accomplished by combining the
three statements into the statement block.

Note that the variable temp is declared inside the block. That
makes it local to the block; i.e., it only exists during the
execution of the block. If the condition is false (i.e., x ≤ y), then
temp will never exist.
This illustrates the recommended practice of
localizing objects so that they are created only
when needed. Note that a C++ program itself is a
statement block preceded by int main().

The scope of a variable is that part of a program


where the variable can be used. It extends from
the point where the variable is declared to the
end of the block which that declaration controls.
So a block can be used to limit the scope of a
variable, thereby allowing the same name to be
used for different variables in different parts of a
program.
EXAMPLE 3.7 Using Blocks to Limit Scope
This program uses the same name n for three different
variables:
int main()
{ int n=44;
cout << "n = " << n << endl;
{ int n; // scope extends over 4 lines
cout << "Enter an integer: ";
cin >> n;
cout << "n = " << n << endl;
}
{ cout << "n = " << n << endl; // the n that was
declared first
}
{ int n; // scope extends over 2 lines
cout << "n = " << n << endl;
}
cout << "n = " << n << endl; // the n that was
declared first
}
Output:
n = 44
Enter an integer: 77
n = 77
n = 44
n = 4251897
n = 44
This program has three internal blocks. The first block declares a new n which
exists only within that block and overrides the previous variable n. So the
original n retains its value of 44 when this n is given the input value 77.
The second block does not redeclare n, so the scope of the original n
includes this block. Thus the third output is the original value 44. The third
block is like the first block: it declares a new n which overrides the original
n. But this third block does not initialize its local n, so the fourth output is
a garbage value (4251897). Finally, since the scope of each redeclared n
extends only to the block where it is declared, the last line of the program
is in the scope of the original n, so it prints 44.
COMPOUND CONDITIONS
Conditions such as n % d and x >= y can be
combined to form compound conditions. This is
done using the logical operators && (and), ||
(or), and ! (not).
They are defined by p && q evaluates to true if and
only if both p and q evaluate to true, p || q
evaluates to false if and only if both p and q
evaluate to false.
!p evaluates to true if and only if p evaluates to
false
For example, (n % d || x >= y) will be false if and
only if n % d is zero and x is less than y. The
definitions of the three logical operators are
usually given by the truth tables below.

These show, for example, that if p is true and q is


false, then the expression p && q will be false and
the expression p || q will be true.
EXAMPLE 3.8 Using Compound Conditions
This program has the same effect as the one in Example 3.5 on page
39. This version uses compound
conditions to find the minimum of three integers:

int main()
{ int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 <= n2 && n1 <= n3) cout << "Their minimum is " << n1 <<endl;
if (n2 <= n1 && n2 <= n3) cout << "Their minimum is " << n2 <<endl;
if (n3 <= n1 && n3 <= n2) cout << "Their minimum is " << n3 <<endl;
}
Output:
Enter two integers: 77 33 55
Their minimum is 33

EXAMPLE 3.9 User-Friendly Input


This program allows the user to input either a “Y” or a “y”
for “yes”:
int main()
{ char ans;
cout << "Are you enrolled (y/n): ";
cin >> ans;
if (ans == 'Y' || ans == 'y') cout << "You are enrolled.\n";
else cout << "You are not enrolled.\n";
}
Output:
Are you enrolled (y|n): N
You are not enrolled.

It prompts the user for an answer, suggesting a


response of either y or n. But then it accepts
any character and concludes that the user
meant “no” unless either a Y or a y is input.
SHORT-CIRCUITING
Compound conditions that use && and || will
not even evaluate the second operand of the
condition unless necessary. This is called
short-circuiting. As the truth tables show, the
condition p && q will be false if p is false. In
that case there is no need to evaluate q.
Similarly if p is true then there is no need to
evaluate q to determine that p || q is true. In
both cases the value of the condition is known
as soon as the first operand is evaluated.
EXAMPLE 3.10 Short-Circuiting
This program tests integer divisibility:
int main()
{ int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (d != 0 && n%d == 0) cout << d << " divides " << n
<< endl;
else cout << d << " does not divide " << n << endl;
}
In this run,d is positive and n%d is zero, so the
compound condition is true:
Enter two positive integers: 300 6
6 divides 300
In this run, d is positive but n%d is not zero, so the
compound condition is false:
Enter two positive integers: 300 7
7 does not divide 300
In this run,d is zero, so the compound condition is
immediately determined to be false without
evaluating the second expression “n%d == 0”:
Enter two positive integers: 300 0
0 does not divide 300
This short-circuiting prevents the program from
crashing because when d is zero the expression
n%d cannot be evaluated.
BOOLEAN EXPRESSIONS
A boolean expression is a condition that is either true or false.
In the previous example the expressions d > 0, n%d == 0,
and (d > 0 && n%d == 0) are boolean expressions. As we
have seen, boolean expressions evaluate to integer values.
The value 0 means “false” and every nonzero value means
“true.”
Since all nonzero integer values are interpreted as meaning
“true,” boolean expressions are often disguised. For
example, the statement
if (n) cout << "n is not zero";
will print n is not zero precisely when n is not zero because
that is when the boolean expression (n) is interpreted as
“true”.
Here is a more realistic example:
if (n%d) cout << "n is not a multiple of d";
The output statement will execute precisely when n%d is not zero, and that
happens precisely when d does not divide n evenly, because n%d is the
remainder from the integer division. The fact that boolean expressions
have integer values can lead to some surprising anomalies in C++.
EXAMPLE 3.11 Another Logical Error
This program is erroneous:
int main()
{ int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2 >= n3) cout << "max = 0"; // LOGICAL ERROR!
}
Output:
Enter an integer: 0 0 1
max = 0

The source of this error is the fact that boolean expressions have numeric values.
Since the expression (n1 >= n2 >= n3) is evaluated from left to right, the first part n1
>= n2 evaluates to “true” since 0 >= 0. But “true” is stored as the numeric value 1.
That value is then compared to the value of n3 which is also 1, so the complete
expression evaluates to “true” even though it is really false! (0 is not the maximum of
0, 0, and 1.)
The problem here is that the erroneous line is syntactically correct, so the compiler
cannot catch the error. Nor can the operating system. This is another logical error,
comparable to that in the program in Example 3.4.
The moral from Example 11 is to remember that boolean expressions have numeric
values, so compound conditions can be tricky.
NESTED SELECTION STATEMENTS
Like compound statements, selection statements can be used wherever any
other statement can be used. So a selection statement can be used within
another selection statement. This is called nesting statements.
EXAMPLE 3.12 Nesting Selection Statements
This program has the same effect as the one in Example 10:
int main()
{ int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (d != 0)
if (n%d == 0) cout << d << " divides " << n << endl;
else cout << d << " does not divide " << n << endl;
else cout << d << " does not divide " << n << endl;
}
The second if..else statement is nested within the if clause of the first
if..else statement. So the second if..else statement will execute only
when d is not zero.

Note that the " does not divide " statement has to be used twice here.
The first one, nested within the if clause of the first if..else statement,
executes when d is not zero and n%d is zero.

The second one executes when d is zero.


When if..else statements are nested, the compiler uses the following
rule to parse the compound statement:
Match each else with the last unmatched if.
EXAMPLE 3.13 Using Nested Selection Statements
This program has the same effect as those in Example 5 and Example 8 . This
version uses nested if..else statements to find the minimum of three integers:
int main()
{ int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 < n2)
if (n1 < n3) cout << "Their minimum is " << n1 << endl;
else cout << "Their minimum is " << n3 << endl;
else // n1 >= n2
if (n2 < n3) cout << "Their minimum is " << n2 << endl;
else cout << "Their minimum is " << n3 << endl;
}
Output:
Enter three integers: 77 33 55
Their minimum is 33

In this run, the first condition (n1 < n2) is false, and the third
condition (n2 < n3) is true, so it reports that n2 is the
minimum.

This program is more efficient than the one in Example 8 , because on


any run
it will evaluate only two simple conditions instead of three compound
conditions. Nevertheless, it should be considered inferior because its
logic is
more complicated. In the trade-off between efficiency and simplicity,
it is
usually best to choose simplicity.
THE else if CONSTRUCT
Nested if..else statements are often used to test
a sequence of parallel alternatives, where
only the else clauses contain further nesting. In
that case, the resulting compound statement is
usually formatted by lining up the else if phrases
to emphasize the parallel nature of the logic.
THE switch STATEMENT
The switch statement can be used instead of the else if construct
to implement a sequence of parallel alternatives. Its syntax is
switch (expression)
{ case constant1: statementList1;
case constant2: statementList2;
case constant3: statementList3;
:
:
case constantN: statementListN;
default: statementList0;
}
This evaluates the expression and then looks for its value \
among the case constants. If the value is found among the
constants listed, then the statements in the corresponding
Statement List are executed. Otherwise if there is a default
(which is optional), then the program branches to its
Statement List. The expression must evaluate to an
integral type and the constants must be integral
constants.
EXAMPLE 17 Using a switch Statement to Select a Range
of Scores.
This program has the same effect as the one in Example
3.16:
int main()
{ int score;
cout << "Enter your test score: "; cin >> score;
switch (score/10)
{ case 10:
case 9: cout << "Your grade is an A." << endl; break;
case 8: cout << "Your grade is a B." << endl; break;
case 7: cout << "Your grade is a C." << endl; break;
case 6: cout << "Your grade is a D." << endl; break;
case 6: cout << "Your grade is a D." << endl; break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0: cout << "Your grade is an F." << endl; break;
default: cout << "Error: score is out of range.\n";
}
cout << "Goodbye." << endl;
}
Output:
Enter your test score: 83
Your grade is a B.
Goodbye.

First the program divides the score by 10 to reduce the range of values
to 0–10. So in the test run, the score 83 reduces to the value 8, the
program execution branches to case 8, and prints the output shown.

Then the break statement causes the program execution to branch to


the first statement after the switch block. That statement prints
“Goodbye.”.
Note that scores in the ranges 101 to 109 and -9 to -1 produce
incorrect results.
It is normal to put a break statement at the end of
each case clause in a switch statement. Without it,
the program execution will not branch directly out
of the switch block after it finishes executing its
case statement sequence. Instead, it will continue
within the switch block, executing the statements in
the next case sequence. This (usually) unintended
consequence is called a fall through.
THE CONDITIONAL EXPRESSION
OPERATOR
C++ provides a special operator that often can be
used in place of the if...else statement. It is called
the conditional expression operator. It uses the ?
and the : symbols in this syntax:
condition ? expression1 : expression2
It is a ternary operator; i.e., it combines three
operands to produce a value. That resulting value
is either the value of expression1 or the value of
expression2, depending upon the boolean value of
the condition.
For example, the assignment
min = ( x<y ? x : y );
would assign the minimum of x and y to min,
because if the condition x<y is true, the expression
( x<y ? x : y ) evaluates to x; otherwise it evaluates
to y.
Conditional expression statements should be used
sparingly: only when the condition and both
expressions are very simple.
EXAMPLE 3.19 Finding the Minimum Again
This program has the same effect as the program in
Example 3.3 :

int main()
{ int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m<n ? m : n ) << " is the minimum." << endl;
}

The conditional expression ( m<n ? m : n ) evaluates to m if


m<n, and
to n otherwise.
The End!!!
Department of Civil Engineering
Chittagong University of Engineering & Technology

CE 205
Computer Programming
(Lecture-8)

Sanjoy Das
Assistant Professor
Department of Civil Engineering
 Often we need to repeat the execution of a
portion of the code for a given number of
times or until a specific condition is met
 Iteration is the repetition of a statement or
block of statements in a program
 Iteration statements are also called loops
because of their cyclic nature
There are three types of loop in C++

for loop

while loop

do ...... while loop


for loop
The Structure of the for loop

{…………….
for (initialization; condition; update)
{Statement;}
Statement;
}
This expression is used to determine whether
It is typically used to declare/initialize the loop should continue iteration. It is
control variables for the loop. This evaluated immediately after the initialization.
expression is evaluated first before If it is true, the loop continues. If it is false,
any iteration occurs. execution continues with the statement after
the loop.

{…………….
for (initialization; condition; update)
{Statement}
Statement The semicolons This expression is evaluated at the
} are mandatory end of each loop iteration. It is
typically used to modify the values
of variables initialized in the first
expression
The sequence of the events of for loop

The initialization expression is evaluated

The condition is evaluated

If condition If condition
is true is false

The Statement is Loop is terminated


executed

The Update expression


is evaluated
#include <iostream>
Using namespace std;
int main ()

{
int sum=0;
for (int i=1; i<5; i++)
{
cout<<"i="<<i;
sum+=i;
cout<<"\tsum="<<sum<<endl;
}
}
i =1 sum = 1
i=2 sum = 3
i=3 sum = 6
i=4 sum = 10
int i = 1

Evaluate i++ i.e.


Check if i<5 yes i=1 sum=0+1=1
i=i+1=1+1=2

Evaluate i++ i.e.


Check if i<5 yes i=2 sum=1+2=3
i=i+1=2+1=3

Evaluate i++ i.e.


Check if i<5 yes i=3 sum=3+3=6
i=i+1=3+1=4

Evaluate i++ i.e.


Check if i<5 yes i=4 sum=6+4=10
i=i+1=4+1=5

Check if i<5 no Loop is terminated statement


while loop
The Structure of the while loop

{…………….
while (condition)
{Statement;}
Statement;
}
Here the condition is evaluated at the
beginning of each loop iteration. If it is
true, the loop continues and if it is
false execution continues with the
statement after the loop.

{…………….
while (condition)
{Statement;}
Statement;
}
#include <iostream>
Using namespace std;
int main ()

{
int sum=0;
int i =1;
while (i<5)
{
cout<<"i="<<i;
sum+=i;
i++;
cout<<"\tsum="<<sum<<endl;
}
}
i =1 sum = 1
i=2 sum = 3
i=3 sum = 6
i=4 sum = 10
Initial conditions before loop: sum=0, i=1

Evaluate i++ i.e.


Check if i<5 yes i=1 sum=0+1=1
i=i+1=1+1=2

Evaluate i++ i.e.


Check if i<5 yes i=2 sum=1+2=3
i=i+1=2+1=3

Evaluate i++ i.e.


Check if i<5 yes i=3 sum=3+3=6
i=i+1=3+1=4

Evaluate i++ i.e.


Check if i<5 yes i=4 sum=6+4=10
i=i+1=4+1=5

Check if i<5 no Loop is terminated statement


do ...... while loop
The Structure of the do…….while loop

{
do
{Statement;}
while (condition)
Statement;
}
Here the condition is evaluated at the
end of each loop iteration. If it is true,
the loop continues and if it is false
execution continues with the
statement after the loop. The loop
statements are always executed at
least once.

{
do
{Statement;}
while (condition)
Statement;
}
#include<iostream>
Using namespace std;
int main()
{
int sum=0;
int i=1;
do {
cout<<"i="<<i;
sum+=i;
i++;
cout<<"\tsum="<<sum<<endl;
}
while(i<5);
}
i =1 sum = 1
i=2 sum = 3
i=3 sum = 6
i=4 sum = 10
Initial conditions before loop: sum=0, i=1

Evaluate i++ i.e.


i=1 sum=0+1=1 Check if i<5 yes
i=i+1=1+1=2

Evaluate i++ i.e. Check if i<5 yes


i=2 sum=1+2=3
i=i+1=2+1=3

Evaluate i++ i.e. Check if i<5 yes


i=3 sum=3+3=6
i=i+1=3+1=4

Evaluate i++ i.e. Check if i<5 no


i=4 sum=6+4=10
i=i+1=4+1=5

Loop is terminated statement


Department of Civil Engineering
Chittagong University of Engineering & Technology

CE 205
Computer Programming & Numerical Methods in CE

Sanjoy Das
Assistant Professor
Department of Civil Engineering
Switch
& Break
 The Switch statement can be used
instead of the else if construct

 Switch statement provides a means


to select from a fixed set of options
depending on the value of an integer
expression
switch (expression)
{
case value 1: statement block 1; break;
case value 2: statement block 1; break;
case value 3: statement block 1; break;

case value N: statement block N; break;


default: statement block P;
}
Statement block Q ;
#include<iostream> Example with if & else if
Using namespace std;
int main()
{
int score;
cout<<"Enter your test score: ";
cin>>score;

if(score>100) cout<<"ERROR: that score is out of RANGE"<<endl;


else if (score>=90) cout<<"Your GRADE is A+"<<endl;
else if (score>=80) cout<<"Your GRADE is A"<<endl;
else if (score>=70) cout<<"Your GRADE is B+"<<endl;
else if (score>=60) cout<<"Your GRADE is B"<<endl;
else if (score>=50) cout<<"Your GRADE is C"<<endl;
else if (score>=40) cout<<"Your GRADE is D"<<endl;
else if (score>=0) cout<<"Your GRADE is F"<<endl;
else cout<<"ERROR: that score is not VALID"<<endl;
}
Output:
Enter your test score:
76
Your grade is B+
#include<iostream>
Using namespace std; Example with switch &
int main()
{ break
int score;
cout<<"Enter your test score: ";
cin>>score;
switch (score/10)
{
case 10:
case 9: cout<<"Your GRADE is A+"<<endl; break;
case 8: cout<<"Your GRADE is A"<<endl; break;
case 7: cout<<"Your GRADE is B+"<<endl; break;
case 6: cout<<"Your GRADE is B"<<endl; break;
case 5: cout<<"Your GRADE is C"<<endl; break;
case 4: cout<<"Your GRADE is D"<<endl; break;
case 3:
case 2:
case 1:
case 0: cout<<"Your GRADE is F"<<endl; break;
default: cout<<"ERROR: that score is out of RANGE"<<endl;
}
}
Output:
Enter your test score: 76
Your grade is B+
#include<iostream>
Using namespace std; Example with if & else if
int main()
{
int score;
cout<<"Enter your test score: ";
cin>>score;

if(score>100) cout<<"ERROR: that score is out of RANGE"<<endl;


else if (score>=80) cout<<"Your GRADE is A+"<<endl;
else if (score>=75) cout<<"Your GRADE is A"<<endl;
else if (score>=70) cout<<"Your GRADE is A-"<<endl;
else if (score>=65) cout<<"Your GRADE is B+"<<endl;
else if (score>=60) cout<<"Your GRADE is B"<<endl;
else if (score>=55) cout<<"Your GRADE is B-"<<endl;
else if (score>=50) cout<<"Your GRADE is C+"<<endl;
else if (score>=45) cout<<"Your GRADE is C"<<endl;
else if (score>=40) cout<<"Your GRADE is D"<<endl;
else if (score>=0) cout<<"Your GRADE is F"<<endl;
else cout<<"ERROR: that score is not VALID"<<endl;
}
#include<iostream>
Using namespace std;
int main()
Example with switch &
{
int score;
break (Corrected)
cout<<"Enter your test score: ";
cin>>score;
if(score>100||score<0) cout<<"that score is not VALID"<<endl;
else
{
switch(score/10)
{
case 10:
case 9: cout<<"Your GRADE is A+"<<endl; break;
case 8: cout<<"Your GRADE is A"<<endl; break;
case 7: cout<<"Your GRADE is B+"<<endl; break;
case 6: cout<<"Your GRADE is B"<<endl; break;
case 5: cout<<"Your GRADE is C"<<endl; break;
case 4: cout<<"Your GRADE is D"<<endl; break;
case 3:
case 2:
case 1:
case 0: cout<<"Your GRADE is F"<<endl; break;
default: cout<<"ERROR: that score is out of RANGE"<<endl;
}
}
}
#include<iostream>
Example with switch &
Using namespace std;
int main()
break (shorted)
{
int score;
cout<<"Enter your test score: ";
cin>>score;
if(score>100||score<0) cout<<"that score is not VALID"<<endl;
else
{
switch(score/10)
{
case 10:
case 9: cout<<"Your GRADE is A+"<<endl; break;
case 8: cout<<"Your GRADE is A"<<endl; break;
case 7: cout<<"Your GRADE is B+"<<endl; break;
case 6: cout<<"Your GRADE is B"<<endl; break;
case 5: cout<<"Your GRADE is C"<<endl; break;
case 4: cout<<"Your GRADE is D"<<endl; break;
default: cout<<"ERROR: that score is out of RANGE"<<endl;
}
}
}
#include<iostream>
Using namespace std;
int main()
Example with switch &
{
int score;
break (logical error)
cout<<"Enter your test score: ";
cin>>score;
if(score>100||score<0) cout<<"that score is not VALID"<<endl;
else
{
switch(score/10)
{
case 10:
case 9: cout<<"Your GRADE is A+"<<endl;
case 8: cout<<"Your GRADE is A"<<endl;
case 7: cout<<"Your GRADE is B+"<<endl;
case 6: cout<<"Your GRADE is B"<<endl;
case 5: cout<<"Your GRADE is C"<<endl;
case 4: cout<<"Your GRADE is D"<<endl;
case 3:
case 2:
case 1:
case 0: cout<<"Your GRADE is F"<<endl;
default: cout<<"ERROR: that score is out of RANGE"<<endl;
}
}
}
 switch, case, break, default are keywords
 The expression is evaluated first
 If one of the case values matches the value of the
expression, execution jumps to the statements following
that case value
 If the no case values matches the value of expression,
execution jumps to the default statement
 default statement is optional
 If there is no default and there is no matching value,
execution is transferred to the statement after the switch
block
 Whenever a break statement is encountered, control is
transferred to the statement after the switch block
 If there is no break statement after a block, execution
continues to the block for the next case value
break statement in loop
 The break statement is also used in loops
 It provides extra flexibility in the control of loops
 Normally a loop will terminate only at the
beginning or at the end of the complete sequence
of statements in the loop’s block
 But the break statement can be placed anywhere
among the other statements within a loop which
can be used to terminate a loop anywhere from
within the loop’s block
#include<iostream>
Example with break in
Using namespace std; loop
int main()
{
int n, count=0, sum=0;
cout<<"Enter positive integers (0 to quit)"<<endl;
for(;;)//"forever"
{
cout<<"\tNumber "<<count+1<<": ";
cin>>n;
if (n<=0) break;
++count;
sum+=n;
}
cout<<"\nThe average of those "<<count<<" numbers is “
<< double (sum)/count<<endl;
}
 When 0 is input, the break executes,
immediately terminating the for loop and
transferring execution to the final output
statement
 for (; ; ) this construct is pronounced as
“forever”
 Without break, this would be an infinite loop
#include<iostream> Example without break in
Using namespace std;
int main()
loop
{
int n, sum=0;
cout<<"How many numbers?"<<endl;
cin>>n;
cout<<"Enter positive integers"<<endl;
for (int i=1;i<=n;i++)
{
int Number;
cout<<"\tNumber "<<i<<": ";
cin>>Number;
sum+=Number;
}
cout<<"\nThe average of those "<<n<<" numbers is“
<< double(sum)/n<<endl;
}
FUNCTIONS,
ARRAY &
POINTERS
C++ FUNCTIONS
• To make large programs manageable,
programmers modularize them into
subprograms.
• These subprograms are called functions.
They can be compiled and tested
separately and reused in different
programs.
• This modularization is characteristic of
successful object-oriented software.
C++ FUNCTIONS
Functions make the programs more
modular and easy to read and
manage.
All C++ programs must contain the
function main( ).
The execution of the program starts
from the function main( ).
SOME STANDARD C++ LIBRARY FUNCTIONS

• The sqrt() function defined in <cmath>


• The rand() function defined in <cstdlib>
• The time() function defined in <ctime>
• The INT_MAX constant defined in <climits>
SOME USER-DEFINED FUNCTIONS
• The Cube() function
• The Max() function
• The factorial function
• The permutation function
• A function that tests primality
• A leap year function
• The swap() function

IMPORTANCE OF FUNCTION
• A program may need to repeat the same piece
of code at various places.
• It may be required to perform certain task
repeatedly.
• The program may become very large if
functions are not used.
• The real reason for using function is to divide
program into different parts.
ADVANTAGES OF FUNCTIONS

• Easier to code
• easier to modify
• easier to maintain
• reusability
• less programming time
• easier to understand
C++ FUNCTIONS

•C++ allows the use of both internal


(user defined) and external (built
in) functions.
• External functions are usually
grouped into specialized libraries
(e.g., iostream, cstdlib, cmath, etc.)
Function is divided into three sections:

Function declaration
Function call
Function definition
FORM OF FUNCTION
Syntax: function declaration
(function header)
return_type function_name
(parameter list) ;
syntax : function call
int main()
{
function_name (parameter list);
}
syntax: function definition (function
body)
{
statement 1;
statement 2;
:::
statement N;

}
FUNCTION DECLARATION
A function declaration is simply the function’s
head, followed by a semicolon. It is also
known as FUNCTION PROTOTYPE. It provides
information to compiler about the structure of
function to be used in program.
It consists of:
• Function return type
• Function name
• Numbers & types of parameters
The general form of function declaration :-
return_type function_name (parameter list);
The return_type specifies the type of the data the function
returns.
The variables that are listed in the function’s parameter list
are called parameters (actual parameters).
The parameter list could be empty .
The parameter list should contain both data type and
name of the variable.
For example,
int factorial (int n, float j);
FUNCTION DEFINITION
• A set of statements that explains what a
function does is called FUNCTION
definition. A function definition is the
complete function: header and body.
A function definition can be written at:
• before main() function
• after main() function
• in a separate file
FUNCTION CALL

The statement that activates a function is


known as FUNCTION CALL.
The following steps take place when a
function is called:
1. The control moves to the function that is
called.
2. All statements in function body are
executed.
3. Control returns back to calling function.
FUNCTION ARGUMENTS
The variables that are listed in the function’s
calls are called the arguments (formal parameters).
Arguments contain the actual value which is to
be passed to the function when it is called.
The sequence of the arguments in the call of the
function should be same as the sequence of the
parameters in the parameter list of the declaration
of the function.
When a function call is made arguments
replace the parameters of the function.
THE RETURN STATEMENT AND RETURN VALUES

A return statement is used to exit


from the function where it is.
It returns a value to the calling
code.
The general form of the return
statement is:-
return expression;
#Include<iostream> int factorial (int n)
int factorial(int n); {
int main () int i=0,fact=1;
{ if(n<=1)
{
int n1,fact;
return(1);
cout <<"Enter the number whose factorial
}
has to be calculated"<< endl; else
cin >> n1; {
fact=factorial(n1); for(i=1; i<=n; i++)
cout << "The factorial of " << n1 << " is : " {
fact=fact*i;
<< fact << endl; }
getch(); return(fact);
return(0); } }
}
SCOPE OF FUNCTIONS
Area in which a function can be accessed is
known as SCOPE OF FUNCTION.
These are two types:
1.Local function
A function that is declared in another
function is called local function.
2.Global function
A function that is declared outside any
function is called global function.
PARAMETERS PASS/CALL BY VALUE

Copies of the arguments are


created .
The parameters are mapped to the
copies of the arguments created.
The changes made to the
parameter do not affect the
arguments.
#include<iostream>
int add (int number)
int add (int n);
int main() {
{ int number, result; number=number+100
number=5; ;
cout << " The initial value of number : “ return(number);
<< number << endl; }
result=add (number);
cout << " The final value of number : "
<< number << endl;
cout << " The result is : " << result << endl;
return 0;
}
PARAMETERS PASS/CALL BY REFERENCE

Pass by reference is the second


way of passing parameters to the
function.
The address of the argument is
copied into the parameter.
The changes made to the
parameter affect the arguments.
#include<iostream> int main()
{
void swap (int &a, int &b); int m=1,n=2;
void swap (int &a, int &b) cout<<"value of m before
{ swaping\t"<<m<<endl;
int t=a; cout<<"value of n before
swaping\t"<<n<<endl;
a=b;
swap(m,n);
b=t; cout<<"value of m after
} swaping\t"<<m<<endl;
cout<<"value of n after
AMPERSAND SIGN=& swaping\t"<<n<<endl;
}
STATIC VARIABLE :
A local variable declared with keyword
static is called Static Variable.
It is used to increase the lifetime of local
variable.
Syntax for declaring is:
static data _type variable_name;
REGISTER VARIABLE :
A variable declared with keyword register is
known as register variable.
The value of register variable is stored in
registers instead of RAM because registers
are faster than RAM so value stored in
registers can be accessed faster than RAM.
Syntax for declaring is:
register data _type variable_name;
FUNCTION OVERLOADING
The process of declaring multiple functions with
same name but different parameters is called
FUNCTION OVERLOADING.
A function is overloaded when same name is given
to different function.
The function with same name must differ in one of
the following ways:
1. Numbers of parameters
2. Data type of parameter
3. Sequence of parameters
#include <iostream> int main() //begin of
#include<conio>
class arithmetic main function
{ {
public: arithmetic a;
void calc (int num1)
{
a.calc (4);
cout<<"Square of a given number: " a.calc (6,7);
<<num1*num1 <<endl; getch();
} }
void calc (int num1, int num2 )
{
cout<<"Product of two whole numbers: "
<<num1*num2 <<endl;
}
};
ARRAY IN C++
An array is a sequence of objects all of which have
the same type.
The objects are called the elements of the array and
are numbered consecutively 0, 1, 2, 3, ... .These
numbers are called index values or subscripts of the
array.
The term “subscript” is used because as a
mathematical sequence, an array would be written
with subscripts: a0, a1, a2, ….
The subscripts locate the element’s position within the
array, thereby giving direct access into the array
If the name of the array is a, then
a[0] is the name of the element that
is in position 0, a[1] is the name of
the element that is in position 1, etc.
In general, the i-th element is in
position i–1.
So if the array has n elements, their
names are a[0], a[1], a[2], …, a[n-1]
• The method of numbering the i-th element with
index i–1 is called zero-based indexing. It
guarantees that the index of each array element
is equal to the number of “steps” from the initial
element a[0] to that element. For example,
element a[3] is 3 steps from element a[0].
In C++, you declare an array by using the
form –
type array name [size]; where type is any
simple type, array name is any legal
identifier, and size (in the square bracket)
represents the number of elements the array
contains
An element is a single object in an array
An array name actually represents a
memory address
When you declare an array, you tell
the compiler to use the array name
to indicate the beginning address of
a series of elements
The subscript used to access an
element of an array indicates how
much to add to the starting address
to locate a value
NEED OF ARRAY
To store processed large number of variables of same
data type and reference/name
easy understanding of program
STORING VALUES IN AN ARRAY

• The statement int rent[4] = {250, 375, 460,


600}; provides four values for the array
• If you declare an array without a size, but
provide initialization values, C++ creates an
array with the exact size you need
• If you do not provide enough values to fill
an array, C++ fills any unassigned array
elements with zeros
TYPES OF ARRAY

One dimensional
Two dimensional
Multi dimensional
1-D ARRAY

A one dimensional array is one in which one


subscript /indices specification is needed to
specify a particular element of array
Declaration :
data_type array_name [size of array ];
Example:
int num[10];
2-D ARRAY
A one-dimensional array of one-dimensional arrays is called
a two-dimensional array; i.e int num[4][3]
MULTI DIMENSIONAL ARRAY
An array with dimensions more than two . An array of
arrays is called a multidimensional array.
Declration:
data_type name [a][b][c][d][e][f]…….[N];
A one-dimensional array of two-dimensional arrays is
called a three-dimensional array;
Array of 3 or more dimensional are not often use
because of huge memory requirement and complexity
involved.
The simplest way to declare a multidimensional array
is like this:
double a[32][10][4];
This is a three-dimensional array with dimensions 32,
10, and 4. The statement a[25][8][3] = 99.99 would
assign the value 99.99 to the element identified by
the multi-index (25,8,3). Example:
ARRAY INITIALIZATION
UNSIZED ARRAY INITIALIZATIONS
Address-of operator or Reference Operator (&)
The address of a variable can be obtained by preceding
the name of a variable with an ampersand sign (&), known
as address-of operator. For example: foo = &myvar;
myvar = 25;
foo = &myvar;
bar = myvar;
Dereference operator (*)
• A variable which stores the address of another variable is
called a pointer. Pointers are said to "point to" the variable
whose address they store.
• An interesting property of pointers is that they can be used to
access the variable they point to directly. This is done by
preceding the pointer name with the dereference operator (*).
the operator itself can be read as "value pointed to by".
For example:
baz = *foo;
POINTERS
• You also can declare variables that can hold
memory addresses
• These variables are called pointer variables, or
simply pointers
• You declare a pointer with a type, just like other
variables
• The major difference between using a pointer
name and the address operator with a variable
name is that a pointer itself is a variable
POINTERS
The reference operator ‘&’ returns the memory
address of the variable to which it is applied.
We can also store the address in another
variable.
The type of the variable that stores an address
is called a pointer.
For example, the address of an int variable can
be stored in a pointer variable of type int*.
USING A POINTER INSTEAD OF
AN ARRAY NAME

• Advanced C++ programmers


use pointers for many purposes
• Sometimes they use a pointer
as an alternative to an array
name
POINTERS AND REFERENCES
THE REFERENCE OPERATOR:

Computer memory can be imagined as a very large


array of bytes.
For example, a computer with 256 MB of RAM
actually contains an array of 268,435,456 (228)
bytes.
As an array, these bytes are indexed from 0 to
268,435,455.
The index of each byte is its memory address.
So a 256 MB computer has memory addresses
ranging from 0 to 268,435,455, which is
0x00000000 to 0x0fffffff in hexadecimal.
The diagram at right represents that array of bytes,
each with its hexadecimal address.
A variable declaration associates three
fundamental attributes to the variable: its name,
its type, and its memory address.
For example, the declaration int n; associates the
name n, the type int, and the address of some
location in memory where the value of n is
stored. Suppose that address is 0x0064fdf0. Then
we can visualize n like this:
 On most computers, variables of type int occupy 4 bytes
in memory.
 So the variable n shown above would occupy the 4-byte
block of memory represented by the shaded rectangle
in the diagram at right, using bytes 0x0064fdf0,
0x0064fdf1, 0x0064fdf2, and 0x0064fdf3.
 Note that the address of the object is the address
of the first byte in the block of memory
where the object is stored.
If the variable is initialized, like this:
int n=44; then the two representations
look like this:
The variable’s value 44 is stored
in the four bytes allocated to it.
In C++, you can obtain the
address of a variable by using the
reference operator &, also called
the address operator. The
expression &n evaluates to the
address of the variable n.
CLASSES & OBJECTS

INTRODUCTION
OOP is a powerful way to approach the task of
programming.
OOP encourages developers to decompose a problem
into its constituent parts.
Each component becomes a self-contained object that
contains its own instructions and data that relate to that
object.
So, complexity is reduced and the programmer can
manage larger programs.
INTRODUCTION
All OOP languages, including C++, share three common
defining traits:
Encapsulation
Binds together code and data
Polymorphism
Allows one interface, multiple methods
Inheritance
Provides hierarchical classification
Permits reuse of common code and data
CLASSES: A FIRST LOOK
General syntax -
class class-name
{
private:
// private functions and variables
public:
// public functions and variables
protected: (optional)
}
object-list (optional);
CLASSES: A FIRST LOOK

A class declaration is a logical abstraction that defines


a new type.
An object declaration creates a physical entity of that
type.
That is, an object occupies memory space, but a type
definition does not.
Each object of a class has its own copy of every
variable declared within the class (except static
variables), but they all share the same copy of member
functions.
INTRODUCING FUNCTION OVERLOADING
Provides the mechanism by which C++ achieves one type of
polymorphism (called compile-time polymorphism).
Two or more functions can share the same name as long as either
The type of their arguments differs, or
The number of their arguments differs, or
Both of the above
The compiler will automatically select the correct version.
The return type alone is not a sufficient difference to allow
function overloading.
CLASSES & OBJECTS

A class is like an array: it is a derived


type whose elements have other types.
The elements of a class may have
different types
Some elements of a class may be
functions, including operators.
CLASSES & OBJECTS
Although any region of storage may generally be
regarded as an “object”, the word is usually used
to describe variables whose type is a class.
Thus “object-oriented programming” involves
programs that use classes.
We think of an object as a self-contained entity
that stores its own data and owns its own
functions.
CLASS DECLARATIONS
Here is a declaration for a class whose objects
represent rational numbers (i.e., fractions):
class Ratio
{ public:
void assign(int,int);
double convert();
void invert();
void print();
private:
int num,den;
};
CLASS DECLARATIONS
 int main()
 { Ratio x;
 x.assign(22,7);
 cout << "x = ";
 x.print();
 cout << " = " << x.convert() << endl;
 x.invert();
 cout << "1/x = ";
 x.print();
 cout << endl;
}
CLASS DECLARATIONS
 void Ratio::assign(int numerator, int denominator)
 { num = numerator;
 den = denominator;
}
 double Ratio::convert()
 { return double(num)/den;
}
 void Ratio::invert()
 { int temp = num;
 num = den;
 den = temp;
}
CLASS DECLARATIONS
 void Ratio::print()
 { cout << num << '/' << den;

}

Output:
x = 22/7 = 3.14286
1/x = 7/22
CLASS DECLARATIONS
The declaration begins with the keyword class followed by the name
of the class and ends with the required semicolon. The name of
this class is Ratio.
The functions assign(), convert(), invert(), and print() are called
member functions because they are members of the class.
Similarly, the variables num and den are called member data.
In this class, all the member functions are designated as public, and
all the member data are designated as private. The difference is
that public members are accessible from outside the class, while
private members are accessible only from within the class.

Preventing access from outside the class is called “information


hiding.” It allows the programmer to compartmentalize the
software which makes it easier to understand, to debug, and to
maintain.
CLASS DECLARATIONS
Here x is declared to be an object of the Ratio class.
Consequently, it has its own internal data members
num and den, and it has the ability to call the four
class member functions assign(), convert(), invert(),
and print(). Note that a member function like invert()
is called by prefixing its name with the name of its
owner: x.invert(). Indeed, a member function can only
be called this way. We say that the object x “owns”
the call.
An object like x is declared just like an ordinary
variable. Its type is Ratio. We can think of this type as
a “user-defined type.” C++ allows us to extend the
definition of the programming language by adding
the new Ratio type to the collection of predefined
numeric types int, float, etc.
CLASS DECLARATIONS

Notice the use of the specifier Ratio:: as a prefix


to each function name. This is necessary for
each member function definition that is given
outside of its class definition. The scope
resolution operator :: is used to tie the function
definition to the Ratio class. Without this
specifier, the compiler would not know that the
function being defined is a member function of
the Ratio class. This can be avoided by
including the function definitions within
declaration.
CONSTRUCTORS
A constructor is a member function that is
invoked automatically when an object is
declared.
A constructor function must have the same
name as the class itself, and it is declared
without return type.
A CONSTRUCTOR FUNCTION FOR THE RATIO CLASS
class Ratio
{ public:
Ratio(int n,int d) { num = n; den = d; }
void print() { cout << num << '/' << den; }
private:
int num,den;
};
int main()
{ Ratio x(-1,3), y(22,7);
cout << "x = ";
x.print();
cout << " and y = ";
y.print();
}
x = -1/3 and y = 22/7
CONSTRUCTORS
The constructor function has the same effect as
the assign() function : it initializes the object by
assigning the specified values to its member
data. When the declaration of x executes, the
constructor is called automatically and the
integers -1 and 3 are passed to its parameters
n and d. The function then assigns these values
to x’s num and den data members. So the
declarations Ratio x(-1,3), y(22,7); are
equivalent to the three lines:
Ratio x,y;
x.assign(-1,3);
y.assign(22,7);
THE CLASS DESTRUCTOR
When an object is created, a constructor is called
automatically to manage its birth. Similarly,
when an object comes to the end of its life,
another special member function is called
automatically to manage its death. This
function is called a destructor.
Each class has exactly one destructor. If it is not
defined explicitly in the class definition, then
like the default constructor, the copy
constructor, and the assignment operator, the
destructor is created automatically.
INCLUDING A DESTRUCTOR IN THE RATIO CLASS
class Ratio
{ public:
Ratio() { cout << "OBJECT IS BORN.\n"; }
~Ratio() { cout << "OBJECT DIES.\n"; } OBJECT IS BORN.
Now x is alive.
private:
OBJECT DIES.
int num,den; Now between blocks.
}; OBJECT IS BORN.
int main() Now y is alive.
OBJECT DIES.
{ { Ratio x; // beginning of scope for x
cout << "Now x is alive.\n";
} // end of scope for x
cout << "Now between blocks.\n";
{ Ratio y;
cout << "Now y is alive.\n";
}
}
THE CLASS DESTRUCTOR
The class destructor is called for an object when it
reaches the end of its scope. For a local object,
this will be at the end of the block within which
it is declared. For a static object, it will be at the
end of the main() function.
Although the system will provide them
automatically, it is considered good
programming practice always to define the copy
constructor, the assignment operator, and the
destructor within each class definition.
Lecture-11

INHERITANCE
A way to reuse existing software to create new software is
by means of inheritance (also called specialization or
derivation).
The common syntax for deriving a class Y from a class X is
class Y : public X
{
// ...
}
Here X is called the base class (or superclass) and Y is
called the derived class (or subclass).
The keyword public after the colon specifies public
inheritance, which means that public members of the base
class become public members of the derived class.
The protected access category is a balance between private
and public categories: private members are accessible only
from within the class itself and its friend classes; protected
members are accessible from within the class itself, its
friend classes, its derived classes, and their friend classes;
public members are accessible from anywhere within the
file. In general, protected is used instead of private
whenever it is anticipated that a subclass might be defined
for the class.
A subclass inherits all the public and protected members of
its base class. This means that, from the point of view of
the subclass, the public and protected members of its base
class appear as though they actually were declared in the
subclass.
One of the most powerful features of C++ is that it
allows objects of different types to respond differently
to the same function call. This is called polymorphism
and it is achieved by means of virtual functions.

You might also like