Problem Solving Using C++ - Unit 1
Problem Solving Using C++ - Unit 1
I Semester BCA
Problem Solving using C++
Course Code: CAM12T Course Title: Problem Solving using C++
Course Contents
Unit-1
Introduction to Programming: Program development life cycle, Introduction to
Procedure Oriented Programming and Object-Oriented Programming (OOP)
paradigms, basic concepts of OOP, benefits and applications of OOP.
Introduction to C++: Overview of C++, Structure of C++ Program, Input-Output 11Hours
statements, Keywords, Identifiers, Constants, Variables, Data types, Operators,
Types of operators, Expressions, Precedence of Operators, Type Conversion,
Storage classes.
Unit-2
Unit-3
Derived Data Types: Arrays, Array Types, Strings, String Manipulation
Functions, Pointers, Pointer Arithmetic.
Managing Console, I/O Operations: C++ Stream, C++ Stream Classes,
Unformatted I/O Operations, Formatted Console I/O Operations, Managing Output
11Hours
withManipulators.
User Defined Data Type: Class Definition, Instance Variables, Member Methods,
Accessing Members, Access specifiers, this pointer, Friend Function,
Constructors,Types of Constructors, Destructor.
Unit-4
Polymorphism: Operator Overloading, Rules for Operator Overloading,
Overloading Unary and Binary Operators.
Inheritance: Inheritance, Types of Inheritance, Virtual Functions and Abstract
Classes. 11Hours
File Handling: Introduction To Files and File Handling, File Opening Modes, Classes
For File Stream Operations, File I/O Operations (Opening, Reading, Writing,
Append And Closing).
Reference Books:
1. Object-Oriented Programming With C++, By M. T. Somashekara, D. S. Guru, H.
S. Nagendraswamy, K. S. Manjunatha, PHI Learning Pvt. Ltd.
UNIT - 01
Introduction to C++: Overview of C++, Structure of C++ Program, Input-Output statements, Keywords,
Identifiers, Constants, Variables, Data types, Operators, Types of operators, Expressions, Precedence of
Operators, Type Conversion, Storage classes.
Introduction to Programming
Programming is the process of creating a set of instructions that a computer can follow to perform
specific tasks.
Programming refers to a technological process for telling a computer which tasks to perform in order to
solve problems.
It can be considered collaboration between humans and computers, in which humans create instructions for
a computer to follow (code) in a language computers can understand.
It involves writing code in a programming language to solve problems, automate tasks, or create
software applications.
Example: If you want a computer to calculate the sum of two numbers, programming involves writing
the steps (instructions) that tell the computer how to do this calculation.
1. Program: A program is a complete set of instructions written in a programming language that tells
the computer how to perform a specific task. It can be something simple, like adding two numbers, or
something complex, like a video game.
Example: A calculator app on your phone is a program. It takes input from the user (numbers and
operations), processes that input (performs the calculations), and then displays the result.
Example: Some programming languages include Python, C, C++, Java, and JavaScript. Each of these
languages has its own unique way of writing instructions, but they all serve the same purpose: to
communicate with the computer.
3. Instructions: Instructions are the individual steps or commands that make up a program. These are
the specific actions that the computer is told to perform, such as adding numbers, storing data, or
displaying text on the screen.
Example: In a program, an instruction might be something like cout<< ―Hello World"; which tells the
computer to display the text "Hello, World!" on the screen.
4. Software: Software is a collection of programs and data that work together to perform specific tasks
on a computer. It can be anything from operating systems like Windows or macOS to applications like
Microsoft Word, web browsers, or games.
Example: Microsoft Word is a piece of software that allows you to write, edit, and format documents. It
consists of multiple programs that handle different tasks, like opening files, saving your work, and
checking spelling.
Recap:
While hundreds of programming languages (if not thousands) exist, and there are many ways to classify
them, they typically can be grouped into five main categories:
Java
Pascal
BASIC
4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web content, or
supportprocesses in larger applications. Some common scripting languages include:
PHP
Ruby
Python
bash
Perl
Node.js
The Program Development Life Cycle (PDLC) is a step-by-step process used by developers to
create, test, and maintain software programs. It ensures that software is developed systematically and
efficiently, meeting the requirements and delivering a high-quality product.
It provides an organized plan for breaking down the task of program development into
manageable chunks, each of which must be completed before moving on to the next phase.
Steps involved:
Understand the problem: The developer or team works with stakeholders (e.g., users, business owners)
to understand the exact requirements. For example, if you're building software for an online store, you
need to understand what features the store needs (like managing products, processing orders, etc.).
Define program goals: Clearly outline what the software is supposed to achieve. For instance, the goal
could be to allow users to browse and purchase products, or to automate stock management.
Identify inputs and outputs: Determine what data the program will receive (input) and what it should
produce (output). For example, in a billing system, the input could be item details and customer info, and
the output would be a generated invoice.
Constraints and assumptions: Identify any limitations or rules the program needs to follow. For
example, the system might need to handle a certain number of users or transactions per day.
Program design starts by focusing on the main goal the program needs to achieve and then
breaking it down into smaller, manageable parts. This method is called top-bottom design or
modular programming. First, you identify the main task or activity the program must perform. Then,
you divide this main task into smaller sections called modules. Each module handles a specific part of
the program's work. To plan how each module will work, programmers create a simple diagram or
plan using design tools to show how the module will complete its assigned task. And also we
determine the requirements like variables, functions, etc. to solve the problem. That means we gather
the required resources to solve the problem defined in the problem definition phase. We also
determine the bounds of the solution.
Depending on the module, people use different types of program design tools. The five major
ones are algorithms, structure charts, flowcharts, decision tables, and pseudocode.
Algorithms: An algorithm is a step-by-step procedure used to solve a problem in the easiest way
possible. An algorithm is an exact list of instructions and can be found in everyday life, not just in
software engineering.
Structure charts: A structure chart looks at the top-down design of the program and breaks it into the
smallest functional modules. It also describes each module‘s function and sub-function in detail.
Flowcharts: A flowchart is a diagram showing the logic of the program. It can also be considered a
pictorial representation of an algorithm. Each step of the algorithm is represented in the form of various
shapes of boxes, with the logical flow indicated by interconnecting arrows.
Decision tables: A decision table is a visual representation that specifies which actions to do based on
given conditions. It is divided into four parts by two horizontal and two vertical lines. Software
engineers and product teams use it to settle different combinations of inputs with their corresponding
outputs.
Pseudocode: It‘s informative text or annotations written in plain English and used to represent an
implementation of algorithms. Since it has no syntax, it can‘t be compiled or interpreted by a computer.
Steps involved:
Write the code: Developers write the program‘s source code based on the design plan. They translate
algorithms, flowcharts, and pseudocode into the actual programming language.
Follow coding standards: It‘s important to follow best practices and coding standards to ensure the
code is readable, maintainable, and efficient. This includes using meaningful variable names, comments,
and consistent formatting.
Modular coding: The program is usually written in modules or functions. Each module handles a
specific task, making it easier to debug and test.
Error handling: Include mechanisms to deal with potential errors (e.g., input validation, exception
handling) to prevent the program from crashing during use.
Debugging: This is the process of finding and fixing errors (bugs) in the program. Common types of
bugs include:
Types of documentation:
Technical documentation: This is for developers and includes details about the program‘s code,
structure, algorithms, and database design. It helps future developers understand how the program was
built so they can maintain or modify it if needed.
User documentation: This is for the end-users, explaining how to install, operate, and troubleshoot the
software. It‘s often written in a simple language and includes step-by-step instructions with examples or
screenshots.
Types of maintenance:
Corrective maintenance: Fixing errors or bugs that were not caught during testing.
Adaptive maintenance: Updating the software to work with new environments (e.g., new operating
systems or hardware).
Perfective maintenance: Improving the performance or adding new features based on user feedback or
new business needs.
Preventive maintenance: Making changes to improve the software‘s future maintainability and
reliability, even if no current problems exist.
Example for PDLC: Developing a library management system for a school. This is a system that
helps manage the books, track borrowing and returning, and keep records of students and books.
1. Problem Definition: The library needs software to manage books, keep track of which student
borrowed which book, and show when the books are due for return. The goal is to reduce manual work
and improve accuracy in record-keeping.
2. Program Design: The program is broken into different tasks: book cataloging, student records,
borrowing/returning books, and overdue reminders. Each task will be handled by a separate module. For
instance, the borrowing module will track which student borrowed which book.
3. Coding: The programmer writes the code to implement the design. The book cataloging module will
allow the librarian to add, update, or remove books from the system. The borrowing module will update
the system when a student borrows or returns a book.
4. Testing and Debugging: The library management system is tested to ensure it works properly. For
example, when a book is borrowed, the system should show that it's no longer available for others until it
is returned.
5. Documentation: User documentation is created for the librarian, explaining how to use the system to
add books, register students, and manage borrowings. Technical documentation is also written for future
developers.
6. Maintenance: After the system is in use, updates might be needed, like adding a new feature for e-
books or fixing a bug that prevents correct tracking of overdue books.
Local Variable: A local variable is a variable that is declared in the main structure of a method and
is limited to the local scope it is given. The local variable can only be used in the method it is defined
in, and if it were to be used outside the defined method, the code will cease to work.
Global Variable: A global variable is a variable which is declared outside every other function
defined in the code. Due to this, global variables can be used in all functions, unlike a local variable.
Modularity: Modularity is when two dissimilar systems have two different tasks at hand but are
grouped together to conclude a larger task first. Every group of systems then would have its owntasks
finished one after the other until all tasks are complete.
Parameter Passing: Parameter Passing is a mechanism used to pass parameters to functions,
subroutines or procedures. Parameter Passing can be done through ‗pass by value‘, ‗pass by
reference‘, ‗pass by result‘, ‗pass by value-result‘ and ‗pass by the name‘.
Disadvantages:
// Function to add two numbers It is a comment, it will not execute. It is for our reference
int adding(int a, int b)
{
return a + b;
}
void main()
{
int num1 = 5, num2 = 10, result;
clrscr();
getch();
}
Object-Oriented Programming(OOP)
Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of methods. In
object-oriented programming, computer programs are designed using the concept of objects that
interact with the real world. Object-oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also determine their types.
getch();
}
divided into small parts called functions. is divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows
approach. a bottom-up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance. data hiding and inheritance is used.
In procedural programming, the function is In object-oriented programming, data is more
more important than the data. important than function.
Procedural programming is used for designing Object-oriented programming is used for
medium-sized programs. designing large and complex programs.
Code reusability absent in procedural Code reusability present in object-oriented
programming, programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
1. Objects
Objects are the basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program must handle.
Objects are basic building blocks for designing programs.
It is called instance of class (occurrence /copy of class).
Object is a collection of data member and member functions..
GM – MIT Degree College, MITM Campus, Mysore 14
Problem Solving Using C++ Unit 1
Each object is identified by unique name and it must be a member of particular class.
Object takes the space in the memory.
2. Class
A class is a blueprint/template for creating objects.
Class is a way of grouping of objects having similar characteristics.
In other words, a group of objects that share common properties for data part and some
program part are collectively called as class.
Once the class is created, any number of objects can be created for that particular class.
Classes are user defined datatype.
When the class is created, no memory is allocated. But when it is instantiated then the memory is
allocated. Instantiation is the process of creating a real object from a class.
Data members are the data variables that are declared inside a class and hold the state of the class. They
represent the attributes or properties of the class.
Member functions are the functions used to manipulate these variables and that are declared inside a
class and operate on the data members of that class. They define the behavior or actions that the class
can perform.
Together these data members and member functions defines the properties and behavior of the
objects in a Class.
In the below example, breed, size, age, color are data members. Eat(), sleep(), sit(), run() are member
functions.
3. Data Abstraction
Abstraction is about hiding complex implementation details and showing only the essential features of
an object.
It hides the unwanted information and represents only the necessary information.
In other words, it refers to the act of
representing essential features without
including the back ground details or
explanations.
Example: Imagine you are using an ATM
machine to check your account balance. The
ATM provides a user-friendly interface with
options like "Check Balance," "Withdraw
Money," and "Deposit Funds." You interact
with the ATM through this interface without
needing to understand the complex processes
behind the scenes.
PIN and selecting options from the menu. The underlying details—such as how the ATM communicates
with the bank's servers, how the transactions are processed, and how data is securely transmitted—are
hidden from you. This abstraction simplifies your experience by providing a straightforward and
consistent interface, while the complexities of data handling and security are managed by the ATM's
internal systems.
By hiding these complex details and showing only the necessary options, the ATM machine
demonstrates the principle of data abstraction. It allows you to perform financial transactions efficiently
without needing to understand the intricate workings behind the scenes.
4. Data Encapsulation
Encapsulation is about bundling/ wrapping up of the data (properties) and methods (functions) that
operate on the data into a single unit called a class.
The data is not accessible to the outside world and only those functions which are wrapped in the
class can access it. These functions provide the interface between the objects data and the program.
For example, you might have a BankAccount class where the balance is private and can only be
accessed or modified through methods like deposit() and withdraw().
5. Inheritance
Inheritance is the process by which objects of one class acquire the properties
of another class.
Inheritance allows one class (child class) to inherit properties and methods
from another class (parent class).
In the concept of inheritance provides the idea of reusablity. This mean that
we can add additional features to an existing class with out modifying it.
The existed class is called as base class or parent class or super class. The
Example: Imagine you have a parent class called Animal that defines basic attributes and methods
common to all animals, such as name and eat(). Now, you want to create a specific type of animal, like a
Dog. Instead of rewriting the code for the common attributes and methods, you create a Dog class that
inherits from the Animal class. The Dog class automatically has the name and eat( ) methods from the
Animal class, but you can also add new attributes, like breed, and methods, like bark( ). This way, the
Dog class extends the functionality of the Animal class by adding its own unique features while reusing
the common functionality provided by its parent class.
6. Polymorphism
Polymorphism means the ability to take more than one form. An
operation may exhibit different instance.
The behaviour depends upon the type of data used in the
operation.
C++ supports operator overloading and function overloading.
o Operator Overloading: The process of making an operator
exhibit different behaviors in different instances is known as
operator overloading.
o Function Overloading: Function overloading is using a single
function name to perform different types of tasks. Polymorphism
is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some
integers, sometimes there are 2 integers, and sometimes there are
3 integers. We can write the Addition Method with the same name
having different parameters, the concerned method will be called
according to parameters.
7. Dynamic binding
Dynamic binding refers to the linking of a procedure call to the code to the executed in response to
the call.
Dynamic binding means the code associated with a given procedure call is not known untill the time
8. Message Passing
It is a mechanism that allows objects to communicate and interact with each other by sending messages.
An object oriented program consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will invoke a function
(procedure) in the receiving object that generates the desired result. Message passing involves
specifying the name of the object, the name of the function (message) and information to be sent.
Example: Imagine you have a whiteboard in an office where you leave notes(messages) for different
team members. If you write ―Send the report‖ on the board, the team member who handles reports will
see it and act on it. If you write ―Call the client,‖ the person in charge of phone calls will handle that
task. Each team member looks at the note and does what is needed based on the message. This way,
messages are passed to the right person, and they perform the appropriate action.
Benefits of OOP
GM – MIT Degree College, MITM Campus, Mysore 19
Problem Solving Using C++ Unit 1
1. Security (Encapsulation): In OOP, encapsulation is the concept of bundling data (variables) and
methods (functions) that operate on the data into a single unit called a class. This ensures that the data is
protected from being accessed or modified by external functions, enhancing security.
Example: Think of a banking system. Your account balance (data) is private and cannot be directly
changed by anyone. Instead, you can only update it through methods like deposit or withdraw. This
prevents unauthorized access or changes to your account balance.
2. Reusability (Inheritance): Through inheritance, you can create a new class based on an existing
class, inheriting its properties and methods. This saves time and effort because you don‘t need to rewrite
the same code for similar functionalities.
Example: Suppose you have a Vehicle class with properties like wheels, engine, and methods like
start(). You can create a Car class that inherits from Vehicle, and automatically gains these properties
and methods. You can then add specific properties like airbags to the Car class without rewriting the
basic vehicle features.
3. Effective Communication (Message Passing): Objects in OOP communicate with each other
through message passing, which means that they send messages (call methods) to request actions or
share information. This makes the interaction between objects simpler and more structured.
Example: In a messaging app, when you send a message to a friend, your User object might call a
sendMessage() method on your friend's User object. This is a clear and defined way of how objects
communicate in an OOP system.
4. Model Real-World Effectively: OOP allows you to model real-world objects as classes in your
program, creating a direct correspondence between the real world and your software. This makes the
software more intuitive and easier to design.
Example: Consider an e-commerce platform. You can create a Product class, a Customer class, and an
Order class. Each class can have attributes and methods that directly map to the real-world objects and
their behaviors, like a customer adding a product to their cart.
5. Suitable for Developing Complex Software: OOP is ideal for developing complex software systems
because it allows for better management of complexity through features like inheritance, encapsulation,
and polymorphism. These features help in organizing and reducing the complexity of large codebases.
Example: In large software applications like enterprise resource planning (ERP) systems, different
modules like inventory, finance, and human resources can be modeled as separate classes, with shared
properties inherited from a base class. This reduces redundancy and keeps the system organized.
6. Easy to Upgrade (Bottom-Up Approach): OOP often employs a bottom-up approach in system
development, meaning you start by creating small, manageable objects or classes and then combine them
to build more complex systems. This makes it easier to upgrade or expand the system over time.
Example: If you're developing a gaming application, you might first create basic classes like Character,
Weapon, and Environment. Later, you can add new features or classes like MagicCharacter or
AdvancedWeapon without disrupting the existing system.
7. Additional Power for Operator (Operator Overloading): OOP allows operators to work differently
based on the type of data they are working with through a concept called operator overloading. This
gives more flexibility and power to operators in the program.
Example: In a graphics software, you might have a Point class representing coordinates. You can
overload the + operator to allow adding two Point objects together, resulting in a new point that
represents their sum. For example, Point(1, 2) + Point(3, 4) might result in Point(4, 6).
8. Easy to Decompose Complicated Work: OOP makes it easier to break down complex problems into
smaller, more manageable parts by focusing on objects rather than functions. This modular approach
simplifies the development and maintenance process.
Example: In a simulation of a traffic system, you could break down the system into objects like Car,
TrafficLight, and Pedestrian. Each object handles its own behavior, making the overall system easier to
develop and manage.
Applications of OOP
1. Object-Oriented Database: Object-oriented databases store data in the form of objects, similar to
how data is represented in OOP. This allows for a more natural and direct mapping between objects in a
program and the data in the database.
Example: A content management system (CMS) for a website may use an object-oriented database to
store and retrieve web pages, user data, and multimedia content, where each entity is represented as an
object.
2. Computer Graphics: OOP is widely used in computer graphics for managing and manipulating
complex graphical elements. Objects can represent graphical entities like shapes, colors, and
transformations.
Example: In video game development, characters, environments, and even effects like lighting and
shadows are implemented as objects, making it easier to manage and render them efficiently.
3. Real-Time Systems: Real-time systems require immediate or timely responses to inputs. OOP helps
in modeling these systems where each real-time task can be represented as an object with specific
behaviors.
Example: An anti-lock braking system (ABS) in a car uses real-time processing to prevent wheel lock
during braking. Each component of the system, like the sensors and actuators, can be represented as
objects, interacting in real-time to ensure safety.
Example: In a modern web server, multiple client requests can be handled simultaneously. Each request
can be treated as an object running in parallel threads, allowing efficient and concurrent processing.
5. System Programs: System programs like compilers, interpreters, and operating systems often use
OOP to manage the complexity of these large systems. OOP helps in modularizing the components of
the system.
Example: The Java Virtual Machine (JVM) uses OOP principles to manage memory, interpret bytecode,
and execute programs, making it easier to port Java applications across different platforms.
6. Artificial Intelligence (AI) and Expert Systems: OOP allows the modeling of complex AI systems
where each component of the AI can be represented as an object with its own data and behavior.
Example: In a chess-playing AI, different elements like the board, pieces, and game rules are
represented as objects, allowing the AI to evaluate and make moves based on the current state of the
game.
Example: In designing a car using CAD software, different parts of the car like the engine, body, and
wheels are treated as objects. These objects can be modified and assembled in the software, reflecting
changes in real-time.
8. Neural Networks:Neural networks in machine learning are often implemented using OOP principles,
where each neuron or layer in the network is represented as an object.
Example: In a facial recognition system, each layer of the neural network can be an object that processes
the image data, extracting features and making predictions based on learned patterns.
Introduction to C++
In 1980s, the C language was playing a dominant role. But when the software size started increasing, it
could not scale up to meet the requirements. Then, C++ was developed by Bjarne Stroustrup at AT
and T Bell Labs in the early 1980’s (1979) as an enhancement to the C language and originally named
C with Classes but later it was renamed C++ in 1983.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-
level language features.
C++ was developed as an extension of C, and both languages have almost the same syntax. The main
difference between C and C++ is that C++ support classes and objects, while C does not. C++ is a
superset of C.
The C programming language was developed by Dennis Ritchie at Bell Labs in the early 1970s. It was
initially designed to create system software for the Unix operating system, which was also being
developed at Bell Labs.
Features of C++:
Advantages of C++
GM – MIT Degree College, MITM Campus, Mysore 24
Problem Solving Using C++ Unit 1
1. Performance: C++ is a compiled language, which means that its code is compiled into machine-
readable code, making it one of the fastest programming languages.
2. Object-Oriented Programming: C++ supports object-oriented programming, which makes it easier to
write and maintain large, complex applications.
3. Standard Template Library (STL): The STL provides a wide range of algorithms and data structures
for working with data, making it easier to write efficient and effective code.
4. Portability: C++ code can be compiled on different platforms with minimal changes, making it a
portable language.
5. Flexibility: C++ supports both low-level (close to hardware) and high-level programming, making it
suitable for a wide range of applications.
Disadvantages of C++:
1. Complexity: C++ has a steep learning curve, especially for beginners, due to its complex syntax,
features, and concepts like pointers, memory management, and multiple inheritance.
2. Verbose Syntax: C++ has a verbose syntax, which can make code longer and more difficult to read and
maintain.
3. Error-Prone: C++ provides low-level access to system resources, which can lead to subtle errors that
are difficult to detect and fix.
4. Long Compilation Times: The compilation process in C++ can be slow, especially for large programs,
due to the complexity of the language and its features.
Applications of C++:
1. System Software: Operating systems like Windows, Linux, and macOS use C++ for their development.
2. Game Development: C++ is widely used in game development due to its high performance and ability
to manage system resources efficiently. Game engines like Unreal Engine are built using C++.
3. Database Management Systems: Databases like MySQL and PostgreSQL have components written in
C++.
4. GUI Applications: Desktop applications with graphical user interfaces, such as Adobe Photoshop, are
often developed using C++.
5. Compilers: Many compilers and interpreters for other programming languages (including C++ itself)
are written in C++.
6. Web Browsers: C++ is used in developing web browsers like Google Chrome and Mozilla Firefox,
particularly for performance-critical parts like rendering engines.
documentation
include files
classes declaration and definition
macros definition
global variables declaration
int main(void)
{
Local variables
Statements
Return 0;
}
Documentation consists of comment lines mentioning the name, input, output etc. For example, //
program to swap two numbers. The comments lines are ignored during compilation.
1. Single line comments: Single line comments should be written in this form.
// abc
Comment should be written only in single line.
2. Multiline comments: Multiline comments should be written in this form
.
/* Write a program to swap two numbers Using
temporary variable */
Include files is used to specify the files which are to be included as the part of the program. C++
compilers are provided with a standard library, which consist of a large number of commonly used
built in functions. In order to use these functions, we need to include some files as the part of our
program. These files are generally called as header files.
Example: #include<iostream.h>
GM – MIT Degree College, MITM Campus, Mysore 26
Problem Solving Using C++ Unit 1
Classes declaration and definition is to declare and define the classes that are used by the program.
Macros definition is to assign symbolic names to constants and define macros. The preprocessor
directive #define is used for this purpose.
Example: #define PI 3.14
NOTE: Commands written by using # are called pre-processor directives. Before C program is
compiled by the compiler, source program is processed by Pre-processor directives. As the name
suggests, Preprocessors are programs that process our source code before compilation.
All of these preprocessor directives begin with a ‗#‘ (hash) symbol. Examples of some
preprocessor directives are: #include, #define, etc.
Global variables are those which are required to be accessed by all the functions defined after their
declaration. So, the variables declared before the main() can be accessed by all the functions which
follow their declaration.
All the above parts are optional. They can be used only when they are required. They can appear in
any order. Then comes the function main(). Every C++ program will have a one main(), this is where the
execution of a program starts from and ends with.
The Opening brace { of the main( ) marks the physical beginning of the program and the closing
brace } marks the physical end of the program. The statements enclosed within the opening brace and
the closing brace form the body of the main( ). It consists of two parts: 1. Local Variables declaration,
where all the variables, which are accessed only by the main( ) are declared and
2. Statements, which includes the executable statements.
After the closing brace of the main( ), user defined functions ,if any, can be defined. The word int
before the main( ) indicates that the main( ) returns an int value to its caller, the underlying operating
system and the word void within the parentheses indicate that the main( ) does not require any inputs
from the calling programs.
In C++ input and output are performed in the form of a sequence of bytes or more commonly
knownas streams.
Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the
main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device
(display screen) then this process is called output.
1. iostream: iostream stands for standard input-output stream. This header file contains definitions of
objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files areused
for manipulating streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle the data
being read from a file as input or data being written into the file as output.
Standard output stream (cout):
The name cout stands for ‗character output‘ or ‗console output‘. Usually the standard output device is
the display screen. The C++ cout statement is the instance of the ostream class. It is used to produce
output on the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion operator
(<<).
Example:
#include <iostream.h>
#include <conio.h>
void main()
{
cout << " Hello World";
}
Output: Hello World
Standard input stream (cin): The name cin stands for ‗character input‘ or ‗console input‘. Usually
the input device in a computer is the keyboard. C++ cin statement is the instance of the class
istream and is used toread input from the standard input device which is usually a keyboard.
The extraction operator (>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
Example:
#include <iostream.h>
#include <conio.h>
Output:
void main()
{ Enter your age: 18
int age; Your age is: 18
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
getch( );
}
NOTE: cout and cin are generally understood to refer to "Console Output" and "Console Input"
because they work specifically with the console (terminal) for displaying output and receiving input in
C++. The word "console" is more commonly used in modern interpretations.
Historically, some early references or resources referred to cout as "Character Output" and cin as
"Character Input" due to their handling of textual characters (strings, numbers, etc.) when performing
input and output operations.
Keywords
keywords are those words of C++ which have predefined meaning assigned by the C + + languoage.
They should not be used for any other purpose other than the purpose for which they are meant. The
keywords are also called reserved words.
Some of the keywords are as follows: int, float, class, return, void, char, double, private, public,
protected etc
There are 95 keywords reserved in C++. Some of the main Keywords are:
break try catch char class const continue
default delete auto else friend for float
long new operator private protected public return
short sizeof static this typedef enum throw
mutable struct case register switch and or
namespace static_cast goto not xor bool do
double int unsigned void virtual union while
Identifiers
The identifier is one which is used for elements like variables constants are in its functions
names etc. In C++, entities like variables, functions, classes, or structs must be given unique names within the
GM – MIT Degree College, MITM Campus, Mysore 30
Problem Solving Using C++ Unit 1
program so that they can be uniquely identified. The unique names given to these entities are known as
identifiers.
It is recommended to choose valid and relevant names of identifiers to write readable and
maintainable programs. Keywords cannot be used as an identifier because they are reserved words to
do specific tasks.
There are a few rules must be followed while constructing a valid identifiers. They are
An identifier can have maximum 31 characters. The permissible characters in an identifier include
letters digits and an optional underscore symbol
It should start with a letter
Special characters other than underscore or not permitted
It should not be a keyword. For example, string, int, class, struct, etc.
NOTE: As C++ is a case-sensitive language so identifiers such as ‗first_name‘ and
‗First_name‘ aredifferent entities.
Variables : Variables are a name given to identify the specific program elements. It is the basic
unit of storage in a program.
All the variable names must begin with a letter of the alphabet or an underscore(_).
GM – MIT Degree College, MITM Campus, Mysore 31
Problem Solving Using C++ Unit 1
We cannot used C++ keyword (for ex float, double, class) as a variable name.
Declaration of Variables
All the variables must be declared before they are used in a C++ program. The purpose of declaring
variables is to reserve the amount of memory required for these variables.
A data type specifies the type of data that a variable an store such as integer,
floating, character etc. Data types specify the size and types of values to be stored.
However, storage representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical on all machines.
GM – MIT Degree College, MITM Campus, Mysore 32
Problem Solving Using C++ Unit 1
All variables use data type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data they can
store. Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared. Every data type requires a different
amount of memory.
1. Primitive Data Types: These data types are built-in or predefined data types and
can be useddirectly by the user to declare variables. example: int, char, float, bool, etc.
Primitive data types available in C++ are:
Integer (int)
Character (char)
Boolean (bool)
Floating Point (float)
Double Floating Point (double)
Valueless or Void (void)
Size and Range of Primary Data Types:
Modifiers: Modifiers are the keywords in C++ which either increase or decrease the size of basic
data type. Also, it makes the variable to represent only positive or both positive and negative
numbers. It specifies the amount of memory space to be allocated for a variable. Modifiers are
prefixed with basic data types to modify the memory allocated for the variable.
Syntax: modifier_name datatype_name variable_name;
Example: long int x;
2. Derived Data Types: Derived data types that are derived from the primitive or built-in data
types. It is an extension of the fundamental data type.
Reference: An alternative name (nickname) for an existing variable, allowing direct access to its value without
creating a new copy.
Example: int y = 20; int& ref = y;
3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by the user
itself. Like, defining a class in C++ or a structure. Data types created by the programmer that represent real-
world objects or concepts, using a combination of basic data types and operations is called User-Defined Data
Types. C++ provides the following user-defined data types:
Class: A blueprint for creating objects that can contain both data (attributes) and functions (methods).
Structure: A user-defined data type that groups different data types into a single unit.
Union: A user-defined data type that allows storing different data types in the same memory location,
but only one at a time.
Enumeration: A user-defined type that assigns names to integral constants, making code easier to read.
typedef: A keyword used to create an alias for an existing data type to simplify code.
Operators in C++:
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. It instructs the computer to perform the specified manipulations over the data.
Operators cannot be used in isolation or solely. They have to be used in combination with
either variables or constants or with combination of variables and constants. When used in
combination they are set to form what are called expressions and expression.
An expression in C++ is a combination of variables or constants and operators conforming to
the syntax rules of the language.
The variables are constants used with an operator are called operands. Depending on the
operator used, the expressions are further classified into arithmetic expressions, relational
expressions, logical expressions and so on.
An operator operates the operands. For example, int c = a + b;
Here, ‗+‘ is the addition operator. ‗a‘ and ‗b‘ are the operands that are being ‗added‘.
1. Unary Operators
2. Binary Operators
3. Ternary Operators
1. Unary Operators: A unary operator is an operator in programming that works with only one operand (a
single value or variable). It performs an operation on that single operand and returns a result. It acts upon one
(single) operand.
2. Binary operators: A binary operator is an operator that requires two operands to perform an
operation. It operates on the two values or variables and returns a result. Most of the operators we use
in programming are binary operators. It acts upon two operands. The binary operators are as follows:
i. Arithmetic Operators
These operators are used to perform arithmetic or mathematical operations on the operands. For
GM – MIT Degree College, MITM Campus, Mysore 36
Problem Solving Using C++ Unit 1
example, ‗+‘ is used for addition, ‗-‗ is used for subtraction ‗*‘ is used for multiplication, etc. An
arithmetic expression is the one which comprises arithmetic operators and variables or constants.
Symbol Name Description Example
int a = 3, b = 6;
+ Addition Adds two operands
int c = a+b; // c = 9
int a = 9, b = 6;
– Subtracti Subtracts second operand from the first
on operand int c = a-b; // c = 3
int a = 3, b = 6;
* Multiplic Multiplies two operands
int c = a*b; // c = 18
ation
int a = 12, b = 6;
/ Division Divides first operand by the second operand
int c = a/b; // c = 2
int a = 8, b = 6;
% Modulo Returns the remainder an integer division
int c = a%b; // c = 2
ii.Relational Operators: These operators are used for the comparison of the values of two operands.
A relational expression is of the form operand1 operator operand2, where operator is any relational
operator operand1 and operand2 are variables are constants or combination of both, which are being
compared. The value of a relational expression is C + + is 1 or 0. The 1 indicates that the condition is
true and 0 indicates that the condition is false. A relational expression is also called a conditional
expression or a Boolean expression.
int a = 3, b = 6;
== Is Equal Checks if both operands are equal
To a==b; // returns false
These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.
Truth table:
Binary Representation:
2: 0000 0010
3: 0000 0011
Example:
Operation Calculation Result
0000 0010 (a =
2)
Bitwise &
2
AND 0000 0011 (b =
3)
= 0000 0010
2 (0000 0010)
Bitwise
|
OR 1
3 (0000 0011)
= 0000 0011
Left Shift 2 (0000 0010)
<< 1 4
= 0000 0100
Right
2 (0000 0010)
Shift
>> 1 1
= 0000 0001
Bitwise
~ 3 (0000
NOT
0011) -4
= 1111 1100
v.Assignment Operators
These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the
compiler will raise an error. The operators +=, -=, *=, /=, %= are called shorthand operators.
Symbol Name Description Example
Assigns the value on the right to the int a = 2;
= Assignment Operator
variable on the left // a = 2
First adds the current value of the
Add and Assignment Operator variable on left to the value on int a = 2, b = 4;
+=
the right and then assigns the a+=b; // a = 6
result to the variable on the left
First subtracts the value on the right
Subtract and Assignment from the current value of the variable int a = 2, b = 4;
-=
Operator on left and then assign the result to a-=b; // a = -2
the variable on the left
First multiplies the current value of
Multiply and Assignment the variable on left to the value on int a = 2, b = 4;
*=
Operator the right and then assign the result a*=b; // a = 8
to
the variable on the left
First divides the current value of the
Divide and Assignment variable on left by the value on the int a = 4, b = 2;
/=
Operator right and then assign the result to the a /=b; // a = 2
variable on the left
Example:
#include <iostream.h>
#include<conio.h>
void main( )
{
int a = 10, b = 20, max; max = a > b ? a : b;
cout << "Maximum value = " << max;
}
Output:
Maximum value = 20
Expressions
An expression is a sequence of operators and their operands, that specifies a computation. An
expression is a combination of operators, constants and variables. An expression may consist of one
or more operands, and zero or more operators to produce a value.
Examples:
1. a+b
2. (a-b)*c
3. 2+(a/b)
4. (a+b) / (x+y)
Precedence of Operators:
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.
Type Conversion
Type conversion is the process that converts the predefined data type of one variable
into an appropriate data type. The main idea behind type conversion is to convert two different
data type variables into a single data type to solve mathematical and logical expressions easily
without any data loss. This can be done either implicitly or explicitly, depending on how the
conversion occurs. There are two types of type conversion: Implicit Type Conversion and
Explicit Type Conversion
1. Implicit Type Conversion: The implicit type conversion is the type of conversion done
automatically by the compiler without any human effort. It means an implicit conversion
automatically converts one data type into another type based on some predefined rules of the
C++ compiler. Hence, it is also known as the automatic type conversion. All the data types of
the variables are upgraded to the data type of the variable with largest data type.
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example for implicit type conversion:
#include <iostream.h>
#include<conio.h>
void main( )
{
// assign the integer value
int num1 = 25; Output:
clrscr( );
The value of num1 is: 25
// declare a float variable The value of num2 is: 25
float num2;
getch( );
}
2. Explicit Type Conversion: This process is also called type casting and it is user-defined. Here
the user can typecast the result to make it of a particular data type. Conversions that
require user intervention to change the data type of one variable to another.
In other words, an explicit conversion allows the programmer to manually changes or
typecasts the data type from one variable to another type.
Generally, we force the explicit type conversion to convert data from one type to another
because it does not follow the implicit conversion rule.
The explicit type conversion is divided into two ways:
1. Explicit conversion using the assignment operator
2. Explicit conversion using the cast operator
a. Converting by assignment: This is done by explicitly defining the required type in front of
the expression in parenthesis. This can be also considered as forceful casting.
Example: Program to convert one data type into another using the assignment operator
#include <iostream.h>
#include<conio.h>
void main( )
{
// initialize an int variable
int num1 = 25;
clrscr( );
Output:
// declare a float variable
float num2; The value of num1 is: 25
The value of num2 is: 25.0
// convert data type from int to float
num2 = (float) num1;
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
getch( );
}
b. Conversion using Cast operator: A Cast operator is an unary operator which forces one
data type to be converted into another data type. C++ supports four types of casting:
i. Static Cast
ii. Dynamic Cast
iii. Const Cast
iv. Reinterpret Cast
i. Static Cast: This is used when you know the type of data at compile time. It's the most basic
cast and is commonly used to convert between related types (like from an integer to a float).
Example:
#include <iostream.h>
#include <conio.h>
void main( )
{
int num = 10; Output:
clrscr( );
Integer: 10 Converted to
float decimal = static_cast<float>(num); // Convert int to float Float: 10.0
getch( );
}
ii. Dynamic Cast: This is used for safely converting pointers or references in an inheritance
hierarchy. It checks at runtime if the conversion is valid (used mainly with polymorphism).
Example:
iii. Const Cast: This is used to remove the "const" qualifier from a variable. It allows you to
modify a value that was initially constant.
Example:
iv. Reinterpret Cast: This is a low-level cast used for converting one pointer type to another,
even if they are unrelated. It doesn't check for compatibility, so it's risky.
Example:
Note: Each cast operator has its own use cases and should be chosen based on the
situation to ensure safe and correct conversions.
Storage Classes:
Syntax: To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;
Example:
void example()
{
auto x = 10; // 'x' is inferred as an int
auto y = 3.14; // 'y' is inferred as a double
}
// In file2.cpp
extern int num; // Refers to 'num' in file1.cpp
count++;
The mutable storage class allows a member of an object to be modified even if the
object itself is declared as const. Normally, a const object cannot modify its data members, but
a mutable variable is an exception to this rule. For example, a class might have a mutable int x;,
which can be modified within a const function.
Example:
class Test
{
mutable int x;
public:
Test() : x(0)
{
}
void modify( ) const
{
GM - MIT Degree College, MITM Campus, Mysore 47
Problem Solving using C++ Unit 1