C++ Sanjoy Sir Slides
C++ Sanjoy Sir Slides
Sanjoy Das
Assistant Professor
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
•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
−
−
− =
−
−
−
−
−
−
−
−
−
Data Representation
. × = .
−
− . × = .
− . × = .
− . × = .
−
− . × = .
−
−
. 28125 = .
Data Representation
. = . 28125
Data Representation
− = ( − )( + +⋯ + )(7)
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-
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
Prepared by
Sanjoy Das
Assistant Prof.
Dept. of CE, CUET
Structure of C++ Program
Include Files
Class Definition
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
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
#include <iostream>
int main()
{
// prints “Boring Class!”
cout << “Boring Class!\n”;
return 0;
}
Introduction to Programming
#include <iostream>
int main()
{
// prints “Boring Class!”
cout << “Boring Class!\n”;
return 0;
}
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
Sanjoy Das
Assistant Professor
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
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:
For example, the following tells the compiler that feet is another name for
int:
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
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
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
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
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
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
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:
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
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().
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
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.
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.
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.
int main()
{ int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m<n ? m : n ) << " is the minimum." << endl;
}
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
{…………….
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
If condition If condition
is true is false
{
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
{…………….
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
{
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
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
• Easier to code
• easier to modify
• easier to maintain
• reusability
• less programming time
• easier to understand
C++ FUNCTIONS
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
One dimensional
Two dimensional
Multi dimensional
1-D ARRAY
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
}
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.
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.