Definition of Procedure Oriented Programming (POP):
High-level languages like COBOL, FORTRAN, and C are examples of POP.
Programs are divided into sub-programs or modules, which are then combined to form a complete program.
These modules are referred to as functions.
Structure of POP:
Programs are organized around functions or procedures.
Each function performs a specific task.
Data Handling in POP:
Important data items are often declared as global, making them accessible to all functions.
Functions can have their own local data, which is accessible only within that function.
Changes made to global data by one function affect other functions that use the same data.
Challenges in POP:
Global data is more vulnerable to accidental changes by functions.
In large programs, it becomes difficult to track which function uses which data.
This can lead to issues in debugging and maintaining the code.
Summary:
POP focuses on dividing programs into functions.
Global data is shared among functions, which can lead to potential risks and complexities in large programs.
procedure-oriented programming
Some characteristics exhibited by procedure-oriented programming are:
Emphasis is on doing things (algorithms).
Large programs are divided into smaller programs known as functions.
Most of the functions share global data.
Data move openly around the system from function to function.
Functions transform data from one form to another.
Employs top-down approach in program design.
Definition of Object-Oriented Programming (OOP):
OOP was invented to address flaws in the procedural programming approach.
It treats data as a critical element and restricts its free flow around the system.
Key Features of OOP:
Data is tied closely to the functions that operate on it.
Data is protected from accidental modification by external functions.
Programs are decomposed into entities called objects.
Structure of OOP:
Data and functions are built around objects.
Each object contains data and functions that operate on that data.
Data Access in OOP:
Data of an object can only be accessed by functions associated with that object.
Functions of one object can interact with functions of other objects.
Advantages of OOP:
Encapsulation ensures data security and prevents accidental modification.
Programs are organized around objects, making them modular and easier to manage.
Promotes reusability and scalability in software development.
Summary:
OOP focuses on objects, combining data and functions into a single entity.
It provides better data protection and organization compared to procedural programming.
Some of the striking features of object oriented programming are:
Emphasis is on data rather than procedure.
Programs are divided into what are known as objects.
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data structure.
Data is hidden and cannot be accessed by external functions
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Follows bottom-up approach in program design.
Procedure oriented programming (POP)
In POP, program is divided into small parts called functions.
In POP, importance is not given to data but to functions as well as sequence of actions to be done.
POP follows Top Down Approach
POP does not have any access specifier
In POP, Data can move freely from function to function in the system
To add new data and functions in POP is not so easy
In POP, most functions uses global data for sharing that can be accessed freely from function to function in the system
POP does not have any proper way for hiding data so it is less secure.
In, POP, Overloading is not possible.
Examples of POP are: C, VB, FORTRAN.
Object oriented programming (OOP)
In OOP, program is divided into parts called objects.
In OOP, importance is given to data rather than procedures or functions because it works as a real world.
OOP follows Bottom Up Approach
OOP has access specifiers named public, private, protected.
In OOP, Objects can move and communicate which each other through member functions.
OOP provides an easy way to add new data and functions
In OOP, data cannot move easily from function to function, it can be kept public or private so we can control the access of data.
OOP provides Data Hiding so provides more security.
In OOP, Overloading is possible in the form of function overloading and operator overloading.
Examples of POP are: C++, JAVA, VB.Net
Objects
Basic run-time entities in an object-oriented system.
Can represent real-world entities like a person, place, bank account, or user-defined data like vectors, time, and lists.
Occupy memory space and have an associated address.
Interact by sending messages to each other during program execution.
Contain both data and code to manipulate the data.
Objects can interact without knowing the internal details of each other.
Class
A collection of objects.
A logical entity that acts as a blueprint for data members and functions.
Example: A class Car with data members (variables) like speed, weight, price, and functions like gearChange(), slowDown(), brake().
Objects are instances of a class.
Inheritance
The process of creating a new class (derived class) from an existing class (base class).
Base class is also known as a parent class or superclass.
Derived class is also known as a child class or subclass.
Reduces code redundancy and improves code reusability.
Real-life example: A child inherits properties from their parents.
Polymorphism
The ability to represent one form in multiple forms.
Original method resides in the base class, while overridden methods reside in derived classes.
Derived from Greek words: "poly" (many) and "morphs" (forms).
Real-life example: A person behaves differently in different situations (e.g., as a student, customer, or son/daughter).
Abstraction
The process of hiding internal details and showing only functionality.
Example: Sending an SMS involves typing a message, selecting a contact, and clicking send. The internal process is hidden from the user.
Data Encapsulation
Combines data and functions into a single unit.
Also known as data hiding.
Achieved by making data members private and providing public functions to access or modify them.
Example: A capsule that wraps different medicines.
Message Passing
Objects communicate by sending and receiving information.
Involves specifying the object name, function name, and information to be sent.
Example: A customer object sends a message to an account object to request the bank balance.
OOP offers several benefits to both the program designer and the user. Object orientation contributes to the solution of many problems associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principle advantages are:
Modular Structure
Programs are organized into clear, easy-to-understand modules (classes and objects).
Code Reusability
Objects created in one program can be reused in other programs, saving development time and cost.
Better Program Design
OOP helps in designing large programs with fewer flaws and better structure.
Enhanced Modularity
Each object exists independently, making programs more modular and manageable.
Inheritance Reduces Redundancy
Redundant code is eliminated by reusing and extending existing classes through inheritance.
Focus on Classes and Objects
Programs are divided into classes and objects rather than functions or procedures.
Bottom-Up Approach
OOP follows a bottom-up approach, focusing on building programs from smaller, reusable components.
Data Security
Encapsulation and data hiding ensure data security by restricting access to private data.
Data and Functions as a Single Entity
Data and functions are combined into a single unit (object), improving organization and clarity.
Easy to Extend
New features can be added easily by introducing new objects without modifying existing ones.
Lower Maintenance Cost
OOP programs are easier to maintain and update compared to other programming paradigms.
Emphasis on Data
Focuses on data rather than procedures, making programs more intuitive and aligned with real-world scenarios.
Improved Software Quality
OOP promotes better-quality software with fewer errors and higher reliability.
Increased Programmer Productivity
Reusable code and modular design enhance programmer efficiency and productivity.
OOP has become one of the programming buzzwords today. There appears to be a great deal of excitement and interest among software engineers in using OOP.
Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as window. Hundreds of windowing systems have been developed, using the OOP techniques. OOP is useful in these types of application because it can simplify a complex problem.
The promising areas of application of OOP include:
User interface design such as windows, menu,...
Real Time Systems
Simulation and Modeling
Object oriented databases
Artificial Intelligence and Expert System
Neural Networks and parallel programming
Decision support and office automation system
Development of C++
Developed by Bjarne Stroustrup at AT&T Bell Laboratories in the early 1980s.
Combines the best features of C and Simula67 (an object-oriented language).
Aimed to support object-oriented programming (OOP) while retaining the power and elegance of C.
Evolution of the Name
Initially called "C with Classes" due to the addition of the class construct.
Renamed to C++ in 1983.
The name C++ is derived from the C increment operator (++), symbolizing an enhanced or augmented version of C.
Relationship with C
C++ is a superset of C, meaning almost all C programs are valid C++ programs.
Adds new features like classes, inheritance, function overloading, and operator overloading to support OOP.
Key Features Added to C
Classes: Enable the creation of abstract data types and encapsulation.
Inheritance: Allows new classes to inherit properties from existing classes, promoting code reusability.
Function Overloading: Supports multiple functions with the same name but different parameters.
Operator Overloading: Enables defining custom behavior for operators (e.g., +, -, *, /) for user-defined types.
Polymorphism: Supports multiple forms of functions or operators, enhancing flexibility.
Why C++ is Truly Object-Oriented
Supports abstraction, encapsulation, inheritance, and polymorphism, the four pillars of OOP.
Enables the creation of complex, reusable, and modular software systems.
C++ bridges the gap between the procedural programming of C and the object-oriented paradigm, making it a powerful and versatile language for modern software development.
Versatility in Handling Large Programs
Suitable for virtually any programming task, including:
Development of editors, compilers, and databases.
Building communication systems and complex real-life applications.
Object-Oriented Libraries
Allows creation of hierarchies of related objects.
Enables development of specialized object-oriented libraries for reuse by other programmers.
Real-World Problem Solving
Effectively maps real-world problems using object-oriented features.
Retains the ability to work close to machine-level details (inherited from C).
Maintainability and Expandability
Programs are easily maintainable and expandable.
New features can be added seamlessly to the existing object structure.
Replacement for C
Expected to replace C as a general-purpose language in the near future due to its advanced features and flexibility.
C++ programs have many parts and components that serve specific purposes. Your first step in learning C++ is to learn what they are. We will begin by looking at below Program.
//A simple C++ program
#include<iostream>
using namespace std;
int main()
{
cout << "Programming in great fun"; return 0;
}
The output of the program is shown below. This is what appears on the screen when the program runs.
Program Output : Programming in C++
Line 1: Comments - They are ignored by the compiler
// A simple C++ program
This section is used to provide small description of the program. The comment lines are simply ignored by the compiler, that means they are not executed. In C++, there are two types of comments.
Single Line Comments: Single line comment begins with // symbol. We can write any number of single line comments.
Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can write any number of multiple lines comments in a program.
In a C++ program, the comment lines are optional. Based on the requirement, we write the comments. All the comment lines in a C++ program just provide the guidelines to understand the program and its code.
Line 2: Preprocessing Commands (#include<iostream> )
Preprocessing commands are used to include header files. We use #include statement to include header file into our program. All C++ Programs begin with a #include directive that includes the specified header file contents into the main program.
We have used the following #include directive in the program. #include <iostream>
The Header file iostream should be included at the beginning of all programs that use input/output statements.
Line 3: using namespace std;
Namespace is a new concept introduced by the ANSI C++ Standards committee. This defines scope for the identifiers that are used in a program. For using the identifiers defined in the namespace scope we must include using directive, like
using namespace std;
Here , std is the standard namespace. cout, cin and a lot of other things are defined in it. using and namespace are the new keywords of C++
Line 4: int main()
Every C++ program must write this statement. This statement (main) specifies the starting point of the C++ program execution. Here, main is a user defined method which tells the compiler that this is the starting point of the program execution. Here, int is a datatype of a value that is going to return to the Operating System after completing the main method execution.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C++ program, every block begins with '{' symbol.
Line 6:
cout << "Programming in C++";
This statement introduces two new C++ features, cout, and <<. The identifier cout ( pronounced as ‘ C out’) is a predefined object that represents the standard output stream represents the screen
The message “Programming in C++” is printed without the quotation marks. In programming terms, the group of characters inside the quotation marks is called a string literal or string constant.
The operator << is called the insertion or put to operator. It inserts the contents of the variable on its right the object on its left.
Line 7:
return 0;
This sends the integer value 0 back to the operating system upon the program’s completion. The value 0 usually indicates that a program executed successfully.
Line 8: Closing Brace ( } )
The close brace indicates the end of the block which belongs to the main method. In C program every block ends with '}' symbol.
Every executable statement must end with semicolon symbol (;).
Every C++ program must contain exactly one main method (Starting point of the program execution).
All the system defined words (keywords) must be used in lowercase letters.
Keywords cannot be used as user defined names (identifiers).
For every open brace ({), there must be respective closing brace (}).
Every variable must be declared before it is used.
A C++ program consists of different sections that organize the code. These sections help in writing clear and structured programs.
Include Section – This is the first part of a C++ program where we add necessary libraries using #include. These libraries provide built-in functions (e.g., <iostream> for input/output).
Class Declaration – If the program uses classes, this section defines the class, its variables (data members), and function declarations (member functions).
Class Function Definitions – The actual code for the functions inside the class is written in this section.
Main Function (main()) – This is where the program execution starts. It may create objects of the class and call its functions.
Modular Approach in C++
Often, a C++ program is divided into three separate files:
Class Declaration File – Contains the structure of the class.
Class Definition File – Includes the actual function implementations.
Main Program File – Uses the class and executes the program.
This structure follows the Client-Server Model:
The class acts as the server (it provides functions and services).
The main program acts as the client (it requests services from the class).
One client can use multiple servers (classes), and one server (class) can serve multiple clients (programs).
This approach helps in organizing large programs efficiently and makes debugging and updates easier.
In C++, the process of creating, compiling, and linking a file involves several steps to transform source code into an executable program. Here’s an overview of each stage:
1. Creating the File:
Open Dev-C++: Start Dev-C++ from your desktop or start menu.
Create a New Project:
Go to File > New > Project....
Select Console Application and choose C++ as the language.
Name your project (e.g., HelloWorld) and select the location where you want to save it.
Click OK, and Dev-C++ will create a project folder with a template main.cpp file.
Write Your Code: If you don’t want to use the generated main.cpp, you can create a new .cpp file by selecting File > New > Source File. Then you can type or paste your code into the editor.
Simple C++ Program (Helloworld.cpp)
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
2. Compiling:
Compile the Code: To compile your code, click on the Compile button in the toolbar (the button with the hammer icon), or press F9.
Dev-C++ will automatically compile your source file into an object file (with a .o extension) and then link it to create the final executable.
3. Linking:
Linking is the process of combining object files (generated by the compiler) into a single executable file. In Dev-C++, the linking process is done automatically after compiling. Once you compile the source code, the IDE automatically generates an executable file and links it, so you don’t have to worry about running separate commands.
By default, the output executable will be located in the project directory (where you saved your project).
You can run the program directly from the IDE by clicking the Execute button (the green play button in the toolbar) or pressing Ctrl + F10.
4. Running the Program:
After successful compilation and linking, you can run your program directly by clicking the Run button or pressing Ctrl + F10.
The output console will appear, and you should see the program's output, like:
Hello, World!
This process simplifies C++ development by automatically handling the compilation and linking steps within the IDE.
Every C++ program is a collection of instructions, and each instruction is made up of individual units.
The smallest individual unit in a C++ program is called a token.
Tokens are the basic building blocks of a C++ program.
Every instruction in a C++ program is a collection of tokens.
Tokens are used to construct C++ programs and they are said to the basic building blocks of a c program
Tokens in a C++ program can include the following:
Keywords
Identifiers
Operators
Constants
Strings
In summary, a collection of all the keywords, identifiers, operators, special symbols, constants, strings, and data values in a C++ program are referred to as tokens.
keywords are special words with predefined meaning which already known to the compiler. Keywords are also known as reserved words in C++ programming language.
Properties of Keywords
All the keywords in C++ programming language are defined as lowercase letters so they must be use only in lowercase letters
Every keyword has a specific meaning, users can not change that meaning.
Keywords can not be used as user defined names like variable, functions, arrays, pointers etc...
Every keyword in represents something or specifies some kind of action to be performed by the compiler.
Identifier is a collection of characters which acts as name of variable, function, array, pointer, structure, label etc... In other words, Identifier is a user defined name of an entity to identify it uniquely during the program execution
Example
int marks;
char studentName[30];
Here, marks and studentName are identifiers.
Rules for Creating Identifiers
An identifier can contain letters (UPPERCASE or lowercase), numeric & Underscore symbol only.
An identifier should not start with numerical value. It can start with a letter or an underscore.
Identifiers are case sensitive.
A declared keyword cannot be used a variable name.
Constants (often referred to as literals) refer to fixed values that do not change during the execution of a program. constant can be of any datatype like integer, floating point, character, string and double etc.,
The following types of literals are available in C++.
Integer-Constants
Character-constants
Floating-constants
Strings-constants
Integer Constants
An integer constant can be a decimal integer or octal integer or hexa decimal integer. A decimal integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and hexa decimal value is prefixed with 'OX'.
Examples
125 ---> Decimal Integer Constant
O76 ---> Octal Integer Constant
OX3A ---> Hexa Decimal Integer Constant
Floating constants
A floating point constant must contain both integer and decimal parts. Some times it may also contain exponent part. When a floating point constant is represented in exponent form, the value must be suffixed with 'e' or 'E'.
Example
The floating point value 3.14 is represented as 3E-14 in exponent form.
Character constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum length of one character.
Example: 'A' , '2', '+'
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that are enclosed in double quotations.
String literal is by default (automatically) added with a special character ‘\0' which denotes the end of the string. Therefore the size of the string is increased by one character.
Example: "COMPUTER" will re-represented as "COMPUTER\0" in the memory and its size is 9 characters.
Variable is a name given to a memory location where we can store different values of same data type during the program execution.
Declaration Syntax:
datatype variableName;
Example: int a, float b, char name
Data types in programming specify the type of value that can be stored in a variable.
The memory size and the type of value that a variable can hold are determined by its data type.
In a C++ program, every variable, constant, or array must have a data type.
The data type specifies:
How much memory should be allocated.
The type of values to be stored in the variable, constant, or array.
The primary data types in C++ programming language are the basic data types. All the primary data types are already defined in the system. Primary data types are also called as Built-In data types. The following are the primary data types in C++ programming language.
Integer Data type
Floating Point Data type
Character Data type
void Data type
character—Keyword used is char
integer—Keyword used is int
floating-point—Keyword used is float
double precision floating point—Keyword used is double
Valueless—Keyword used is void.
Integer Data type:
Integer data type is a set of whole numbers. Every integer value does not have the decimal value.
We use the keyword "int" to represent integer data type in c++.
We use the keyword int to declare the variables and to specify return type of a function.
The integer data type is used with different type modifiers like short, long, signed and unsigned.
The following table provides complete details about integer data type.
Character Data type
Character data type is a set of characters enclosed in single quotations. The following table provides complete details about character data type.
Floating Point Data types:
Floating point data types are set of numbers with decimal value. Floating-point data types are used to define variables that can hold real numbers. Every floating point value must contain the decimal value.
The floating point data type has three variants...
float
double
long double
We use the keyword "float" to represent floating point data type and "double" to represent double data type in C++.
Both float and double are similar but they differ in number of decimal places.
The float value contains 6 decimal places whereas double value contains 10 decimal places. The following table provides complete details about floating point data types.
void Data type
The void data type means nothing or no value. Generally, void is used to specify a function which does not return any value. We also use the void data type to specify empty parameters of a function.
Declaration
Declaration introduces one or more variables within a program. Definition, on the other hand, directs the compiler to actually allocate memory for the variable. A declaration statement begins with the type, followed by the name of one or more variables. The general form is
data_type variable_name_1, variable_name_2, ..., variable_name_n;
Declaration of multiple variables of the same data types can be done in one statement.
For example,
int a; int b; int c;
can be rewritten as int a, b, c;
The above declaration tells to the compiler (32 bit compiler) that allocate 4 bytes of memory with the name a,b,c and allows only integer values into that memory location.
A special operator called sizeof will report the number of bytes of memory used by any data type or variable.
Operator is a symbol which is used to perform some particular action or operation to fulfill the specified task.
Operands: operands are the data on which the operators are going to perform the operation or the action.
The classifications of operators based on the number of operands involved are
(a) Unary Operator
(b) Binary Operator
(c) Ternary Operator
Unary Operator: - Unary operator will operators on only one operand.
Ex: +5, -3, ++2, ………
Binary Operator: - Binary operator will operators on two operands.
Ex: 5+4, 6-5, 6>5, 2X7, ……..
Ternary Operator: - Ternary operator will operators on three operands. It is also called as Conditional operators (?,:).
Another classification of operator is based on the type of operation being used are:
The arithmetic operators are used for performing the basic arithmetic operations like +, -, x, %.
Relational operators specify how the two operands are related with one another. It is used to compare two values. The relational operator returns either true or false. The different relation operators are.
Logical operators are used to perform logical operations on Boolean values (true/false).
Types of logical operators:
The truth table for logical operators are as follows:
The increment operator is used to increase the value of the variable by ‘1’ . This operator variable is denoted by ‘++’.
To decrease the value of the variable by ‘1’ the decrement operator is used and is denoted by ‘- -‘.
The Increment/Decrement operators are classified into two types (a) Pre (b) Post
Pre-Increment: In Pre-Increment, the value is first incremental and then the required operation or task is performed.
Syntax: ++ Operand
e.g.: ++a
Post-Increment: In post-increment, the required operation or task is performed and then the value of the variable is incremented.
Syntax: Operand ++
e.g.: a ++
Pre-Decrement: In Pre-Decrement we first decrease the value and then perform the actual specified value.
Syntax: -- Operand
e.g.: --a
Post-Decrement: - In post-decrement we first perform the task and then decrease the value of the variable by one.
Syntax: Operand --
e.g.: a--
This operator is used to assign the value to a variable. The value can be directly passed or indirectly passed through some other variable.
Syntax: Operand1= Operand2;
e.g.: x=5; a=b; etc..
There are some special assignment operators which are also called as short hand operators that reduce the number of micro–instructions.
These are exclusively used only with assignment operators, where the operand value, before and after the assignment operator will be same.
Syntax:
< Operand1> = <Operand1> arithmetic operator <Operand2>
<Operand1> arithmetic operator =<Operand2>
i) Comma Operator:
The comma operator is used to separate two different expressions. e.g.: - int a, b, c;
c = (a=10,b=20,a+b);
ii) Sizeof Operator:
The sizeof operator is used to return the no. of bytes the operand occupies in the memory. The operand may be a variable or a constant or a data type qualifier.
Syntax: sizeof(operand)
This operator is used to evaluate an expression based on true or false.
Syntax: (expression)? True Part : False Part;
Along with the above operators there are few more operators which are introduced in C++. They are listed below.
An expression is a combination of operands i.e., constants, variables and numbers connected by operators and parenthesis. For an instance, in the expression
A+B
A and B are operands and + is an operator.
Rules for formation of an expression:
A signed or unsigned constant or variable is an expression.
An expression connected by an operator to a variable or constant is an expression.
Two expressions connected by an operator is also an expression.\
Two operators should not occur in continuation.
Operator precedence is used to determine the order of operators evaluated in an expression. In C++ programming language every operator has precedence (priority). When there is more than one operator in an expression the operator with higher precedence is evaluated first and the operator with least precedence is evaluated last.
Statements are instructions given to the computer to perform any kind of action (e.g., data movement, decision making).
Statements form the smallest executable unit within a C++ program.
The flow of control refers to the process of controlling the execution sequence of statements in a program.
There are three types of statements in C++:
Conditional Statements: Used to make decisions in the program based on certain conditions.
Loop (or) Iterative Statements: Used to repeat a block of code multiple times.
Jump Statements: Used to alter the normal flow of control in a program (e.g., break, continue, goto).
Conditional / Decision Making Statements:
In C++ programming language, the program execution flow is, line by line from top to bottom. That means the c program is executed line by line from the main method. But this type of execution flow may not be suitable for all the program solutions. Sometimes, we make some decisions or we may skip the execution of one or more lines of code.
Decision making statements are the statements that are used to verify a given condition and decides whether a block of statements gets executed or not based on the condition result.
C++ provides the following statements for implementing the selection control structure If Statement
if statement
if statement
if else statement
nested if statement
if else if statement (if else ladder)
switch statement
In order to check a single condition we use “if statement” ,it will gives the output of the condition is true (or) correct.
Simple if statement is used when we have only one option that is executed or skipped based on a condition.
The if-else statement is used to verify a given condition and execute one of two blocks of statements based on the condition's result.
The if-else statement evaluates a specified condition:
If the condition is TRUE, it executes the True block.
If the condition is FALSE, it executes the False block.
The if-else statement is used when there are two options, and only one option needs to be executed based on whether the condition is TRUE or FALSE.
The if-else-if statement can be defined using any combination of simple if & if-else statements.
The switch statement compares a provided value (called switchValue) with the value associated with each option (called cases).
Each option (case) in the switch statement has a value associated with it.
The execution starts from the first case where the value matches the switchValue.
Switch Statement Flow:
Case Comparison: The switch statement compares the switchValue with the value of each case.
If a match is found, execution starts from that case.
If no match is found, the default case (if provided) is executed.
Break Statement:
The break statement is used to terminate the switch statement after a matching case is executed.
It is optional but commonly used to prevent the execution from continuing to the next cases.