Unit 1 Notes
Unit 1 Notes
-------------------------------------------------------------------------------------------------------------------------------
Object-oriented programming and procedural programming both are used to develop the applications.
Both of them are high-level programming languages.
Procedural Programming
It is defined as a programming language derived from the structure programming and based on calling
procedures. The procedures are the functions, routines, or subroutines that consist of the computational
steps required to be carried. It follows a step-by-step approach in order to break down a task into a set of
variables and routines via a sequence of instructions. During the program's execution, a procedure can be
called at any point, either by other procedures or by itself. The examples of procedural programming are
ALGOL, COBOL, BASIC, PASCAL, FORTRAN, and C.
Object-oriented programming
OOP is said to be the most popular programming model among developers. It is well suited for programs
that are large, complex, and actively updated or maintained. It makes the development and maintenance
of software easy by providing major concepts such as abstraction, inheritance, polymorphism, and
encapsulation. These four are also the four pillars of an object-oriented programming system.
1
OOPs, provide the ability to simulate real-world events much more effectively. We can provide the
solution to real-world problems if we are using the Object-Oriented Programming language. OOPs,
provide data hiding, whereas, in Procedure-oriented programming language, global data can be accessed
from anywhere.
The examples of OOPs are - C#, Python, C++, Java, PHP, Scala, Perl, etc.
4. In procedural programming, data moves In OOP, objects can move and communicate
freely within the system from one function to with each other via member functions.
another.
5. It is structure/procedure-oriented. It is object-oriented.
6. There are no access modifiers in procedural The access modifiers in OOP are named as
programming. private, public, and protected.
2
7. Procedural programming does not have the There is a feature of inheritance in object-
concept of inheritance. oriented programming.
8. There is no code reusability present in It offers code reusability by using the feature of
procedural programming. inheritance.
10. It gives importance to functions over data. It gives importance to data over functions.
11. In procedural programming, there are no In OOP, there is an appearance of virtual classes
virtual classes. in inheritance.
12. It is not appropriate for complex problems. It is appropriate for complex problems.
13. There is not any proper way for data hiding. There is a possibility of data hiding.
14. In Procedural programming, a program is In OOP, a program is divided into small parts
divided into small programs that are referred that are referred to as objects.
to as functions.
Advantages:
We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,
3
OOP language allows breaking the program into the bit-sized problems that can be solved easily
(one object at a time).
The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing classes.
Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
Disadvantages of OOP
The length of the programs developed using OOP language is much larger than the procedural
approach. Since the program becomes larger in size, it requires more time to be executed that
leads to slower execution of the program.
We cannot apply OOP everywhere as it is not a universal language. It is applied only when it is
required. It is not suitable for all types of problems.
Programmers need to have brilliant designing skill and programming skill along with proper
planning because using OOP is little bit tricky.
OOPs take time to get used to it. The thought process involved in object-oriented programming
may not be natural for some people.
Everything is treated as object in OOP so before applying it we need to have excellent thinking in
terms of objects.
4
Structure of C++ program:
Programs are a sequence of instructions or statements. These statements form the structure of a C++
program. C++ program structure is divided into various sections, namely, headers, class definition,
member functions definitions and main function.
Note that C++ provides the flexibility of writing a program with or without a class and its member
functions definitions. A simple C++ program (without a class) includes comments, headers, namespace,
main() and input/output statements.
Comments are a vital element of a program that is used to increase the readability of a program and to
describe its functioning. Comments are not executable statements and hence, do not increase the size of a
file.
C++ supports two comment styles: single line comment and multiline comment. Single line comments are
used to define line-by-line descriptions. Double slash (//) is used to represent single line comments. To
understand the concept of single line comment, consider this statement.
5
/ / An example to demonstrate single line comment It can also be written as
/ / An example to demonstrate
Multiline comments are used to define multiple lines descriptions and are represented as / * * /. For
example, consider this statement.
Generally, multiline comments are not used in C++ as they require more space on the line. However, they
are useful within the program statements where single line comments cannot be used. For example,
consider this statement.
Compiler ignores everything written after the single line comment and hence, an error occurs. Therefore,
in this case multiline comments are used. For example, consider this statement.
Headers: Generally, a program includes various programming elements like built-in functions, classes,
keywords, constants, operators, etc., that are already defined in the standard C++ library. In order to use
such pre-defined elements in a program, an appropriate header must be included in the program. The
standard headers contain the information like prototype, definition and return type of library
functions, data type of constants, etc. As a result, programmers do not need to explicitly declare (or
define) the predefined programming elements.
Standard headers are specified in a program through the preprocessor directive” #include. In Figure, the
iostream header is used. When the compiler processes the instruction #inc1ude<iostream>, it includes the
contents of iostream in the program. This enables the programmer to use standard input,
output and error facilities that are provided only through the standard streams defined in <iostream>.
These standard streams process data as a stream of characters, that is, data is read and displayed in a
continuous flow. The standard streams defined in <iostream> are listed here.
• cin (pronounced “see in”) : It is the standard input stream that is associated with the standard input
device (keyboard) and is used to take the input from users.
• cout (pronounced “see out”) : It is the standard output stream that is associated with the standard output
device (monitor) and is used to display the output to users.
6
Namespace: Since its creation, C++ has gone through many changes by the C++ Standards Committee.
One of the new features added to this language is namespace. A namespace permits grouping of various
entities like classes, objects, functions and various C++ tokens, etc., under a single name. Different users
can create separate namespaces and thus can use similar names of the entities. This avoids compile-time
Main Function: The main () is a startup function that starts the execution of a C++ program. All C++
statements that need to be executed are written within main ( ). The compiler executes all the instructions
written within the opening and closing curly braces’ {}’ that enclose the body of main ( ). Once all the
instructions in main () are executed, the control passes out of main ( ), terminating the entire program and
returning a value to the operating system.
In C++, data types are declarations for variables. This determines the type and size of data
associated with variables. The table below shows the fundamental data types, their meaning, and
their sizes (in bytes):
int Integer 2 or 4
float Floating-point 4
char Character 1
bool Boolean 1
void Empty 0
1. C++ int
Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.
7
For example, int salary = 85000;
float and double are used to store floating-point numbers (decimals and exponentials).
The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the
precision of float. To learn more, visit C++ float and double.
As mentioned above, these two data types are also used for exponentials.
For example, double distance = 45E12 // 45E12 is equal to 45*10^12
3. C++ char
Note: In C++, an integer value is stored in a char variable rather than the character itself.
4. C++ bool
The bool data type has one of two possible values: true or false.
Booleans are used in conditional statements and loops (which we will learn in later chapters).
5. C++ void
The void keyword indicates an absence of data. It means "nothing" or "no value".
8
Symbolic constants and reference by variables:
A symbolic constant is a name given to some numeric constant, or a character constant or string constant,
or any other constants. Symbolic constant names are also known as constant identifiers. Pre-processor
directive #define is used for defining symbolic constants.
#define PI 3.141592
Note: symbolic constants names are written in uppercase by convention, but it is not required.
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 provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
9
1) Arithmetic Operators
2) Relational Operators
10
== Checks if the values of two operands are (A == B) is not true.
equal or not, if yes then condition becomes
true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
3) Logical Operators
11
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.
4) Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^ are as
follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
12
-----------------
~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 −
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.
~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.
13
5) Assignment Operators
14
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
6) Other Operators
The following table lists some other operators that C++ supports.
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and
will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of
Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.
Member operators are used to reference individual members of classes, structures, and unions.
15
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual address of
the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
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.
16
Shift << >> Left to right
Control Structures
Control Structures are just a way to specify flow of control in programs. Any algorithm or program can
be clearer and understood if they use self-contained modules called as logic or control structures. It
basically analyzes and chooses in which direction a program flows based on certain parameters or
conditions. There are three basic types of logic, or flow of control, known as:
17
3. Iteration logic, or repetitive flow
Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the
series of instructions given to the computer. Unless new instructions are given, the modules are executed
in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also,
implicitly follows the order in which modules are written. Most of the processing, even some complex
problems, will generally follow this elementary flow pattern.
Selection Logic simply involves a number of conditions or parameters which decides one out of several
written modules. The structures which use these type of logic are known as Conditional Structures.
These structures can be of three types:
Single Alternative
If (condition) then:
[Module A]
[End of If structure]
18
Double Alternative
If (Condition), then:
[Module A]
Else:
[Module B]
[End if structure]
Multiple Alternatives
[Module A]
[Module B]
..
..
[Module N]
[End If structure]
In this way, the flow of the program depends on the set of conditions that are written. This can be more
understood by the following flow charts:
Repeat-For Structure
Repeat for i = A to N by I:
19
[Module]
[End of loop]
Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K
increases or decreases according to the positive and negative value of I respectively.
Repeat-While Structure
It also uses a condition to control the loop. This structure has the form:
[Module]
[End of Loop]
C++ Functions
The function in C++ language is also known as procedure or subroutine in other programming languages.
To perform any task, we can create function. A function can be called many times. It provides modularity
and code reusability.
Advantage of functions in C
1) Code Reusability: By creating functions in C++, you can call it many times. So we don't need to write
the same code again and again.
2) Code optimization: It makes the code optimized, we don't need to write much code. But if you use
functions, you need to write the logic only once and you can reuse it several times.
Types of Functions
1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x),
cos(x), exp(x), etc.
20
2. User-defined functions: are the functions which are created by the C++ programmer, so that he/she
can use it many times. It reduces complexity of a big program and optimizes the code.
Declaration of a function
//code to be executed
1. #include <iostream>
3. void func() {
6. i++;
7. j++;
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
A function prototype is a declaration of the function that tells the program about the type of the value
returned by the function and the number and type of arguments. Function prototyping is one very useful
feature of C++ function. A function prototype describes the function interface to the compiler by giving
details such as the number and type of arguments and the type of return values.
The prototype declaration looks just like a function definition except that it has no body i.e., its code is
missing. This is the time you knew the difference between a declaration and a definition. A declaration
introduces a (function) name to the program whereas a definition is a declaration that also tells the
program what the function is doing and how it is doing.
Thus the above given examples are function definitions and the following are declarations or shall we say,
function prototypes:
Therefore, you can say that a function prototype has the following parts:
22
return type
argument list
Let's look at the following function prototype: int sum(int n1, int n2);
Here,
Since every function prototype is followed by a semicolon, so at last there will be ; as in the above
function prototype.
Tip - A function declaration can skip the argument names but a function definition, can not.
Use of Void
As you know about void data type that it specifies an empty set of values and it is used as the return type
for functions that do not return a value. Thus, a function that does not return a value is declared as
follows:
By declaring a function's return type void, one makes sure that the function cannot be used in an
assignment statement.
Tip - If a function does not return a result, declare the result type as void.
A function that does not require any parameter (i.e., it has an empty argument list) can be declared as
follows:
return_type function_name(void);
Tip - If a function takes no argument, you should specify void in its prototype.
23
As already mentioned if you omit the type specifier of a function, it is assumed to be returning int values.
For the functions returning non-integer values, the type specifier must be given.
A function prototype can either appear before the definition of calling the function (such prototypes are
known as global prototypes) or within the definition of calling function (such prototypes are known as
local prototypes).
Here, the return_type specifies the type of value that the return statement of the functions returns. It may
be any valid C++ data type. If no type is specified, the compiler assumes that the function returns an
integer value. The parameter list is a common-separated list of variables of a function referred to as its
arguments. A function may be without any parameters, in which case, the parameter list is empty. Here
are some examples of functions. Below is a function having only one parameter of int type and return
type also as int :
Here is another function definition example. This function has return type as int, and have two integer
parameters
24
int temp;
while(n2)
temp = n2 ;
n2 = n1%n2 ;
n1 = temp ;
return n1 ;
Let's take an example program, demonstrating function prototype and function definition in C++. This
program also uses function calling, which is covered in C++ Calling Function tutorial coming in the next
chapter.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
25
clrscr();
int a, b;
cin>>a>>b;
getch();
int res;
res = x + y;
return res;
int res;
res = x - y;
return res;
26
{
int res;
res = x * y;
return res;
if(y==0)
getch();
exit(1);
else
int res;
res = x / y;
return res;
27
Example: Return by Reference
#include <iostream>
// global variable
int num;
// function declaration
int& test();
int main() {
// equivalent to num = 5;
test() = 5;
return 0;
// function definition
int& test() {
return num;
The return statement is return num;. Unlike return by value, this statement doesn't return value of num,
instead it returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in test() = 5;
This stores 5 to the variable num, which is displayed onto the screen.
28
Important Things to Remember When Returning by Reference.
Ordinary function returns value but this function doesn't. Hence, you cannot return a constant
from the function.
int& test()
{ return 2; }
int& test()
{ int n = 2; return n; }
Inline Functions:
C++ inline function is powerful concept that is commonly used with classes. If a function is inline,
the compiler places a copy of the code of that function at each point where the function is called at
compile time.
Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword inline before the function name and define the function before
any calls are made to the function. The compiler can ignore the inline qualifier in case defined
function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the
inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
29
inline int Max(int x, int y) {
int main() {
return 0;
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Default Arguments
A default argument is a value in the function declaration automatically assigned by the compiler
if the calling function does not pass any value to that argument.
o The values passed in the default arguments are not constant. These values can be
overwritten if the value is passed to the function. If not, the previously declared value
retains.
o During the calling of function, the values are copied from left to right.
30
o All the values that will be given default value will be on the right.
Example
Code
1. #include<iostream>
3. int sum(int x, int y, int z=0, int w=0) // Here there are two values in the default argumen
ts
6. }
7. int main()
8. {
10. cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w = 0
11. cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w = 30
12. return 0;
13. }
Output
31
25
50
80
Explanation
In the above program, we have called the sum function three times.
o Sum(10,15)
When this function is called, it reaches the definition of the sum. There it initializes x to
10 y to 15, and the rest values are zero by default as no value is passed. And all the values
after sum give 25 as output.
Function Overloading
Function overloading is a C++ programming feature that allows us to have more than one function having
same name but different parameter list, when I say parameter list, it means the data type and sequence of
the parameters, for example the parameters list of a function myfuncn(int a, float b) is (int, float) which is
different from the function myfuncn(float a, int b) parameter list (float, int). Function overloading is
a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following
functions in the same scope.
32
sum(int num1, double num2)
The easiest way to remember this rule is that the parameters should qualify any one or more of the
following conditions, they should have different type, number or sequence of parameters.
For example:
These two functions have different parameter type:
All of the above three cases are valid case of overloading. We can have any number of functions, just
remember that the parameter list should be different. For example:
This is not allowed as the parameter list is same. Even though they have different return types, its not
valid.
#include <iostream>
class Addition {
public:
33
int sum(int num1,int num2) {
return num1+num2;
return num1+num2+num3;
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
return 0;
Output:
35
191
The main advantage of function overloading is to the improve the code readability and allows code
reusability. In the example 1, we have seen how we were able to have more than one function for the
same task (addition) with different parameters; this allowed us to add two integer numbers as well as
three integer numbers, if we wanted we could have some more functions with same name and four or five
arguments.
Imagine if we didn’t have function overloading, we either have the limitation to add only two integers or
we had to write different name functions for the same task addition, this would reduce the code
readability and reusability.
34