0% found this document useful (0 votes)
13 views323 pages

1: Problem Solving, Algorithm & Flowchart

The document provides an overview of problem-solving and programming using C++, focusing on algorithms, flowcharts, and the C++ programming language itself. It outlines the Program Development Life Cycle (PDLC), detailing stages from problem definition to maintenance, and explains the characteristics, advantages, and disadvantages of algorithms and flowcharts. Additionally, it introduces C++ features, program structure, execution steps, character sets, and tokens.

Uploaded by

Divya R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views323 pages

1: Problem Solving, Algorithm & Flowchart

The document provides an overview of problem-solving and programming using C++, focusing on algorithms, flowcharts, and the C++ programming language itself. It outlines the Program Development Life Cycle (PDLC), detailing stages from problem definition to maintenance, and explains the characteristics, advantages, and disadvantages of algorithms and flowcharts. Additionally, it introduces C++ features, program structure, execution steps, character sets, and tokens.

Uploaded by

Divya R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 1: PROBLEM SOLVING, ALGORITHM & FLOWCHART

1.1 PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)


1.2 ALGORITHM
1.2.1 ADVANTAGES OF ALGORITHM
1.2.2 DISADVANTAGES OF ALGORITHM
1.3 FLOWCHART
1.3.1 ADVANTAGES OF FLOWCHART
1.3.2 DISADVANTAGES OF FLOWCHART

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 1: PROBLEM SOLVING, ALGORITHM & FLOWCHART

PROBLEM-SOLVING
• Problem-solving is the process of using computational-methods and logical-
reasoning to find solutions to complex issues or tasks.
• This process is fundamental to developing software.

1.1 PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)


• PDLC is a structured approach to developing software.
• It consists of six stages:
1) Problem Definition
2) Problem Analysis
3) Algorithm Development
4) Coding & Documentation
5) Testing & Debugging
6) Maintenance

1) Problem Definition
• This stage involves defining the problem that the software aims to solve.
• Key-Points
- Clearly identify and state the problem.
- Gather requirements from stakeholders to understand what they expect.
- Define the scope of the software-project, including its goals and objectives.
- Document the problem and requirements for later reference.
2) Problem Analysis
• In this stage, the problem defined earlier is analyzed to understand its nature,
scope, and specific requirements.
• Key-Points
- Break down the problem into smaller parts or modules.
- Analyze user needs to ensure the solution meets requirements.
- Consider time, budget, and technical limits.
- Assess if the problem can feasibly be solved with available resources.

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-2
PROBLEM SOLVING AND PROGRAMMING USING C++
3) Algorithm Development
• Here, algorithms are designed to solve each part of the problem identified in the
analysis stage.
• Key-Points
- Design algorithms to meet requirements.
- Use flowcharts, pseudocode, or structured English to show algorithms visually or
in text.
- Ensure algorithms are clear, efficient, and logical.
- Keep scalability and maintainability in mind.
4) Coding & Documentation
• Coding involves implementing designed algorithms in a programming language.
Documentation involves describing the program's functionality, usage, and
internals.
• Key-Points
- Write code following coding standards and best practices.
- Use appropriate data structures and programming constructs.
- Include comments and documentation in the code to explain its purpose, logic,
and usage.
- Create user manuals, technical documentation, and comments for future
reference and maintenance.
5) Testing & Debugging
• Testing verifies that the software meets requirements and functions correctly.
Debugging identifies and fixes errors found during testing.
• Key-Points
- Develop test cases based on requirements and expected outcomes.
- Execute test cases to find errors, bugs, or inconsistencies.
- Fix issues to ensure the software works as intended.
- Conduct different types of testing like unit, integration, system, and acceptance
testing.
6) Maintenance
• Maintenance includes making changes and updates to the software after
deployment.
• Key-Points
- Address bug fixes and enhancements based on feedback and changing needs.
- Optimize performance for new hardware or software.
- Update documentation to reflect changes.
- Plan for long-term maintenance with version control and bug tracking.

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-3
PROBLEM SOLVING AND PROGRAMMING USING C++
1.2 ALGORITHM
• An algorithm is a step by step procedure to solve a problem
• In other words, an algorithm is a sequence of instructions that act on some input
data to produce some output in a finite number of steps
• Algorithm is independent of any programming language
• Algorithm is written in the natural languages like English
• Five properties of algorithm are:
1) Input: An algorithm may have many inputs or no inputs at all
2) Output: An algorithm must produce at least 1 output as result
3) Finite: An algorithm should have finite number of steps and it should end
after a finite time
4) Definite: Each step must be clear, well-defined and precise. There should be
no any ambiguity
5) Effective: Each step must be simple and should take a finite amount of time
• Example 1: Write an algorithm to find sum of 2 numbers
Step 1: Start
Step 2: Read Number1, Number2
Step 3: Compute Sum= Number1+Number2
Step 4: Write Sum
Step 5: Stop
1.2.1 ADVANTAGES OF ALGORITHM
• Clear Steps: Algorithms provide simple, clear steps to solve problems.
• Effective Problem Solving: They break down problems into smaller, manageable
parts.
• Reusability: You can reuse an algorithm for similar problems in the future.
1.2.2 DISADVANTAGES OF ALGORITHM
• Time-Consuming to Create: Creating an algorithm can take a lot of time.
• Requires Skill: Writing a good algorithm needs strong problem-solving skills.
• Limited Use: Algorithms are usually designed for specific problems and may not
work for others without changes.

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-4
PROBLEM SOLVING AND PROGRAMMING USING C++
1.3 FLOWCHART
• Flowchart is a pictorial representation of an algorithm
• In other words, flowchart shows the sequence of instructions in a program
• Flowcharts are compared with the blue print of a building
• Flowcharts are used in analyzing or designing a program
• Each step in the algorithm is represented by a different symbols
• Actual instructions are written within the symbols
• Symbols are connected by arrows
• Basic flowchart symbols are represented in below table

Symbols used in flowchart

• Example: Draw a flowchart to find sum of 2 numbers.

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-5
PROBLEM SOLVING AND PROGRAMMING USING C++
1.3.1 ADVANTAGES OF FLOWCHART
• Easy to Understand: Flowcharts clearly show the steps of a process. This makes it
easier to understand how things work.
• Improves Communication: They help team members and clients communicate
better by providing a simple visual guide to discuss a process.
• Helps in Problem Solving: Flowcharts make it easier to find and fix problems by
showing the entire process visually.
1.3.2 DISADVANTAGES OF FLOWCHART
• Complicated for Large Systems: Flowcharts can become confusing and hard to
follow when used for big or complex systems.
• Takes Time to Create: Making detailed flowcharts can take a lot of time, especially
for processes that change often.
• Not Very Flexible: Flowcharts might not work well for processes that are not
straightforward, as they usually show steps in a fixed order.

ALGORITHM VS. FLOWCHART

PROBLEM SOLVING, ALGORITHM & FLOWCHART


1-6
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 2: INTRODUCTION TO C++

2.1 FEATURES OF C++


2.2 GENERAL STRUCTURE OF C++ PROGRAM
2.3 STEPS IN C++ PROGRAM EXECUTION
2.4 CHARACTER SET
2.5 TOKENS
2.5.1 KEYWORDS
2.5.2 IDENTIFIER
2.5.3 CONSTANTS
2.6 BASIC DATA-TYPES
2.6.1 PRIMARY DATA-TYPES
2.6.2 QUALIFIERS
2.7 VARIABLE
2.7.1 RULES FOR DEFINING A VARIABLE
2.7.2 DECLARATION OF VARIABLE
2.7.3 INITIALIZATION OF VARIABLE
2.8 DATA INPUT/OUTPUT-FUNCTIONS
2.8.1 INPUT-FUNCTIONS
2.8.2 OUTPUT-FUNCTIONS

INTRODUCTION TO C++
2-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 2: INTRODUCTION TO C++

2.1 FEATURES OF C++


1) Object-Oriented Programming (OOP)
• C++ supports OOP concepts like classes, objects and inheritance.
• Classes are used to group data and functions into objects for modularity and
reusability.
2) Strongly Typed Language
• C++ is statically typed, so variables must be declared with their data-types before
use.
• Strong-typing catches errors during compilation. This can lead to more efficient
code execution.
3) Standard Template Library (STL)
• STL provides template-classes and functions for common data-structures (e.g.,
vectors, lists) and algorithms (sorting, searching).
• It promotes code reuse and productivity with pre-implemented, efficient solutions.
4) Memory-management
• C++ supports explicit memory-management through features like dynamic
memory-allocation (new/delete) and pointers.
• Developers can optimize memory-usage.
5) Performance
• C++ is known for efficiency and is suitable for systems-programming and games.
• It offers low-level control over hardware. This optimizes code for speed and
memory.
6) Operator Overloading
• C++ allows overloading-operators (e.g., `+`, `-`, `*`) to define custom behaviors
for user-defined types.
• This enhances code-readability and maintainability for operations on these types.
7) Multiple-inheritance
• C++ supports multiple-inheritance. This allows classes to inherit from more than
one parent-class.
• This supports complex object-oriented designs.
8) Templates
• Templates in C++ enable generic-programming where types and functions can work
with specified parameters later.
• They reduce code duplication and enhance flexibility by allowing reusable-code for
any data-type.
9) Exception Handling
• C++ uses `try`, `catch`, and `throw` for exception handling and managing errors.
• This separates error-handling logic from normal program flow, enhancing reliability.
10) Standardization
• C++ is standardized by ISO. This ensures consistency and portability across
platforms and compilers.
• New standards (e.g., C++11, C++14) introduce features, improve the language,
and clarify its use for developers.

INTRODUCTION TO C++
2-2
PROBLEM SOLVING AND PROGRAMMING USING C++
2.2 GENERAL STRUCTURE OF C++ PROGRAM
#include <iostream> // Preprocessor-directive
using namespace std; // Namespace declaration
int main() // Main function
{
declaration section

statement-1 // Executable section starts


statement-2
statement-3 // Executable section ends
}
Preprocessor-directives
• The preprocessor accepts the source-program and prepares the source-program for
compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the specified file-
contents in the beginning of the program.
• For ex:
#include< iostream >
Namespace Declaration
• Namespaces are used to organize code into logical-groups and avoid naming-
conflicts.
main()
• Every C++ program should have a function-called as main().
• This the first function to be executed always.
• The statements enclosed within left and right brace is called body of the function.
• The main() function is divided into 2 parts:
i) Declaration section
• The variables that are used within the function main() should be declared in
the declaration-section only.
• The variables declared inside a function are called local-variables.
Ex:
int p, t, r;
ii) Executable section
• This contains the instructions given to the computer to perform a specific
task.
• The task may be to
→ display a message
→ read data or
→ add 2 numbers etc
• Comments are portions of the code ignored by the compiler. The comments
allow the user to make simple notes in the source-code.
// this is an example for single line comment
/* this is an example
for multiple line comment */

INTRODUCTION TO C++
2-3
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to display a message on the screen

INTRODUCTION TO C++
2-4
PROBLEM SOLVING AND PROGRAMMING USING C++
2.3 STEPS IN C++ PROGRAM EXECUTION

1) Preprocessing
• Purpose: Before compilation, the preprocessor scans the source-code for
preprocessor-directives (`#include`, `#define`, etc.).
• Actions:
- Header inclusion: `#include` directives pull in contents of header-files.
- Macro substitution: `#define` macros are replaced with their defined-values.
2) Compilation
• Purpose: The preprocessed source-code is translated into machine-readable
instructions.
• Actions:
- Syntax analysis: Checks syntax for correctness, identifies tokens (keywords,
identifiers, literals).
- Semantic analysis: Validates semantics (type checking, function-calls, etc.).
- Code generation: Translates validated-code into assembly- or machine-code.

INTRODUCTION TO C++
2-5
PROBLEM SOLVING AND PROGRAMMING USING C++
3) Assembly (Optional step)
• Purpose: Translates the output of the compiler into object-code specific to the
platform (if compiling to assembly-code).
• Actions: Generates assembly-language-code or intermediate object-files (`.obj`).
4) Linking
• Purpose: Combines object-files and libraries to generate an executable-file.
• Actions:
- Symbol resolution: Resolves external-references to functions or variables used
across different files.
- Static library inclusion: Links statically linked libraries (`.lib`, `.a`).
- Dynamic linking (optional): Resolves references to dynamically linked
libraries (`.dll`, `.so`).
5) Loading
• Purpose: The operating-system loads the executable-file into memory for
execution.
• Actions: Allocates memory-space for the program and initializes necessary data-
structures.
6) Initialization:
• Purpose: Prepares the environment before `main()` execution.
• Actions: Initializes global-variables with default-values, sets up environment-
variables, etc.
7) Execution of `main()` function
• Purpose: The entry-point where program execution begins.
• Actions: Executes statements inside `main()`, including variable-assignments,
control flow statements (`if`, `for`, `while`), and I/O-operations (`cout`, `cin`).

Note:
HOW TO LEARN C++ LANGUAGE?
• English is a universal language used to communicate with others.
• In the same way, C++ is a language used to communicate with computer. In other words,
C++ is used to instruct computer to perform particular task.
• The task can be
→ simple task like adding 2 numbers or
→ complex task like building a railway reservation system
• Before you play the game, you should learn rules of the game. So that you can play better
and win easily. In the same way, to write C++ programs, you should learn rules of C++
language.
STEPS TO LEARN C++ LANGUAGE
Step 1: Before speaking any language, you should first learn alphabets. In the same way, to
learn C++ language, you should first learn alphabets in C++.
Step 2: Then, you should learn how to group alphabets in particular sequence to form a
meaningful word. In the same way, in C++ language, you should learn tokens (i.e. words).
Step 3: Then, you should learn how to group the words in particular sequence to form a
meaningful sentence. In the same way, in C++ language, you should learn instruction (i.e.
sentence).
Step 4: Then, you should learn how to group the sentences in particular sequence to form a
meaningful paragraph. In the same way, in C++ language, you should learn program (i.e.
paragraph).

INTRODUCTION TO C++
2-6
PROBLEM SOLVING AND PROGRAMMING USING C++
2.4 CHARACTER SET
• Character-set refers to the set of alphabets, letters and some special-characters
that are valid in C++ language.
• For example, the characters in C++ are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
→ Symbols such as + - * / %
→ White spaces

2.5 TOKENS
• A token is a smallest element of a C++ program.
• One or more characters are grouped in sequence to form meaningful words. These
meaningful words are called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while
→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "sri"
→ Operators ex: + - * /
→ Special symbols ex: [], (), {}

INTRODUCTION TO C++
2-7
PROBLEM SOLVING AND PROGRAMMING USING C++
2.5.1 KEYWORDS
• Keywords are tokens which are used for their intended-purpose only.
• Each keyword has fixed meaning and that cannot be changed by user. Hence, they
are also called reserved-words.
Rules for using keyboards
• Keywords cannot be used as a variable or function.
• All keywords should be written in lower letters.
• Some keywords are as listed below table

2.5.2 IDENTIFIER
• As the name indicates, identifier is used to identify various entities of program such
as variables, constants, functions etc.
• In other words, an identifier is a word consisting of sequence of
→ Letters
→ Digits or
→ "_"(underscore)
• For ex:
area, length, breadth

INTRODUCTION TO C++
2-8
PROBLEM SOLVING AND PROGRAMMING USING C++
2.5.3 CONSTANTS
• A constant is an identifier whose value remains fixed throughout the execution of
the program.
• The constants cannot be modified in the program.
• For example:
1, 3.14512 , “z‟, “gcwmaddur"
• Five different types of constants are:
1) Integer-constant
• An integer is a whole-number without any fraction-part.
• There are 3 types of integer-constants as listed in below table:

2) Floating-point-constant
• The floating-point-constant is a real-number.
• The floating-point-constants can be represented using 2 forms as listed in below
table:

3) Character-constant
• A symbol enclosed within a pair of single-quotes(') is called a character-constant.
• Each character is associated with a unique-value called an ASCII (American
Standard Code for Information Interchange) code.
• For ex:
'9', 'a', '\n'
4) String-constant
• A sequence of characters enclosed within a pair of double-quotes(“) is called a
string-constant.
• The string always ends with NULL (denoted by \0) character.
• For ex:
"9" "a" "gcwmaddur" "\n"
5) Escape Sequence Characters
• An escape sequence character begins with a backslash and is followed by one
character.
• A backslash (\) along with some characters give rise to special print effects by
changing (escaping) the meaning of some characters.

INTRODUCTION TO C++
2-9
PROBLEM SOLVING AND PROGRAMMING USING C++
• The complete set of escape sequences are as listed in below table:

COMPARISON OF KEYWORDS, IDENTIFIERS, AND CONSTANTS

INTRODUCTION TO C++
2-10
PROBLEM SOLVING AND PROGRAMMING USING C++
2.6 BASIC DATA-TYPES
• The data-type defines the type of data stored in a memory-location.
• C++ supports 3 classes of data-types:
1) Primary data-type e.g. int, flaot
2) Derived data-types e.g. array
3) User defined data-types e.g. structure, class
2.6.1 PRIMARY DATA-TYPES
1) int
• An int is a keyword which is used to define integers.
• Using int keyword, the programmer can inform the compiler that the data
associated with this keyword should be treated as integer.
• C++ supports 3 different sizes of integer:
→ short int
→ int
→ long int
2) float
• A float is a keyword which is used to define floating-point-numbers.
3) double
• A double is a keyword used to define long floating-point-numbers.
4) char
• A char is a keyword which is used to define single character.
5) bool
• A bool is a keyword which is used to define Boolean values (true or false).
6) void
• void is an empty data-type. Since no value is associated with this data-type, it does
not occupy any space in the memory.
• This is normally used in functions to indicate that the function does not return any
value.

2.6.2 QUALIFIERS
• Qualifiers alter the meaning of primary data-types to yield a new data-type.
1) Size Qualifiers
• Size-qualifiers alter the size of primary data-type.
• The keywords long and short are two size-qualifiers.
For example:
long int i; //The size of int is 4 bytes but, when long keyword is
//used, that variable will be of 8 bytes
short int i; //The size of int is 4 bytes but, when short keyword is
//used, that variable will be of 2 byte

INTRODUCTION TO C++
2-11
PROBLEM SOLVING AND PROGRAMMING USING C++
2) Sign Qualifiers
• Whether a variable can hold positive-value, negative-value or both values is
specified by sign-qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
unsigned int a; //unsigned variable can hold zero & positive-values only
signed int b; //signed variable can hold zero , positive and negative-values
3) Constant Qualifiers
• Constant qualifiers can be declared with keyword ‘const’.
• An object declared by const cannot be modified.
const int p=20; //the value of p cannot be changed in the program.

INTRODUCTION TO C++
2-12
PROBLEM SOLVING AND PROGRAMMING USING C++
2.7 VARIABLE
• A variable is an identifier whose value can be changed during execution of the
program.
In other words, a variable is a name given to a memory-location where the data
can be stored.
• Using the variable-name, the data can be
→ stored in a memory-location and
→ accessed or manipulated
2.7.1 RULES FOR DEFINING A VARIABLE
1) The first character in the variable should be a letter or an underscore(‘_’)
2) The first character can be followed by letters or digits or underscore
3) No extra symbols are allowed (other than letters, digits and underscore)
4) Length of a variable can be up to a maximum of 31 characters
5) Keywords should not be used as variable-names
• Valid variables:
z, principle_amount, gcw_maddur
Invalid variables:
3fact //violates rule 1
sum= sum-of-digits dollar$ //violates rule 3
for int if //violates rule 5
2.7.2 DECLARATION OF VARIABLE
• The declaration tells the complier
→ what is the name of the variable used
→ what type of date is held by the variable
• Syntax:
data_type v1,v2,v3;
where v1,v2,v3 are variable-names
data_type can be int, float or char
• For ex:
int a, b, c;
float x, y, z;
2.7.3 INITIALIZATION OF VARIABLE
• The variables are not initialized when they are declared. Hence, variables normally
contain garbage-values and hence they have to be initialized with valid-data.
• Syntax is shown below:
data_type var_name=data;
where data_type can be int, float or char
var_name is a name of the variable
= is assignment operator
‘data’ is the value to be stored in variable
• For ex:
int a=10;
float pi=3.1416;
char c='z';

INTRODUCTION TO C++
2-13
PROBLEM SOLVING AND PROGRAMMING USING C++
2.8 DATA INPUT/OUTPUT-FUNCTIONS
• C++ has several library-functions for input- and output-operations.
• For example:
`cin`, `cout`, `cerr`, `clog`.
• To use these functions in a C++ program, the preprocessor-statement
`#include<iostream>` must be included.
2.8.1 INPUT-FUNCTIONS
• Input-functions are used to read data from the keyboard and store it in a memory-
location.
• For example:
`cin`: Reads input from the standard-input (keyboard).
• Syntax:
`int num;
cin >> num;` //reads the entered value into the variable `num`.
2.8.2 OUTPUT-FUNCTIONS
• Output-functions are used to receive data from memory-locations and display it on
the monitor.
• For example:
`cout`: Writes output to the standard-output (screen).
• Syntax:
`cout << "Hello!";` // This Displays "Hello!" followed by a newline by default.
• Program which asks user for their name and age, then prints a greeting message.
#include <iostream>
using namespace std;

int main() {
// Variables to store user input
string name;
int age;

// Prompt user for input


cout << "Enter your name: ";
cin >> name;

cout << "Enter your age: ";


cin >> age;

// Output greeting message


cout << "Hello, " << name << "! You are " << age << " years old." << endl;

return 0;
}
Output:
Enter your name: Rama
Enter your age: 30
Hello, Rama! You are 30 years old.

INTRODUCTION TO C++
2-14
PROBLEM SOLVING AND PROGRAMMING USING C++
INPUT FUNCTIONS VS OUTPUT FUNCTIONS

INTRODUCTION TO C++
2-15
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 3: OPERATORS & EXPRESSIONS

3.1 OPERATOR
3.1.1 ARITHMETIC OPERATORS
3.1.2 RELATIONAL OPERATORS
3.1.3 LOGICAL OPERATORS
3.1.4 ASSIGNMENT OPERATOR
3.1.5 SHORTHAND OPERATORS
3.1.6 CONDITIONAL OPERATOR
3.1.7 BITWISE OPERATORS
3.1.8 COMMA OPERATOR
3.1.9 sizeof OPERATOR
3.1.10 INCREMENT/DECREMENT OPERATORS
3.1.10.1 INCREMENT OPERATOR
3.1.10.2 DECREMENT OPERATOR
3.1.11 SCOPE RESOLUTION OPERATOR
3.2 EXPRESSION
3.2.1 ARITHMETIC EXPRESSIONS
3.2.2 RELATIONAL-EXPRESSIONS
3.2.3 LOGICAL-EXPRESSIONS
3.3 PRECEDENCE AND ASSOCIATIVITY
3.3.1 PRECEDENCE OF OPERATORS
3.3.2 ASSOCIATIVITY OF OPERATORS
3.3.2.1 LEFT-ASSOCIATIVE OPERATORS
3.3.2.2 RIGHT-ASSOCIATIVE OPERATORS
3.4 TYPE CONVERSION
3.4.1 TYPE CONVERSION (IMPLICIT CONVERSION)
3.4.2 TYPE CASTING (EXPLICIT CONVERSION)

OPERATORS & EXPRESSIONS


3-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 3: OPERATORS & EXPRESSIONS

3.1 OPERATOR
• An operator specifies what operation need to be performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation
Operand
• An operand can be a constant or a variable.
Expression
• An expression is combination of operands and operator that reduces to a single-
value.
• For ex:
Consider the following expression a+b
here a and b are operands
+ is an operator

CLASSIFICATION OF OPERATORS

OPERATORS & EXPRESSIONS


3-2
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.1 ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations.
• There are 5 arithmetic operators:

• Program to demonstrate the working of arithmetic operators.


#include <iostream>
using namespace std;
int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;

c = a - b;
cout << "a-b=" << c << endl;

c = a * b;
cout << "a*b=" << c << endl;

c = a / b;
cout << "a/b=" << c << endl;

c = a % b;
cout << "Remainder when a divided by b=" << c << endl;

return 0;
}
Output:
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1

OPERATORS & EXPRESSIONS


3-3
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.2 RELATIONAL OPERATORS
• Relational operators are used to find the relationship between two operands.
• The output of relational-expression is either true (1) or false (0).
• For example
a>b // If a is greater than b,
// then a>b returns 1
// else a>b returns 0.
• The 2 operands may be constants, variables or expressions.
• There are 6 relational operators:

• For ex:
Condition Return values
2>1 1 (or true)
2>3 0 (or false)
3+2<6 1 (or true)
• Program to illustrate the use of relational operators.
#include <iostream>

int main() {
cout << "4>5 : " << (4 > 5) << endl;
cout << "4>=5 : " << (4 >= 5) << endl;
cout << "4<5 : " << (4 < 5) << endl;
cout << "4<=5 : " << (4 <= 5) << endl;
cout << "4==5 : " << (4 == 5) << endl;
cout << "4!=5 : " << (4 != 5) << endl;

return 0;
}
Output:
4>5 : 0
4>=5 : 0
4<5 : 1
4<=5 :1
4==5 : 0
4!=5 : 1

OPERATORS & EXPRESSIONS


3-4
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.3 LOGICAL OPERATORS
• These operators are used to perform logical operations.
• The output of logical-expression is either true (1) or false (0).
• There are 3 logical operators:
Operator Meaning Example
&& Logical AND If c=5 and d=2 then ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then !(c==5) returns false.
• All non-zero values (i.e. 1, -1, 2, -2) will be treated as true.
While zero value (i.e. 0) will be treated as false.

• Program to illustrate the use of logical operators


#include <iostream>
using namespace std;

int main() {

cout << "7 && 0 : " << (7 && 0) << endl;


cout << "7 || 0 : " << (7 || 0) << endl;
cout << "!0 : " << (!0) << endl;

return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1
!0 : 1

OPERATORS & EXPRESSIONS


3-5
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.4 ASSIGNMENT OPERATOR
• The most common assignment operator is =.
• This operator assigns the value in right side to the left side.
• Syntax:
variable=expression;
• For ex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to b
5=c; // Error! 5 is a constant.
• Program to demonstrate the working of assignment operator.
#include <iostream>
using namespace std;

int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;

return 0;
}
Output:
a+b=13

OPERATORS & EXPRESSIONS


3-6
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.5 SHORTHAND OPERATORS
• Shorthand operators combine an arithmetic operation with assignment.
• Syntax:
`op=`
where `op` is an arithmetic operator.
• For ex,
a=a+10: can be written as a+=10;
• In the same way, we have:
Operator Example Same as
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
• Program to illustrate the usage of the shorthand operators.
#include <iostream>
using namespace std;

int main() {
int num = 10;
cout << "Initial value of num: " << num << endl;

// Shorthand operators
num += 5; // Equivalent to num = num + 5;
cout << "After num += 5: " << num << endl;

return 0;
}
Output:
Initial value of num: 10
After num += 5: 15

OPERATORS & EXPRESSIONS


3-7
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.6 CONDITIONAL OPERATOR
• The conditional operator is also called ternary operator as it takes three operands.
• Conditional operators are used for decision making in C++.
• Syntax:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false;
If exp1 is evaluated to true, exp2 is executed;
If exp1 is evaluated to false, exp3 is executed.
• Program to find largest of 2 numbers using conditional operator.
#include <iostream>
using namespace std;

int main() {
int a, b, max;
cout << "Enter 2 distinct numbers: " << endl;
cin >> a >> b;

max = (a > b) ? a : b;
cout << "Largest number = " << max << endl;

return 0;
}
Output:
enter 2 distinct numbers
34
largest number = 4

OPERATORS & EXPRESSIONS


3-8
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.7 BITWISE OPERATORS
• These operators are used to perform logical operation (and, or, not) on individual
bits of a binary-number.
• There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
• For ex,
Ex for ~ (bitwise complement) Ex for & (bitwise AND)
a = 13 0000 1101 a = 13 0000 1101
~a= 11110010 b = 6 0000 0110
a&b 0000 0100
Ex for || (bitwise OR) Ex for ^ (bitwise xor)
a = 13 0000 1101 a = 13 0000 1101
b=6 0000 0110 b=6 0000 0110
a|b 0000 1111 a^b 0000 1011
• The operator that is used to shift the data by a specified number of bit positions
towards left or right is called shift operator.
The syntax is shown below for << The syntax is shown below for >>
b=a << num; b=a >> num;
where ‘a’ is value to be shifted
‘num’ is number of bits to be shifted
Ex for <<(left shift): Ex for >>(right shift):
a = 13 0000 1101 a = 13 0000 1101
b=a<<1 0001 1010 b=a<<1 0000 0110

OPERATORS & EXPRESSIONS


3-9
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to illustrate the usage of the Bitwise Operators
#include <iostream>
using namespace std;

int main() {
// Variables for demonstration
unsigned int num1 = 13; // Binary: 0000 1101
unsigned int num2 = 6; // Binary: 0000 0110
unsigned int result;

// Bitwise AND
result = num1 & num2;
cout << "Bitwise AND (num1 & num2): " << result << endl;

// Bitwise OR
result = num1 | num2;
cout << "Bitwise OR (num1 | num2): " << result << endl;

// Bitwise XOR
result = num1 ^ num2;
cout << "Bitwise XOR (num1 ^ num2): " << result << endl;

// Bitwise NOT
result = ~num1;
cout << "Bitwise NOT (~num1): " << result << endl;

// Left shift
result = num1 << 1;
cout << "Left shift (num1 << 1): " << result << endl;

// Right shift
result = num1 >> 1;
cout << "Right shift (num1 >> 1): " << result << endl;

return 0;
}
Output:
Bitwise AND (num1 & num2): 4
Bitwise OR (num1 | num2): 15
Bitwise XOR (num1 ^ num2): 11
Bitwise NOT (~num1): 4294967282
Left shift (num1 << 1): 26
Right shift (num1 >> 1): 6

OPERATORS & EXPRESSIONS


3-10
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.8 COMMA OPERATOR
• Comma operator allows multiple-expressions to be evaluated within a single-
statement.
• This operator
 evaluates each expression from left to right and
 returns the result of the rightmost expression.
• Syntax:
`expression1, expression2, ..., expressionN`
• This operator is often used in `for` loops, function-calls, and variable-declarations.
• Program to illustrate the usage of the comma operator.
#include <iostream>
using namespace std;

int main() {
int a = 1, b = 2, c = 3;

// Using comma operator in a single-statement


int result = (a += 5, b += 10, c += 15);

// Output results
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "Result = " << result << endl;
return 0;
}
Output:
a=6
b = 12
c = 18
Result = 18

OPERATORS & EXPRESSIONS


3-11
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.9 sizeof OPERATOR
• This operator is used to determine the size, in bytes, of a data-type.
• Syntax:
`sizeof(type)`
• This operator is commonly used to determine storage-requirements.
• Program to illustrate the usage of the `sizeof` operator.
#include <iostream>
using namespace std;

int main() {
int intSize = sizeof(int);
double doubleSize = sizeof(double);
char charSize = sizeof(char);
bool boolSize = sizeof(bool);

cout << "Size of int: " << intSize << " bytes" << endl;
cout << "Size of double: " << doubleSize << " bytes" << endl;
cout << "Size of char: " << charSize << " byte" << endl;
cout << "Size of bool: " << boolSize << " byte" << endl;
return 0;
}
Output:
Size of int: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
Size of bool: 1 byte

OPERATORS & EXPRESSIONS


3-12
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.10 INCREMENT/DECREMENT OPERATORS
3.1.10.1 INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is used to
increase the value of a variable by 1.
• For example:
If b=5
then b++ or ++b; // b becomes 6
• The increment operator is classified into 2 categories:
1) Post increment Ex: b++
2) Pre increment Ex: ++b
• As the name indicates, post-increment means first use the value of variable and
then increase the value of variable by 1.
• As the name indicates, pre-increment means first increase the value of variable by 1
and then use the updated value of variable.
• For ex:
If x is 10,
then z= x++; sets z to 10
but z = ++x; sets z to 11
• Program to illustrate the use of increment operators.
#include <iostream>
using namespace std;

int main() {
int x = 10, y = 10, z;

z = x++;
cout << "z = " << z << " x = " << x << endl;

z = ++y;
cout << "z = " << z << " y = " << y << endl;

return 0;
}
Output:
z=10 x=11
z=11 y=11

OPERATORS & EXPRESSIONS


3-13
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.10.2 DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used to
decrease the value of a variable by 1.
• For example:
If b=5
then b-- or --b; // b becomes 4
• Similar to increment operator, the decrement operator is classified into 2
categories:
1) Post decrement Ex: b--
2) Pre decrement Ex: --b
• For ex:
If x is 10,
then z= x--; sets z to 10,
but z = --x; sets z to 9.
• Program to illustrate the use of decrement operators.
#include <iostream>
using namespace std;

int main() {
int x = 10, y = 10, z;

z = x--;
cout << "z = " << z << " x = " << x << endl;

z = --y;
cout << "z = " << z << " y = " << y << endl;

return 0;
}
Output:
z=10 x=9
z=9 y=9

OPERATORS & EXPRESSIONS


3-14
PROBLEM SOLVING AND PROGRAMMING USING C++
INCREMENT OPERATOR VS. DECREMENT OPERATOR

OPERATORS & EXPRESSIONS


3-15
PROBLEM SOLVING AND PROGRAMMING USING C++
3.1.11 SCOPE RESOLUTION OPERATOR
• This operator is used to access global-variables from within local scopes such as
functions.
• Syntax: `
::variable_name`
• This operator is used to differentiate between local and global-variables with the
same name.
• This operator helps in accessing global-variables within any scope without
ambiguity.
• Program to illustrate the use of Scope Resolution operator.
#include <iostream>
using namespace std;
int globalVar = 100; // Global-variable

int main() {
int localVar = 50; // Local variable

cout << "Global-variable: " << globalVar << endl;


cout << "Local variable: " << localVar << endl;

cout << "Accessing globalVar: " << ::globalVar << endl;

return 0;
}
Output:
Global-variable: 100
Local variable: 50
Accessing globalVar: 100

OPERATORS & EXPRESSIONS


3-16
PROBLEM SOLVING AND PROGRAMMING USING C++
3.2 EXPRESSION
• An expression is combination of operands and operator that reduces to a single-
value.
• For examples: Simple expressions: `x + y`, `5 * z`
Complex expressions: `a + b * (c - d)`
• Expressions are used to perform computations, assign values, or compare values.

3.2.1 ARITHMETIC EXPRESSIONS


• Arithmetic expressions performs basic arithmetic operations on numeric data-types
(`int`, `float`).
• Program to illustrate the use of Arithmetic Expressions.
#include <iostream>
using namespace std;

int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;
c = a - b;
cout << "a-b=" << c << endl;
return 0;
}
Output:
a+b=13
a-b=5

3.2.2 RELATIONAL-EXPRESSIONS
• Relational-expressions compare two values and return a Boolean result (`true` or
`false`).
• They are used in decision-making statements like `if`, `while`, and `for` loops:
• Program to illustrate the use of Relational-expressions.
#include <iostream>
using namespace std;

int main() {
cout << "4>5 : " << (4 > 5) << endl;
cout << "4>=5 : " << (4 >= 5) << endl;
return 0;
}
Output:
4>5 : 0
4>=5 : 0
4<5 : 1

OPERATORS & EXPRESSIONS


3-17
PROBLEM SOLVING AND PROGRAMMING USING C++
3.2.3 LOGICAL-EXPRESSIONS
• Logical-expressions combine multiple conditions using logical operators (`&&`,
`||`, `! `).
• They evaluate to `true` or `false` based on the truth values of their operands.
• Program to illustrate the use of Logical-expressions.
#include <iostream>
using namespace std;

int main() {
cout << "7 && 0 : " << (7 && 0) << endl;
cout << "7 || 0 : " << (7 || 0) << endl;
return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1

OPERATORS & EXPRESSIONS


3-18
PROBLEM SOLVING AND PROGRAMMING USING C++
3.3 PRECEDENCE AND ASSOCIATIVITY
3.3.1 PRECEDENCE OF OPERATORS
• The order in which different operators are used to evaluate an expression is called
precedence of operators.
• Operators with higher-precedence are evaluated before operators with lower-
precedence.
Example: Arithmetic operator (`*`) has higher-precedence than addition (`+`).
• Parentheses ` () ` can be used to explicitly control the order of evaluation in
expressions.
Example:
(a + b) * c ensures that addition is performed before multiplication, overriding
default precedence

Precedence Table

OPERATORS & EXPRESSIONS


3-19
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to illustrate the use of Precedence.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5, c = 2;
int result = a + b * c; // * has higher-precedence than +
cout << "Result of a + b * c: " << result << endl;
return 0;
}
Output:
Result of a + b * c: 20

OPERATORS & EXPRESSIONS


3-20
PROBLEM SOLVING AND PROGRAMMING USING C++
3.3.2 ASSOCIATIVITY OF OPERATORS
• Associativity determines the order in which operators of the same precedence are
grouped and evaluated.
• Two types of associativity:
1) Left-associative (`left-to-right`)
2) Right-associative (`right-to-left`)

3.3.2.1 LEFT-ASSOCIATIVE OPERATORS


• Operators are evaluated from left to right if they have the same precedence level.
• Example: Addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), etc.
• Program to illustrate the use of Left-Associative Operators
#include <iostream>
using namespace std;

int main() {
int result = 10 - 5 + 3; // Left-associative operators: subtraction and addition

cout << "Result: " << result << endl;

return 0;
}

Output:
Result: 8

3.3.2.2 RIGHT-ASSOCIATIVE OPERATORS


• Operators are evaluated from right to left if they have the same precedence level.
• Example: Assignment (`=`), conditional operator (`?:`), etc.
• Program to illustrate the use of Right-Associative Operators

OPERATORS & EXPRESSIONS


3-21
PROBLEM SOLVING AND PROGRAMMING USING C++
LEFT-ASSOCIATIVE OPERATORS VS. RIGHT-ASSOCIATIVE OPERATORS

OPERATORS & EXPRESSIONS


3-22
PROBLEM SOLVING AND PROGRAMMING USING C++
3.4 TYPE CONVERSION
• Type conversion is used to convert data of one type to data of another type.
• Type conversion is of 2 types:
1) Type Conversion (Implicit Conversion)
2) Type Casting (Explicit Conversion)

OPERATORS & EXPRESSIONS


3-23
PROBLEM SOLVING AND PROGRAMMING USING C++
3.4.1 TYPE CONVERSION (IMPLICIT CONVERSION)
• If a compiler converts one type of data into another type of data automatically, it is
known as implicit conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
• If one operand type is same as other operand type, no conversion takes place and
type of result remains same as the operands i.e. int+int=int
float+float=float
• Conversion rules are as follows:
→ If either operand is long double, convert the other to long double.
→ Otherwise, if either operand is double, convert the other to double.
→ Otherwise, if either operand is float, convert the other to float.
→ Otherwise, convert char and short to int.
→ Then, if either operand is long, convert the other to long.
• Program to illustrate implicit conversion.
#include <iostream>
using namespace std;

int main() {
int a = 5;
double b = 10.5;
double result = a + b; // Implicit conversion of 'a' to double before addition

cout << "Result: " << result << endl;

return 0;
}
Output:
Result: 15.5

OPERATORS & EXPRESSIONS


3-24
PROBLEM SOLVING AND PROGRAMMING USING C++
3.4.2 TYPE CASTING (EXPLICIT CONVERSION)
• When the data of one type is converted explicitly to another type with the help of
some pre-defined functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
• Syntax:
data_type1 v1;
data_type2 v2 = static_cast<data_type2>(v1);
where v1 can be expression or variable
• Program to illustrate explicit conversion.
#include <iostream>
int main() {
float b = 11.000000;
int c = 22;
float d = b / static_cast<float>(c);

cout << "b = " << b << endl;


cout << "c = " << c << endl;
cout << "d = " << d << endl;

return 0;
}
Output:
b = 11
c = 22
d = 0.5

IMPLICIT CONVERSION VS. EXPLICIT CONVERSION

OPERATORS & EXPRESSIONS


3-25
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 4: CONTROL STRUCTURES

4.1 BASIC CONCEPT OF DECISION-STATEMENTS


4.1.1 THE if STATEMENT
4.1.2 THE if else STATEMENT
4.1.3 THE nested if STATEMENT
4.1.4 THE else if LADDER STATEMENT
4.1.5 THE switch-statement
4.2 BASIC CONCEPT OF LOOP
4.2.1 THE while LOOP
4.2.2 THE for LOOP
4.2.3 THE do while STATEMENT
4.2.4 NESTED LOOPS
4.3 break AND continue STATEMENTS
4.3.1 THE break STATEMENT
4.3.2 THE continue STATEMENT

CONTROL STRUCTURES
4-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 4: CONTROL STRUCTURES

INTRODUCTION TO CONTROL STRUCTURES


• A program is nothing but the execution of sequence of one or more instructions.
• Quite often, it is desirable to change the order of execution of statements based on
certain conditions
• This involves a kind of decision making to see whether a particular condition has
occurred or not and direct the computer to execute certain statements accordingly.
• Based on application, it is necessary / essential
i) To alter the flow of a program
ii) Test the logical conditions
iii) Control the flow of execution as per the selection.
• These conditions can be placed in the program using decision-making statements.

C++ SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS


1) Decision making statements
i) if statement
ii) if else statement
iii) nested if statement
iv) else if ladder
v) switch-statement
2) Loop control statements
i) while loop
ii) for loop
iii) do-while loop
3) Unconditional control statements
i) break statement
ii) contiue statement

CONTROL STRUCTURES
4-2
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1 BASIC CONCEPT OF DECISION-STATEMENTS
• Decision making is critical to computer programming.
• There will be many situations when you will be given 2 or more options and you will
have to select an option based on the given conditions.
• For ex, we want to print a remark about a student based on secured marks and
following is the situation:
1. Assume given marks are x for a student
2. If given marks are more than 95 then
3. Student is brilliant
4. If given marks are less than 30 then
5. Student is poor
6. If given marks are less than 95 and more than 30 then
7. Student is average
• Now, question is how to write programming code to handle such situation. C++
language provides conditional i.e., decision making statements which work based on
the following flow diagram:

• There are 5 types of decision-statements:


i) if statement
ii) if else statement
iii) nested if statement
iv) else if ladder
v) switch-statement

CONTROL STRUCTURES
4-3
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1.1 THE if STATEMENT
• This is basically a “one-way” decision-statement.
• This is used when we have only one alternative.
• Syntax:
if(expression)
{
statement1;
}
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement1 is skipped.
• The flow diagram is shown below:

• Program to illustrate the use of if statement


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter any non zero integer: " << endl;
cin >> n;

if (n > 0)
cout << "Number is a positive number" << endl;
if (n < 0)
cout << "Number is a negative number" << endl;

return 0;
}
Output:
Enter any non zero integer:
7
Number is positive number

CONTROL STRUCTURES
4-4
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1.2 THE if else STATEMENT
• This is basically a “two-way” decision-statement.
• This is used when we must choose between two alternatives.
• Syntax:
if(expression)
{
statement1;
}
else
{
statement2;
}
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement2 is executed.
• The flow diagram is shown below:

• Program to illustrate the use of if else statement.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter any non-zero integer: " << endl;
cin >> n;

if (n > 0)
cout << "Number is a positive number" << endl;
else
cout << "Number is a negative number" << endl;

return 0;
}
Output:
Enter any non-zero integer:
7
Number is positive number

CONTROL STRUCTURES
4-5
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1.3 THE nested if STATEMENT
• An if-else statement within another if-else statement is called nested if statement.
• This is used when an action has to be performed based on many decisions. Hence, it
is called as multi-way decision-statement.
• Syntax:
if(expr1)
{
if(expr2)
statement1
else
statement2
}
else
{
if(expr3)
statement3
else
statement4
}
• Here, firstly expr1 is evaluated to true or false.
If the expr1 is evaluated to true, then expr2 is evaluated to true or false.
If the expr2 is evaluated to true, then statement1 is executed.
If the expr2 is evaluated to false, then statement2 is executed.
If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
If the expr3 is evaluated to true, then statement3 is executed.
If the expr3 is evaluated to false, then statement4 is executed.
• The flow diagram is shown below:

CONTROL STRUCTURES
4-6
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to select and print the largest of the 3 numbers using nested “if-else”
statements.
#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter Three Values: " << endl;
cin >> a >> b >> c;

cout << "Largest Value is: ";


if (a > b) {
if (a > c)
cout << a << endl;
else
cout << c << endl;
} else {
if (b > c)
cout << b << endl;
else
cout << c << endl;
}

return 0;
}
Output:
Enter Three Values:
786
Largest Value is: 8

CONTROL STRUCTURES
4-7
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1.4 THE else if LADDER STATEMENT
• This is basically a “multi-way” decision-statement.
• This is used when we must choose among many alternatives.
• Syntax:
if(expression1)
statement1;
else if(expression2)
statement2;
else if(expression3)
statement3
else if(expression4)
statement4
else
default statement5
• The expressions are evaluated in order (i.e. top to bottom).
• If an expression is evaluated to true, then
→ statement associated with the expression is executed &
→ control comes out of the entire else if ladder
• For ex, if exprression1 is evaluated to true, then statement1 is executed.
If all the expressions are evaluated to false, the last statement4 (default case)
is executed.

CONTROL STRUCTURES
4-8
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to illustrate the use of else if ladder statement.
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter any integer: ";
cin >> n;

if (n > 0)
cout << "Number is Positive" << endl;
else if (n < 0)
cout << "Number is Negative" << endl;
else if (n == 0)
cout << "Number is Zero" << endl;
else
cout << "Invalid input" << endl;

return 0;
}
Output:
Enter any integer: 7
Number is Positive

CONTROL STRUCTURES
4-9
PROBLEM SOLVING AND PROGRAMMING USING C++
4.1.5 THE switch-statement
• This is basically a “multi-way” decision-statement.
• This is used when we must choose among many alternatives.
• The syntax & flow diagram is shown below:

• Here, choice can be either any integer value or a character.


• Based on this integer value, the control is transferred to a particular case-value
where necessary statements are executed.
• During executing, if break statement is encountered, then the control comes out of
the switch-block.
• If the value of the choice does not match with any of the case values (i.e. value1,
value2, value3) then control goes to default label.
• All case-values must be different.
• Program to illustrate the use of switch-statement.
#include <iostream>
using namespace std;

int main() {
char grade; // local variable definition
cout << "Enter grade A to D: " << endl;
cin >> grade;

switch (grade) {
case 'A':
 cout << "Excellent!" << endl;
break;
case 'B':
cout << "Well done" << endl;
break;
case 'C':
cout << "You passed" << endl;
break;

CONTROL STRUCTURES
4-10
PROBLEM SOLVING AND PROGRAMMING USING C++
case 'D':
cout << "Better try again" << endl;
break;
default:
cout << "Invalid grade" << endl;
return 0;
}
cout << "Your grade is " << grade << endl;
return 0;
}
Output:
enter grade A to D:
B
Well done
Your grade is B

CONTROL STRUCTURES
4-11
PROBLEM SOLVING AND PROGRAMMING USING C++
4.2 BASIC CONCEPT OF LOOP
• Let's consider a situation when you want to write a message “Welcome to C++
language” five times.
Here is a simple C++ program to do the same:
#include <iostream>
using namespace std;

int main() {
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
• When the program is executed, it produces the above result.
• It was simple, but again let's consider another situation when you want to write the
same message thousand times, what you will do in such situation?
• Are we going to write cout statement thousand times? No, not at all.
• C++ language provides a concept called loop, which helps in executing one or more
statements up to desired number of times.
• Loops are used to execute one or more statements repeatedly.
• The flow diagram is shown below:

• There are 3 types of loops in C++ programming:


1) while loop
2) for loop
3) do while loop

CONTROL STRUCTURES
4-12
PROBLEM SOLVING AND PROGRAMMING USING C++
4.2.1 THE while LOOP
• A while loop-statement can be used to execute a set of statements repeatedly as
long as a given condition is true.
• Syntax:
while(expression)
{
statement1;
statement2;
}
• Firstly, the expression is evaluated to true or false.
• If the expression is evaluated to false, the control comes out of the loop without
executing the body of the loop.
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is
executed.
• After executing the body of the loop, control goes back to the beginning of the while
statement and expression is again evaluated to true or false. This cycle continues
until expression becomes false.
• The flow diagram is shown below:

• Program to display a message 5 times using while statement.


#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
cout << "Welcome to C++ language" << endl;
i = i + 1;
}
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language

CONTROL STRUCTURES
4-13
PROBLEM SOLVING AND PROGRAMMING USING C++
4.2.2 THE for LOOP
• A for loop-statement can be used to execute s set of statements repeatedly as long
as a given condition is true.
• Syntax:
for(expr1;expr2;expr3)
{
statement1;
}
• Here, expr1 contains initialization statement
expr2 contains limit test expression
expr3 contains updating expression
• Firstly, expr1 is evaluated. It is executed only once.
• Then, expr2 is evaluated to true or false.
If expr2 is evaluated to false, the control comes out of the loop without
executing the body of the loop.
If expr2 is evaluated to true, the body of the loop (i.e. statement1) is executed.
• After executing the body of the loop, expr3 is evaluated.
• Then expr2 is again evaluated to true or false. This cycle continues until expression
becomes false.
• The flow diagram is shown below:

CONTROL STRUCTURES
4-14
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to display a message 5 times using for statement.
#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
cout << "Welcome to C++ language" << endl;
}
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language

CONTROL STRUCTURES
4-15
PROBLEM SOLVING AND PROGRAMMING USING C++
4.2.3 THE do while STATEMENT
• When we do not know exactly how many times a set of statements have to be
repeated, do-while statement can be used.
• Syntax:
do
{
statement1;
}while(expression);
• Firstly, the body of the loop is executed. i.e. the body of the loop is executed at
least once.
• Then, the expression is evaluated to true or false.
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is
executed
• After executing the body of the loop, the expression is again evaluated to true or
false. This cycle continues until expression becomes false.
• The flow diagram is shown below:

• Program to display a message 5 times using do while statement


#include <iostream>
using namespace std;

int main() {
int i = 1;
do {
cout << "Welcome to C++ language" << endl;
i = i + 1;
} while (i <= 5);

return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language

CONTROL STRUCTURES
4-16
PROBLEM SOLVING AND PROGRAMMING USING C++
WHILE LOOP VS. DO-WHILE LOOP

CONTROL STRUCTURES
4-17
PROBLEM SOLVING AND PROGRAMMING USING C++
4.2.4 NESTED LOOPS
• Nested loops refer to placing one loop inside another loop.
• Syntax:
for (initialization; condition; update) {
// Outer loop code
for (initialization; condition; update) {
// Inner loop code
}
}

while (outer_condition) {
// Outer loop code
while (inner_condition) {
// Inner loop code
}
}

do {
// Outer loop code
do {
// Inner loop code
} while (inner_condition);
} while (outer_condition);

• Program to print a 3x3 matrix using nested for loops


#include <iostream>

int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}
return 0;
}

Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

CONTROL STRUCTURES
4-18
PROBLEM SOLVING AND PROGRAMMING USING C++
4.3 break AND continue STATEMENTS
4.3.1 THE break STATEMENT
• The break statement is jump-statement which can be used in switch-statement and
loops.
• The break statement works as shown below:
1) If break is executed in a switch-block, the control comes out of the switch-block
and the statement following the switch-block will be executed.
2) If break is executed in a loop, the control comes out of the loop and the statement
following the loop will be executed.
• Syntax:

• Program to illustrate usage of break statement.


#include <iostream>

int main() {
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
cout << "Breaking the loop at i = 5" << endl;
break;
}
cout << i << " ";
}
return 0;
}

Output:
1 2 3 4 Breaking the loop at i = 5

CONTROL STRUCTURES
4-19
PROBLEM SOLVING AND PROGRAMMING USING C++
4.3.2 THE continue STATEMENT
• During execution of a loop, it may be necessary to skip a part of the loop based on
some condition. In such cases, we use continue statement.
• The continue statement is used only in the loop to terminate the current iteration.
• Syntax:

• Program to read and add only positive numbers using continue statement.
#include <iostream>
using namespace std;
int main() {
int i = 1, num, sum = 0;
for (i = 0; i < 5; i++) {
cout << "Enter an integer: ";
cin >> num;
if (num < 0) {
cout << "You have entered a negative number" << endl;
continue; // skip the remaining part of loop
}
sum = sum + num;
}
cout << "The sum of the positive integers entered = " << sum << endl;
return 0;
}
Output:
Enter an integer: 10
Enter an integer:-15
You have entered a negative number
Enter an integer: 15
Enter an integer: -100
You have entered a negative number
Enter an integer: 30
The sum of the positive integers entered = 55

CONTROL STRUCTURES
4-20
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 5: FUNCTION

5.1 FUNCTION DEFINITION


5.2 ADVANTAGES OF FUNCTIONS
5.3 CLASSIFICATION (TYPES) OF FUNCTIONS
5.4 STRUCTURE OF USER-DEFINED-FUNCTIONS
5.5 ACTUAL AND FORMAL-ARGUMENTS
5.5.1 DEFAULT ARGUMENTS
5.6 CLASSIFICATION OF USER-DEFINED-FUNCTIONS
5.6.1 FUNCTION WITH NO ARGUMENTS AND NO RETURN-VALUE
5.6.2 FUNCTION WITH NO ARGUMENTS AND RETURN-VALUE
5.6.3 FUNCTION WITH ARGUMENTS BUT NO RETURN-VALUE
5.6.4 FUNCTION WITH ARGUMENTS AND RETURN-VALUE
5.7 RECURSION
5.7.1 GCD
5.7.2 FIBONACCI NUMBERS
5.8 ARGUMENT-PASSING – PASS BY VALUE & PASS BY REFERENCE
5.8.1 REFERENCE-VARIABLES
5.9 FUNCTION OVERLOADING
5.10 INLINE FUNCTIONS
5.11 FRIEND FUNCTIONS
5.12 STORAGE-CLASS
5.12.1 AUTOMATIC VARIABLE (LOCAL VARIABLE)
5.12.2 EXTERNAL VARIABLE (GLOBAL VARIABLE)
5.12.3 REGISTER-VARIABLE
5.12.4 STATIC-VARIABLE

FUNCTION
5-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 5: FUNCTION

5.1 FUNCTION DEFINITION


• A function is a block of code to perform a specific-task.
• Every C++ program has at least one function main().
• Without main() function, there is technically no C++ program .
• The function can take one or more arguments.
• The function can also return-values using the `return` statement.

5.2 ADVANTAGES OF FUNCTIONS


1) Modularity
• Functions break down a program into smaller parts.
• Each function performs a specific-task. This helps in understanding and maintaining
the code.
2) Code Reusability
• Functions allow to reuse the same code in different parts of a program or even in
different programs.
• Once a function is defined, it can be used multiple times across the program.
3) Readability
• Functions improve code-readability by organizing it logically.
• Well-named functions with clear inputs and outputs help programmers understand
the purpose of each part of the program.
4) Debugging and Testing
• Functions simplify the debugging and testing processes.
• They are smaller units of code. This makes it easier to isolate and identify errors
within their scope.
• This reduces the complexity of troubleshooting.
• This enhances the reliability of the overall program.
5) Abstraction
• Functions provide abstraction by allowing programmers to focus on what a task
does rather than how it is implemented internally.
• This improves productivity and facilitates collaboration among developers working
on different parts of the program.

FUNCTION
5-2
PROBLEM SOLVING AND PROGRAMMING USING C++
5.3 CLASSIFICATION (TYPES) OF FUNCTIONS
• In C++, functions are categorized into two types:
1) Library Function
• Library functions are built-in functions provided by the C++ standard-library.
• Examples:
`main()`, which is where every C++ program begins execution
`cout` for output
`cin` for input
2) User-Defined-Function
• C++ allows programmers to define their own functions according to their specific
requirements. These functions are called user-defined-functions.
• For example, if a programmer needs to calculate the factorial of a number, they can
create separate user-defined-function.

LIBRARY FUNCTION VS. USER-DEFINED-FUNCTION

FUNCTION
5-3
PROBLEM SOLVING AND PROGRAMMING USING C++
5.4 STRUCTURE OF USER-DEFINED-FUNCTIONS
#include <iostream> // C++ standard input/output library

void function_name(); //function-declaration

int main()
{
...........
...........
function_name(); // function-call
...........
...........
}

void function_name() //function-definition


{
................
................
}
• Every C++ program begins from main().
• Program starts executing the codes inside main() function.
• When the control of program reaches to function_name() inside main() function, the
control of program jumps to void function_name() and executes the codes inside it.
• When all the codes inside that user-defined-function are executed, control of the
program jumps to the statement just after function_name() from where it is called.
Function-Declaration (Function Prototyping)
• Every function should be declared before they are used.
• Function-declaration gives compiler information about
→ function-name
→ type-of-arguments to be passed
→ return-type
• Syntax:
return_type function_name(type(1) argument(1),....,type(n) argument(n));
Function-Call
• A Function-call is an instruction that tells the program to execute the user-defined-
function.
• Syntax:
function_name(argument(1), ...... argument(n));
Function-Definition
• Function-definition contains programming codes to perform specific-task.
• Syntax:
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}

FUNCTION
5-4
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to print a sentence using function
#include <iostream>
using namespace std;

void display(); // Function-declaration

int main() {
display(); // Function-call
return 0;
}

void display() // Function-definition


{
cout << "C++ Programming";
}
Output:
C++ programming

FUNCTION
5-5
PROBLEM SOLVING AND PROGRAMMING USING C++
5.5 ACTUAL AND FORMAL-ARGUMENTS
• Argument (or parameter) refers to data that is passed to the function-definition.
• Arguments used in the function-call are referred to as actual-arguments.
These actual values are passed to a function to compute a value or to perform a
task.
• The arguments used in the function-declaration are referred as formal-
arguments.
They are formal variables that accept or receive the values supplied by
the function-call.
• The no. of actual- and formal-arguments and their data-types should be same.
• Program to add two integers. Make a function add integers and display sum in
main() function.
#include <iostream>
using namespace std;

// Function-declaration
int add(int a, int b);

int main()
{
int a, b, sum;
cout << "Enter two numbers to add: " << endl;
cin >> a >> b;
sum = add(a, b); // Actual-arguments
cout << "Sum = " << sum << endl;
return 0;
}

// Function-definition
int add(int a, int b) // Formal-arguments
{ int sum;
sum = a + b;
return sum;
}
Output:
Enters two number to add
23
Sum=5

FUNCTION
5-6
PROBLEM SOLVING AND PROGRAMMING USING C++
ACTUAL ARGUMENTS VS. FORMAL ARGUMENTS

FUNCTION
5-7
PROBLEM SOLVING AND PROGRAMMING USING C++
5.5.1 DEFAULT ARGUMENTS
• In C++, you can assign default-values to function-parameters. This allows some or
all arguments to have predefined-values.
• This feature is helpful when you want to provide a default behavior if the user does
not specify values for certain arguments.
• Syntax:
returnType functionName(type arg1 = defaultValue1, type arg2 = defaultValue2, ...) {
// Function-body
// Use arg1, arg2, and other arguments
}
Where:
`arg1`, `arg2`, etc.: These are the function-parameters for which default-
values are specified.
`defaultValue1`, `defaultValue2`, etc.: These values are assigned as defaults
for the respective parameters.
• Program to calculate the area of a rectangle using a function
#include <iostream>
using namespace std;

// Function to calculate rectangle area with default arguments


int calculate_rectangle_area(int width = 2, int height = 3) {
int area = width * height;
return area;
}

int main() {
// Call the function without specifying width and height (default-values used)
int default_area = calculate_rectangle_area();

// Call the function with custom width and height


int custom_area = calculate_rectangle_area(5, 4);

// Output results
cout << "Default Area: " << default_area << endl;
cout << "Custom Area: " << custom_area << endl;

return 0;
}
Output:
Default Area:6
Custom Area:20

FUNCTION
5-8
PROBLEM SOLVING AND PROGRAMMING USING C++
5.6 CLASSIFICATION OF USER-DEFINED-FUNCTIONS
In C++, user-defined-functions can be classified based on whether they take
arguments and whether they return a value.
1) Function with no arguments and no return-value
2) Function with no arguments and return-value
3) Function with arguments but no return-value
4) Function with arguments and return-value

5.6.1 FUNCTION WITH NO ARGUMENTS AND NO RETURN-VALUE


• This function does not accept any arguments and does not return any value
(`void`).
• It performs a set of operations defined within its body without requiring input from
outside.
• Syntax:
`void function_name() { ... }`
• Example:
void greet() {
cout << "Hello, welcome to C++ functions!" << endl;
}

5.6.2 FUNCTION WITH NO ARGUMENTS AND RETURN-VALUE


• This function does not take any arguments but returns a value of type
`return_type`.
• It computes or retrieves some result and returns it to the caller.
• Syntax:
`return_type function_name() { ... return expression; }
• Example: `
int getNumber() {
int num = 10;
return num;
}

5.6.3 FUNCTION WITH ARGUMENTS BUT NO RETURN-VALUE


• This function accepts arguments of specified types (`type1`, `type2`, etc.) but
does not return any value (`void`).
• It performs operations using the provided arguments without needing to return a
result.
• Syntax:
`void function_name(type1 arg1, type2 arg2, ...) { ... }`
• Example:
void displaySum(int a, int b) {
int sum = a + b;
cout << "Sum of " << a << " and " << b << " is: " << sum << endl;
}

FUNCTION
5-9
PROBLEM SOLVING AND PROGRAMMING USING C++
5.6.4 FUNCTION WITH ARGUMENTS AND RETURN-VALUE
• This function accepts arguments of specified types (`type1`, `type2`, etc.) and
returns a value of type `return_type`.
• It computes or processes the arguments and then returns a result based on the
computation.
• Syntax:
`return_type function_name(type1 arg1, type2 arg2, ...) { ... return expression; }`
• Example:
double calculateAverage(double x, double y, double z) {
double average = (x + y + z) / 3;
return average;
}

FUNCTION
5-10
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate function with no arguments and no return-value.
#include <iostream>
using namespace std;
// Function-declaration
void add();

int main() {
add();
return 0;
}

// Function-definition
void add() {
int a, b, sum;
cout << "Enter two numbers to add: ";
cin >> a >> b;
sum = a + b;
cout << "\nSum = " << sum << endl;
}
Output:
Enters two number to add : 2 3
Sum=5

Program to illustrate function with no arguments and return-value.


#include <iostream>
using namespace std;
// Function-declaration
int add();

int main() {
int sum;
sum = add();
cout << "\nSum = " << sum << endl;
return 0;
}

// Function-definition
int add() {
int a, b, sum;
cout << "Enter two numbers to add: ";
cin >> a >> b;
sum = a + b;
return sum;
}
Output:
Enters two number to add : 2 3
Sum=5

FUNCTION
5-11
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate function with arguments but no return-value
#include <iostream>
using namespace std;
// Function-declaration
void add(int a, int b);

int main() {
int a, b;
cout << "Enter two numbers to add: ";
cin >> a >> b;
add(a, b);
return 0;
}

// Function-definition
void add(int a, int b) {
int sum = a + b;
cout << "\nSum = " << sum << endl;
}
Output:
Enters two number to add : 2 3
Sum=5

Program to illustrate function with arguments and return-value


#include <iostream>
using namespace std;//
Function-declaration int
add(int a, int b);

int main() {
int a, b, sum;
cout << "Enter two numbers to add: ";
cin >> a >> b;
sum = add(a, b);
cout << "\nSum = " << sum << endl;
return 0;
}

// Function-definition
int add(int a, int b) {
int sum = a + b;
return sum; // Return statement of function
}
Output:
Enters two number to add : 2 3
Sum=5

FUNCTION
5-12
PROBLEM SOLVING AND PROGRAMMING USING C++
5.7 RECURSION
• Recursion is a technique where a function calls itself repeatedly until a certain
condition is met
• Basic idea of recursion:
1) Break a problem into smaller sub-problems until the sub-problems can be
solved directly.
2) Then, combine the solutions of the sub-problems to get the solution of the
original problem.
• Recursion requires a base-case and a recursive-case.
1) In base-case, the problem can be solved directly w/o recursion.
2) In recursive-case, the function calls itself with a smaller input. This makes the
problem simpler and closer to the base-case.
• Eventually, the recursive-case will lead to the base-case and the recursion will
terminate.
• Recursive-functions can be slower and less memory efficient than iterative-
functions.
• Recursion can be used to solve following problems:
1) Finding GCD of 2 numbers
2) Generating Fibonacci numbers

FUNCTION
5-13
PROBLEM SOLVING AND PROGRAMMING USING C++
5.7.1 GCD
• GCD stands for Greatest Common Divisor.
• GCD is the largest positive integer that divides two or more integers w/o leaving a
remainder.
• The GCD of two numbers can be calculated using the Euclidean algorithm.
• The algorithm is as follows:
1) Let x and y be two positive integers.
2) If y is zero, the GCD of x and y is a.
3) Otherwise, the GCD of x and y is the same as the GCD of y and x % y.
4) Recursively call the gcd function with y and x % y as arguments, until y
becomes zero.
5) The last non-zero remainder returned by the recursive calls is the GCD of x
and y.

Program to find GCD using Recursive-function


#include <iostream>
using namespace std;

int gcd(int x, int y) {


if (y == 0) {
return x;
} else {
return gcd(y, x % y);
}
}

int main() {
int x, y, result;
cout << "Enter two positive integers: ";
cin >> x >> y;
result = gcd(x, y);
cout << "The GCD of " << x << " and " << y << " is " << result << endl;
return 0;
}

Output:
Enter two positive integers: 30 12
The GCD of 30 and 12 is 2

FUNCTION
5-14
PROBLEM SOLVING AND PROGRAMMING USING C++
5.7.2 FIBONACCI NUMBERS
• The fibonacci-sequence is a sequence in which each number after the first two is the
sum of the two preceding-numbers.
• The sequence starts with 0 and 1,
• So the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.
• The algorithm is as follows:
1) If n is 0 or 1, return n.
2) Otherwise, return the sum of the (n-1)th and (n-2)th terms of the Fibonacci-
sequence.

Program to calculate the nth number in the Fibonacci-sequence


#include <iostream>
using namespace std;

int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

int main() {
int n;
cout << "Enter the number of Fibonacci numbers to generate: ";
cin >> n;
cout << "The first " << n << " Fibonacci numbers are: " << endl;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
Output:
Enter the number of Fibonacci numbers to generate: 4
The first 4 Fibonacci numbers are:
0112

FUNCTION
5-15
PROBLEM SOLVING AND PROGRAMMING USING C++
5.8 ARGUMENT-PASSING – PASS BY VALUE & PASS BY REFERENCE
Definition
• Argument-passing refers to how arguments are transferred to functions.
• It determines whether a function works directly with the original data or a copy of
it.
Types of Argument-Passing
1) Pass by Value
• Here, a copy of the actual-argument is passed to the function-parameter.
• Modifications to the parameter inside the function do not affect the original-
argument.
2) Pass by Reference
• This allows a function to directly access and modify the original-argument.
• Syntax involves passing the address of the argument using references (`&`).
• Program to demonstrate argument-passing Methods.
#include <iostream>
using namespace std;
// Pass by value
void incrementByValue(int x) {
x++;
}

// Pass by reference
void incrementByReference(int &x) {
x++;
}

int main() {
int value = 5;

// Pass by value example


incrementByValue(value);
cout << "Value after pass by value: " << value << endl;

// Pass by reference example


incrementByReference(value);
cout << "Value after pass by reference: " << value << endl;
return 0;
}
Output:
Value after pass by value: 5
Value after pass by reference: 6

FUNCTION
5-16
PROBLEM SOLVING AND PROGRAMMING USING C++
PASS BY VALUE VS PASS BY REFERENCE

FUNCTION
5-17
PROBLEM SOLVING AND PROGRAMMING USING C++
5.8.1 REFERENCE-VARIABLES
Definition
• Reference-variables provide an alias (an alternative name) to an existing variable.
• Once initialized, a reference-variable remains bound to the same object throughout
its lifetime.
Declaration and Initialization
• Declaring a reference-variable involves using an ampersand (`&`) symbol after the
type in the declaration.
Usage and Benefits
• They are particularly useful in function-parameters to pass variables by reference.
This enables functions to modify the original data.
• Program to demonstrate use of Reference-variables
#include <iostream>
using namespace std;

int main() {
int value = 10; // Declare an integer variable 'value' and initialize it to 10
int &refNum = value; // Declare a reference 'refNum' to 'value'

// Output the value of 'value' and 'refNum'


cout << "Value: " << value << endl;
cout << "Reference Number: " << refNum << endl;

return 0;
}
Output:
Value: 10
Reference Number: 10

FUNCTION
5-18
PROBLEM SOLVING AND PROGRAMMING USING C++
5.9 FUNCTION OVERLOADING
Definition
• Function overloading means having multiple-functions with the same name but
different parameter-lists.
Purpose
• It allows creating functions that do similar tasks but work with different data-types
or numbers of parameters.
How Function-calls Are Resolved
• The compiler decides which function to use based on the types and no. of
arguments determined at compile time.
Rules for Overloaded Functions
• Overloaded functions must have different types or no. of parameters. The return-
type alone isn't enough to distinguish between overloaded functions.
Advantages
• Function overloading improves code reusability, clarity, and flexibility.
Example
• Program to illustrate Function overloading
#include <iostream>
using namespace std;

// Function to calculate area of a rectangle (integers)


int calculate_area(int length, int width) {
return length * width;
}

// Overloaded function to calculate area of a circle


double calculate_area(double radius) {
return 3)14 * radius * radius;
}

int main() {
// Calculate and display area of a rectangle with integers
int rect_area = calculate_area(5, 4);
cout << "Area of rectangle (integers): " << rect_area << endl;

// Calculate and display area of a circle


double circle_area = calculate_area(3)0);
cout << "Area of circle: " << circle_area << endl;

return 0;
}
Output:
Area of rectangle (integers): 20
Area of circle: 28.26

FUNCTION
5-19
PROBLEM SOLVING AND PROGRAMMING USING C++
5.10 INLINE FUNCTIONS
Definition
• Inline functions are small functions that the compiler can expand at the point of call
rather than executing a function-call.
• They are typically used for short and simple functions to avoid the overhead of
function-call.
How It Works
• When a function is declared as inline, the compiler replaces the function-call with
the actual code of the function-body.
• This eliminates the overhead of function-call and improves program execution-
speed.
Syntax
• To declare a function as inline, use the `inline` keyword before the function-
definition.
• Syntax:
inline type funcation_name() {
….. . . .
}
Advantages
• Inline functions reduce function-call overhead, especially useful for small functions.
• They can improve program performance by eliminating the time spent in function-
call setup and return.
Example
• Program to demonstrate the use of an inline function:
#include <iostream>
using namespace std;

// Inline function to calculate the square of a number


inline int square(int num) {
return num * num;
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

// Call to the inline function square()


cout << "Square of " << num << " is: " << square(num) << endl;

return 0;
}
Output
Enter a number: 5
Square of 5 is: 25

FUNCTION
5-20
PROBLEM SOLVING AND PROGRAMMING USING C++
5.11 FRIEND FUNCTIONS
Definition
• Friend functions are functions that are not members of a class but have access to
the private- and protected-members of the class.
• They are declared inside the class using the `friend` keyword.
Accessing Private and Protected Members
• A friend function can access private- and protected-members of a class, even
though it is not a member of that class.
• This feature allows functions outside the class to directly manipulate or use its
private-data.
Advantages
• Friend functions allow access to private-members of a class without breaking
encapsulation rules.
• They make it easier to handle complex operations involving multiple classes by
letting functions access private-members directly.
• Friend functions are helpful for tasks that need direct access to private-data. This
improves code organization and reuse.
Example
• Program to demonstrate the use of a friend function:
#include <iostream>
// Forward declaration of MyClass
class MyClass;

void displayData(MyClass obj); // Friend function-declaration

// MyClass definition
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}

// Declaring displayData() as a friend function of MyClass


friend void displayData(MyClass obj);
};

// Friend Function-definition
void displayData(MyClass obj) {
cout << "Data in MyClass: " << obj.data << endl;
}
int main() {
MyClass obj(10);
displayData(obj); // Calling friend function
return 0;
}
Output:
Data in MyClass: 10

FUNCTION
5-21
PROBLEM SOLVING AND PROGRAMMING USING C++
5.12 STORAGE-CLASS
• Every variable has two properties: type and storage-class.
• Type refers to the data-type of variable whether it is character or integer etc.
• Storage-class determines how long it stays in existence.
• There are 4 types of storage-class:
1) Automatic (or local)
2) External (or global)
3) Static
4) Register

5.12.1 AUTOMATIC VARIABLE (LOCAL VARIABLE)


• Definition: An automatic variable is a variable that is automatically created when a
function is called and destroyed when the function exits.
• Scope: It has a local scope. This means it is accessible only within the function
where it is defined.
• Usage: Since, variable inside a function is automatic by default, keyword auto are
rarely used.
• Advantage: Automatically managed by the compiler.
They are created when the function is called and destroyed when it exits.
This ensures they don’t occupy memory longer than necessary.

5.12.2 EXTERNAL VARIABLE (GLOBAL VARIABLE)


• Definition: An external variable is a variable defined outside of all functions.
• Scope: It has a global scope. This means it is accessible from any function or file.
• Usage: It can be accessed across multiple files using the extern keyword.
• Advantage: Provides a way to share data across different parts of a program.
• Example: Program to demonstrate working both local and global-variables
#include <iostream>
int z; // z is a global-variable

void display() {
cout << "\nSum = " << z << endl;
}

int main() {
int a, b; // a and b are local-variables
cout << "Enter two numbers to add: ";
cin >> a >> b;
z = a + b;
display();
return 0;
}
Output:
Enters two number to add: 2 3
Sum=5

FUNCTION
5-22
PROBLEM SOLVING AND PROGRAMMING USING C++
5.12.3 REGISTER-VARIABLE
• Definition: A register variable is a variable that is stored in the CPU's register
instead of memory.
• Scope: Local to the function where they are declared.
• Usage: It is used for frequently accessed variables to improve performance.
• Advantage: Value stored in register are much faster to access than that of
memory.
• Example: Program to illustrate use of register-variable.
#include <iostream>
int main() {
int a, b;
register int z;
cout << "Enter two numbers to add: ";
cin >> a >> b;
z = a + b;
cout << "\nSum = " << z << endl;
return 0;
}
Output:
Enters two number to add
23
sum=5

5.12.4 STATIC-VARIABLE
• Definition: A static variable is a variable that retains its value between function-
calls. It is initialized only once.
• Scope: It has a local scope but its lifetime extends for the duration of the program.
• Usage: Used for maintaining state information between function calls.
• Advantage: Provides a way to preserve the value of a variable across multiple
function calls. This is useful for keeping track of state or counters.
• Example: Program to demonstrate working of static-variable.
#include <iostream>
void Check() {
static int c = 0;
cout << c << "\t";
c = c + 5;
}
int main() {
Check();
Check();
Check();
return 0;
}
Output:
0 5 10

FUNCTION
5-23
PROBLEM SOLVING AND PROGRAMMING USING C++
COMPARISON OF AUTOMATIC VARIABLE, EXTERNAL VARIABLE, REGISTER
VARIABLE AND STATIC VARIABLE

FUNCTION
5-24
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 6: ARRAYS AND STRINGS

6.1 ARRAY DEFINITION


6.2 SINGLE-DIMENSIONAL-ARRAY
6.2.1 DECLARATION OF SINGLE-DIMENSIONAL-ARRAY
6.2.2 STORING VALUES IN SINGLE-DIMENSIONAL-ARRAY
6.3 TWO-DIMENSIONAL-ARRAY
6.3.1 DECLARATION OF TWO-DIMENSIONAL-ARRAY
6.3.2 STORING VALUES IN TWO-DIMENSIONAL-ARRAY
6.4 ARRAYS AND FUNCTION
6.5 STRING DEFINITION
6.6 STRING HANDLING FUNCTIONS

ARRAYS AND STRINGS


6-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 6: ARRAYS AND STRINGS

BASIC CONCEPT OF ARRAYS


• Consider a situation, where we need to store 5 integer-numbers.
• If we use simple variable and data-type concepts, then we need 5 variables of int
data-type and program will be something as follows:
#include <iostream>
using namespace std;

int main() {
int number1;
int number2;
int number3;
int number4;
int number5;

number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;

cout << "number1: " << number1 << endl;


cout << "number2: " << number2 << endl;
cout << "number3: " << number3 << endl;
cout << "number4: " << number4 << endl;
cout << "number5: " << number5 << endl;

return 0;
}
Output:
number1: 10
number2: 20
number3: 30
number4: 40
number5: 50
• It was simple, because we had to store just 5 integer-numbers. Now let's assume
we have to store 5000 integer-numbers, so what is next? Are we going to use 5000
variables?
• To handle such situation, C++ language provides a concept called the array.
• Some examples where arrays can be used are
1) List of temperatures recorded every hour in a day, or a month, or a year
2) List of employees in an organization
3) List of products and their cost sold by a store
4) Test scores of a class of students

ARRAYS AND STRINGS


6-2
PROBLEM SOLVING AND PROGRAMMING USING C++
6.1 ARRAY DEFINITION
• Array is a collection of elements of same data-type.
• The elements are stored sequentially one after the other in memory.
• Any element can be accessed by using
→ name of the array
→ position of element in the array i.e. index
• Arrays are of 2 types:
1) Single-dimensional-array
2) Multi-dimensional-array

6.2 SINGLE-DIMENSIONAL-ARRAY
• This array is a linear-list consisting of related elements of same type.
• In memory, all the elements are stored in continuous memory-location one after the
other.

6.2.1 DECLARATION OF SINGLE-DIMENSIONAL-ARRAY


• The syntax is shown below:
data_type array_name[array_size]
where data_type can be int, float or char
array_name is name of the array
array_size indicates no. of elements in the array
• For ex:
int age[5];
• The above code can be pictorially represented as shown below:

• Note that, the first element is numbered 0 and so on.


• Here, the size of array “age‟ is 5 times the size of int because there are 5 elements.

ARRAYS AND STRINGS


6-3
PROBLEM SOLVING AND PROGRAMMING USING C++
6.2.2 STORING VALUES IN SINGLE-DIMENSIONAL-ARRAY
• The values can be stored in array using following three methods:
1) Initialization
2) Assigning values
3) Input values from keyboard

Initialization of One-Dimensional Array


• The syntax is shown below:
data_type array_name[array_size]={v1,v2,v3};
where v1, v2, v3 are values
• For ex:
int age[5]={2, 4, 34, 3, 4};
• The above code can be pictorially represented as shown below:

• Example: Program to illustrate the initialization of one-dimensional array.


#include <iostream>
using namespace std;

int main() {
int age[5] = {2, 4, 34, 3, 4};

cout << "Value in array age[0]: " << age[0] << endl;
cout << "Value in array age[1]: " << age[1] << endl;
cout << "Value in array age[2]: " << age[2] << endl;
cout << "Value in array age[3]: " << age[3] << endl;
cout << "Value in array age[4]: " << age[4] << endl;

return 0;
}
Output:
Value in array age[0] :2
Value in array age[1] :4
Value in array age[2] :34
Value in array age[3] :3
Value in array age[4] :4

ARRAYS AND STRINGS


6-4
PROBLEM SOLVING AND PROGRAMMING USING C++
Assigning values to One-Dimensional Array
• For example:
int age[5];
age[0]=2; //value 2 stored in array “age‟ at position 0
age[1]=4; //value 4 stored in array “age‟ at position 1
age[2]=34; //value 34 stored in array “age‟ at position 2
age[3]=3; //value 3 stored in array “age‟ at position 3
age[4]=4; //value 4 stored in array “age‟ at position 4
• Here, `age` is a one-dimensional array with 5 rows (or columns).
• Each element of the array is accessed by specifying its index.
• Example: Program to illustrate assigning values to one-dimensional array.
#include <iostream>
using namespace std;

int main() {
int age[5];
age[0] = 2;
age[1] = 4;
age[2] = 34;
age[3] = 3;
age[4] = 4;

cout << "Value in array age[0]: " << age[0] << endl;
cout << "Value in array age[1]: " << age[1] << endl;
cout << "Value in array age[2]: " << age[2] << endl;
cout << "Value in array age[3]: " << age[3] << endl;
cout << "Value in array age[4]: " << age[4] << endl;

return 0;
}
Output:
Value in array age[0] :2
Value in array age[1] :4
Value in array age[2] :34
Value in array age[3] :3
Value in array age[4] :4

ARRAYS AND STRINGS


6-5
PROBLEM SOLVING AND PROGRAMMING USING C++
Reading/Writing to One-Dimensional Array
• For example:
int age[5];
cin >> age[0]; // read data from keyboard into array age at position 0
cin >> age[1]; // read data from keyboard into array age at position 1
cin >> age[2]; // read data from keyboard into array age at position 2
cin >> age[3]; // read data from keyboard into array age at position 3
cin >> age[4]; // read data from keyboard into array age at position 4
• In general, to read 5 values into the array, we can write as follows:
for (int i = 0; i < 5; i++)
{
cin >> age[i];
}
Similarly, to display 5 elements stored in the array, we can write:
for (int i = 0; i < 5; i++)
{
cout << age[i] << " ";
}
• Example: Program to illustrate reading/writing to one-dimensional array.
#include <iostream>
using namespace std;

int main() {
int age[5], i;

cout << "Enter 5 numbers:" << endl;


for (i = 0; i < 5; i++) {
cin >> age[i];
}

for (i = 0; i < 5; i++) {


cout << "Value in array age[" << i << "]: " << age[i] << endl;
}

return 0;
}
Output:
enter 5 numbers:
2 4 34 3 4
Value in array age[0] :2
Value in array age[1] :4
Value in array age[2] :34
Value in array age[3] :3
Value in array age[4] :4

ARRAYS AND STRINGS


6-6
PROBLEM SOLVING AND PROGRAMMING USING C++
6.3 TWO-DIMENSIONAL-ARRAY
• Arrays with two dimensions are called two-dimensional-arrays.
• For ex:
int matrix[2][2];
• The above code can be pictorially represented as shown below:

• A two-dimensional-array is used when elements are arranged in a tabular fashion.


• Here, to identify a particular element, we have to specify 2 indices:
→ First index identifies the row number of the element
→ Second index identifies the column number of the element

6.3.1 DECLARATION OF TWO-DIMENSIONAL-ARRAY


• The syntax is shown below:
data_type array_name[array_size][array_size];
• For ex:
int matrix[2][2];
• The above code can be pictorially represented as shown below:

ARRAYS AND STRINGS


6-7
PROBLEM SOLVING AND PROGRAMMING USING C++
6.3.2 STORING VALUES IN TWO-DIMENSIONAL-ARRAY
• The values can be stored in array using following three methods:
1) Initialization
2) Assigning values
3) Input values from keyboard

Initialization of Two-Dimensional-Array
• For ex:
int matrix[2][2]= {1, 23, 44, 5};
• The above code can be pictorially represented as shown below:

• Example: Program to illustrate the initialization of two-dimensional array.


#include <iostream>
using namespace std;

int main() {
int matrix[2][2] = {1, 23, 44, 5};

cout << "Value in array matrix[0][0]: " << matrix[0][0] << endl;
cout << "Value in array matrix[0][1]: " << matrix[0][1] << endl;
cout << "Value in array matrix[1][0]: " << matrix[1][0] << endl;
cout << "Value in array matrix[1][1]: " << matrix[1][1] << endl;

return 0;
}
Output:
Value in array matrix[0][0]: 1
Value in array matrix[0][1]: 23
Value in array matrix[1][0]: 44
Value in array matrix[1][1]: 5

ARRAYS AND STRINGS


6-8
PROBLEM SOLVING AND PROGRAMMING USING C++
Assigning values to Two-Dimensional Array
• For example:
int matrix[2][2];
matrix[0][0]= 1; // value 1 is stored in the array `matrix` at row 0, column 0
matrix[0][1]=23; // value 23 is stored in the array `matrix` at row 0, column 1
matrix[1][0]= 44; //value 44 is stored in the array `matrix` at row 1, column 0
matrix[1][1]= 5; // value 5 is stored in the array `matrix` at row 1, column 1
• Here, `matrix` is a two-dimensional array with 2 rows and 2 columns.
• Each element of the array is accessed by specifying its row and column index.
• Example: Program to illustrate assigning values to Two-dimensional array
#include <iostream>

int main() {
int matrix[2][2];
matrix[0][0] = 1;
matrix[0][1] = 23;
matrix[1][0] = 44;
matrix[1][1] = 5;

cout << "Value in array matrix[0][0]: " << matrix[0][0] << endl;
cout << "Value in array matrix[0][1]: " << matrix[0][1] << endl;
cout << "Value in array matrix[1][0]: " << matrix[1][0] << endl;
cout << "Value in array matrix[1][1]: " << matrix[1][1] << endl;

return 0;
}
Output:
Value in array matrix[0][0]: 1
Value in array matrix[0][1]: 23
Value in array matrix[1][0]: 44
Value in array matrix[1][1]: 5

ARRAYS AND STRINGS


6-9
PROBLEM SOLVING AND PROGRAMMING USING C++
Reading and Writing Two-Dimensional-Array
• For ex:
int matrix[2][2]
cin >> matrix[0][0]; // read data from keyboard into matrix at row=0 col=0
cin >> matrix[0][1]; // read data from keyboard into matrix at row=0 col=1
cin >> matrix[1][0]; // read data from keyboard into matrix at row=1 col=0
cin >> matrix[1][1]; // read data from keyboard into matrix at row=1 col=1
• In general, to read 6 values, we can write:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> matrix[i][j];
}
}
• Similarly to display 4 elements stored in the matrix, we can write:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout << matrix[i][j];
}
}
• Example: Program to illustrate reading/writing to two-dimensional array.
#include <iostream>
using namespace std;

int main() {
int matrix[2][2], i, j;

cout << "Enter elements of 2x2 matrix: " << endl;


for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
cin >> matrix[i][j];
}
}

cout << "Elements of the matrix are: " << endl;


for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}

return 0;
}

ARRAYS AND STRINGS


6-10
PROBLEM SOLVING AND PROGRAMMING USING C++
Output:
enter elements of 2*2 matrix:
1 23
44 5
elements of the matrix are:
1 23
44 5

SINGLE-DIMENSIONAL ARRAY VS TWO-DIMENSIONAL ARRAY

ARRAYS AND STRINGS


6-11
PROBLEM SOLVING AND PROGRAMMING USING C++
6.4 ARRAYS AND FUNCTIONS
• The arrays can be passed to functions using 2 methods:
1) Passing Individual Elements of Array and
2) Passing the Whole Array

1) Passing Individual Elements of Array


• All array-elements can be passed as individual elements to a function like any other
variable.
• The array-element is passed as a value-parameter i.e. any change in the formal-
parameter will not affect the actual-parameter i.e. array-element.
• Example: Program to illustrate passing individual elements of an array to a function
#include <iostream>
void display(int a) {
cout << a;
}

int main() {
int c[3] = {2, 3, 4};
display(c[2]); // Passing array element c[2] only.
return 0;
}
Output:
4

2) Passing the Whole Array


• Here, the parameter passing is similar to pass by reference.
• In pass by reference, the formal-parameters are treated as aliases for actual-
parameters.
• So, any changes in formal-parameter imply there is a change in actual-parameter.
• Example: Program to find average of 6 marks using pass by reference
#include <iostream>
void average(int m[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += m[i];
}
int avg = sum / size;
cout << "Aggregate marks = " << avg << endl;
}

int main() {
int m[6] = {60, 50, 70, 80, 40, 80};
average(m, 6); // Only name of array is passed as argument
return 0;
}
Output:
aggregate marks= 70

ARRAYS AND STRINGS


6-12
PROBLEM SOLVING AND PROGRAMMING USING C++
6.5 STRING DEFINITION
Definition
• A string is an array of characters (`char`).
• It represents a sequence of characters stored in contiguous memory-locations.
• Strings are terminated by a null-character (`'\0'`), which marks the end of the
string.
Declaration and Initialization
• Strings can be declared and initialized using C-style character arrays or using
`string`.
• Example:
char s[10] = "rama"; // C-style string
string s = "rama"; // string
• The above code can be pictorially represented as shown below:

• Program to illustrate read and write operations on strings:


#include <iostream>
#include <string> // for string
using namespace std;

int main() {
// Reading a string from user input
string input;
cout << "Enter a string: ";
getline(cin, input); // reads entire line, including spaces

// Writing the string to standard output


cout << "You entered: " << input << endl;

return 0;
}
Output:
Enter a string: rama
You entered: rama

ARRAYS AND STRINGS


6-13
PROBLEM SOLVING AND PROGRAMMING USING C++
6.6 STRING MANIPULATION FUNCTIONS
• Strings are often needed to be manipulated by programmer according to the need
of a problem.
• All string manipulation can be done manually by the programmer but, this makes
programming complex and large.
• To solve this, the C++ supports a large number of string handling functions.
• There are numerous functions defined in <string.h> header file.
• Common string manipulation functions include:
getline() substr()
find() append()
size() or length() replace()
tolower() toupper()

getline()
• This function is used to read a line or string from standard-input (usually keyboard)
into a string-variable.
• Syntax:
`getline(cin, str);`
• It reads characters from the `cin` input stream until a newline-character (`\n`) is
encountered and stores them in the string-variable `str`.
• Example:
string name;
cout << "Enter your name: ";
getline(cin, name);
If you input "rama", `name` will contain "rama".

substr()
• This function extracts a substring from a string.
• Syntax:
`str.substr(start_pos, length);`
• It returns a new string that contains a portion of the original string `str`, starting
from index `start_pos` and extending `length` characters long.
• Example:
string message = "Hello, World!";
string sub = message.substr(7, 5); // Extracts "World"

find()
• This function searches for a substring within a string.
• Syntax:
`str.find(substring);`
• It returns the position (index) of the first occurrence of `substring` within `str`, or
`string::npos` if `substring` is not found.
• Example:
string sentence = "The quick brown fox jumps over the lazy dog.";
size_t found = sentence.find("fox");
// found will be 16

ARRAYS AND STRINGS


6-14
PROBLEM SOLVING AND PROGRAMMING USING C++
append()
• This function adds characters to the end of a string.
• Syntax:
`str.append(suffix);`
• Example:
string greeting = "Hello";
greeting.append(", World!");
// greeting now contains "Hello, World!"

size() or length()
• This function return the length of a string.
• Syntax:
`str.size()` or `str.length()`
• Example:
string text = "gcwmaddur”
int len = text.size(); // len will be 9

replace()
• This function replaces part of a string with another string or a portion of another
string.
• Syntax:
`str.replace(start_pos, length_to_replace, new_str);`
• It replaces `length_to_replace` characters starting from `start_pos` in `str` with
the characters from `new_str`.
• Example:
string message = "Hello, World!";
message.replace(7, 5, "Universe"); // Replaces "World" with "Universe"
// message now contains "Hello, Universe!"

tolower()
• This function converts all characters in a string to lowercase.
• Syntax:
`transform(str.begin(), str.end(), str.begin(), ::tolower);`
• Example:
string text = "Hello, World!";
transform(text.begin(), text.end(), text.begin(), ::tolower);
// text now contains "hello, world!"

toupper()
• This function converts all characters in a string to uppercase.
• Syntax:
`transform(str.begin(), str.end(), str.begin(), ::toupper);`
• Example:
string text = "Hello, World!";
transform(text.begin(), text.end(), text.begin(), ::toupper);
// text now contains "HELLO, WORLD!"

ARRAYS AND STRINGS


6-15
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 7: STRUCTURE AND UNION

7.1 STRUCTURE
7.1.1 STRUCTURE-VARIABLE DECLARATION
7.1.2 STRUCTURE-VARIABLE INITIALIZATION
7.1.3 ACCESSING MEMBERS OF A STRUCTURE
7.2 NESTED STRUCTURE
7.3 ARRAY OF STRUCTURES
7.4 UNION
7.4.1 STRUCTURE-VARIABLE DECLARATION
7.4.2 STRUCTURE-VARIABLE INITIALIZATION
7.4.3 ACCESSING MEMBERS OF A STRUCTURE
7.5 STRUCTURE VS. UNION

STRUCTURE AND UNION


7-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 7: STRUCTURE AND UNION

7.1 STRUCTURE
• Structure is a collection of elements of different data-type.
• Syntax:
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the structure.
• For example:
struct Person
{
string name;
int cit_no;
float salary;
};
• The above code can be pictorially represented as shown below:

7.1.1 STRUCTURE-VARIABLE DECLARATION


• When you declare a structure-variable, you define an instance of that structure
type.
• Syntax:
struct StructureName variableName;
• Example:
struct person p1, p2;
• The above code can be pictorially represented as shown below:

• Here, the statement declares that p1 and p2 are variables of type struct person.
• Once the structure-variable is declared, the compiler allocates memory for the
structure-variables.
• The size of the memory allocated is the sum of size of individual members.

STRUCTURE AND UNION


7-2
PROBLEM SOLVING AND PROGRAMMING USING C++
7.1.2 STRUCTURE-VARIABLE INITIALIZATION
• Structure-variables can be declared and initialized at the time of declaration or
separately.
• Syntax:
struct StructureName variableName = {value1, value2, ...};
• Example:
struct Person p1 = {"rama", 24, 23000};
• The above code can be pictorially represented as shown below:

• Here, the statement initializes p1 with name "rama", cit_no 24, and salary 23000.

7.1.3 ACCESSING MEMBERS OF A STRUCTURE


• Members of a structure are accessed using the member-access-operator (.).
• Syntax:
variableName.memberName
• Example:
cout << "Name: " << p1.name << endl;
• Here the above statement accesses and prints the name member of structure p1.
• Program to illustrate use of Structure
#include <iostream>
#include <string> // Include the string library
struct Person {
string name;
int cit_no;
float salary;
};

int main() {
// Initialize the structure
Person p1 = {"rama", 24, 23000};

// Print name
cout << "Name: " << p1.name << endl;
// Print cit_no
cout << "Citizen Number: " << p1.cit_no << endl;
// Print salary
cout << "Salary: " << p1.salary << endl;
return 0;
}
Output:
Name: rama
Citizen Number: 24
Salary: 23000

STRUCTURE AND UNION


7-3
PROBLEM SOLVING AND PROGRAMMING USING C++
7.2 NESTED STRUCTURE
• Definition: A nested structure is a structure within another structure, where one
structure is used as a member of another structure.
• Purpose: It allows for organizing related data into a more hierarchical format.
• For example, storing a date of birth within a person record.

• Program to illustrate use of nested structure


#include <iostream>
#include <string> // Include the string library
struct Dob {
int day;
int month;
int year;
};
struct Person {
string name;
int cit_no;
float salary;
Dob d1; // Nested structure for date of birth
};
int main() {
Person p1; // Create instances of Person

// Assign values to p1
p1.name = "rama";
p1.cit_no = 101;
p1.salary = 50000.50;
p1.d1.day = 15;
p1.d1.month = 6;
p1.d1.year = 1990;

// Print p1's details


cout << "Person 1 details:" << endl;
cout << "Name: " << p1.name << endl;
cout << "Citizen Number: " << p1.cit_no << endl;
cout << "Salary: " << p1.salary << endl;
cout << "Date of Birth: " << p1.d1.day << "/" << p1.d1.month << "/" << p1.d1.year;
return 0;
}
Output:
Person 1 details:
Name: rama
Citizen Number: 101
Salary: 50000.5
Date of Birth: 15/6/1990

STRUCTURE AND UNION


7-4
PROBLEM SOLVING AND PROGRAMMING USING C++
7.3 ARRAY OF STRUCTURES
• An array of structures is a collection of structures of the same type.
• This allows storing multiple records of structured data in a single array.
• It is useful when you need to manage and manipulate a collection of records, such
as a list of students, employees, or products.
• Program to illustrate use of Array of Structures
#include <iostream>
#include <string> // Include the string library
struct Person {
string name;
int cit_no;
float salary;
};

int main() {
// Initialize an array of structures
Person people[3] = {
{"Arjuna", 1, 88000},
{"Krishna", 2, 92000},
{"Bhima", 3, 79000}
};

// Print details of each person


for (int i = 0; i < 3; ++i) {
cout << "Person " << (i + 1) << " details:" << endl;
cout << "Name: " << people[i].name << endl;
cout << "Citizen Number: " << people[i].cit_no << endl;
cout << "Salary: " << people[i].salary << endl << endl;
}

return 0;
}
Output:
Person 1 details:
Name: Arjuna
Citizen Number: 1
Salary: 88000

Person 2 details:
Name: Krishna
Citizen Number: 2
Salary: 92000

Person 3 details:
Name: Bhima
Citizen Number: 3
Salary: 79000

STRUCTURE AND UNION


7-5
PROBLEM SOLVING AND PROGRAMMING USING C++
7.4 UNION
• Union is a collection of elements of different data-type.
• Unlike structures, where each member has its own memory-location, all members of
a union share the same memory-location.
• Syntax:
union Union_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the Union.
• For example:
union Person
{
string name;
int cit_no;
float salary;
};
• The above code can be pictorially represented as shown below:

7.4.1 UNION-VARIABLE DECLARATION


• When you declare a Union-variable, you define an instance of that Union-type.
• Syntax:
union UnionName variableName;
• Example:
union person p1, p2;
• Here the above statement declares that p1 and p2 are variables of type union
person.
• Once the Union-variable is declared, the compiler allocates memory for the Union-
variables.
• The size of the memory allocated is determined by the largest member of the union
(salary in this case).

7.4.2 UNION-VARIABLE INITIALIZATION


• Union-variables can be declared and initialized at the time of declaration, but only
one member of the union can be initialized a value at any given time.
• Syntax:
union UnionName variableName = {value1};
• Example:
union Person p1 = {"rama"}; // Only the 'name' member is initialized
• Here, the above statement initializes p1 with name "rama".

STRUCTURE AND UNION


7-6
PROBLEM SOLVING AND PROGRAMMING USING C++
7.4.3 ACCESSING MEMBERS OF A UNION
• Members of a union are accessed using the member-access-operator (.).
• Syntax:
variableName.memberName
• Example:
cout << "Name: " << p1.name << endl;
• Here, the above statement accesses and prints the name member of Union p1.
• Program to illustrate use of union
#include <iostream>
#include <string> // Include the string library
using namespace std;

union Person {
string name;
int cit_no;
float salary;
};

int main() {
// Initialize the Union
Person p1;

p1.salary = 23000; // Corrected initialization

// Print salary
cout << "Initial salary: " << p1.salary << endl;

// Input new salary


cout << "Enter new salary: ";
cin >> p1.salary; // To read the new salary

// Print the updated salary


cout << "Updated salary: " << p1.salary << endl;

return 0;
}
Output:
Initial salary: 23000
Enter new salary: 35000
Updated salary: 35000

STRUCTURE AND UNION


7-7
PROBLEM SOLVING AND PROGRAMMING USING C++
7.5 STRUCTURE VS. UNION

STRUCTURE AND UNION


7-8
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 8: POINTERS

8.1 POINTER
8.1.1 DECLARATION & INITIALIZATION OF POINTER VARIABLE
8.2 POINTERS AND ARRAYS
8.3 POINTER ARITHMETIC

POINTERS
8-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 8: POINTERS

BASIC CONCEPT OF POINTERS


• As you know, every variable is a memory-location and every memory-location has
its address defined which can be accessed using ampersand(&) operator, which
denotes an address in memory.
• Consider the following example, which will print the address of the variables
defined:
#include <iostream>
using namespace std;

int main() {
int var1;

cout << "Address of var1 variable: " << &var1 << endl;

return 0;
}
Output:
Address of var1 variable: 1266

POINTERS
8-2
PROBLEM SOLVING AND PROGRAMMING USING C++
8.1 POINTER
• A pointer is a variable which holds address of another variable or a memory-
location.
• For ex:
c=22;
pc=&c;
Here pc is a pointer; it can hold the address of variable c
& is called reference operator

8.1.1 DECLARATION & INITIALIZATION OF POINTER VARIABLE


• Dereference operator(*) are used for defining pointer-variable.
• Syntax:
data_type *ptr_var_name;
• For ex:
int *a; // a as pointer variable of type int
float *c; // c as pointer variable of type float
• Steps to access data through pointers:
1) Declare a data-variable ex: int c;
2) Declare a pointer-variable ex: int *pc;
3) Initialize a pointer-variable ex: pc=&c;
4) Access data using pointer-variable ex: cout << *pc
• Program to illustrate working of pointers.
#include <iostream>
int main() {
int *pc;
int c;
c = 22;

cout << "Address of c: " << &c << endl;


cout << "Value of c: " << c << endl;

pc = &c;
cout << "Address of pointer pc: " << pc << endl;
cout << "Content of pointer pc: " << *pc << endl;

return 0;
}
Output:
Address of c: 1232
Value of c: 22
Address of pointer pc: 1232
Content of pointer pc: 22

POINTERS
8-3
PROBLEM SOLVING AND PROGRAMMING USING C++
8.2 POINTERS AND ARRAYS
• Consider an array:
int arr[4];
• The above code can be pictorially represented as shown below:

• The name of the array always points to the first element of an array.
• Here, address of first element of an array is &arr[0].
Also, ‘arr’ represents the address of the pointer where it is pointing.
Hence, &arr[0] is equivalent to arr.
• Value inside the address &arr[0] and address arr are equal.
Value in address &arr[0] is arr[0] and value in address arr is *arr.
Hence, arr[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
• You can declare an array and can use pointer to alter the data of an array.
• Program to access elements of an array using pointer.
#include <iostream>
using namespace std;

int main() {
int data[5];
int* ptr = data; // Pointer to the first element of the array

cout << "Enter elements: ";


for (int i = 0; i < 5; ++i) {
cin >> *(ptr + i); // Use pointer arithmetic to access array elements
}

cout << "You entered: ";


for (int i = 0; i < 5; ++i) {
cout << *(ptr + i) << " "; // Use pointer arithmetic to access array elements
}

return 0;
}
Output:
Enter elements: 1 2 3 5 4
You entered: 1 2 3 5 4

POINTERS
8-4
PROBLEM SOLVING AND PROGRAMMING USING C++
8.3 POINTER ARITHMETIC
• A pointer holds an address in memory, which is a numeric value.
• There are 4 arithmetic operators that can be used on pointers: ++, --, +, and –
• For example:
 You can perform increment operation on pointers, but the actual byte
increment depends on the data-type the pointer points to.
 Incrementing 1 to an int* pointer increases its address by 4 bytes.
• Program to increment the variable pointer to access each succeeding element of the
array.
#include <iostream>
using namespace std;

int main() {
int var[] = {222, 333, 444};
int i, *ptr;
ptr = var;

for (i = 0; i < 3; i++) {


cout << "Address of var[" << i << "] = " << ptr << endl;
cout << "Value of var[" << i << "] = " << *ptr << endl;
ptr++; // move to the next location
}
return 0;
}
Output:
Address of var[0] = 1130
Value of var[0] = 222
Address of var[1] = 1134
Value of var[1] = 333
Address of var[2] = 1138
Value of var[2] = 444

POINTERS
8-5
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 9: OBJECT ORIENTED CONCEPTS, CLASSES AND


OBJECTS

9.1 FEATURES OF OOP


9.1.1 ENCAPSULATION
9.1.2 INHERITANCE
9.1.3 POLYMORPHISM
9.1.4 ABSTRACTION
9.2 CLASS & OBJECT
9.3 DEFINING MEMBER-FUNCTIONS
9.4 STATIC MEMBER-DATA AND FUNCTIONS
9.5 ARRAY OF OBJECTS
9.6 PROCEDURAL PROGRAMMING VS OBJECT-ORIENTED PROGRAMMING

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 9: OBJECT ORIENTED CONCEPTS, CLASSES AND


OBJECTS

9.1 FEATURES OF OBJECT-ORIENTED PROGRAMMING (OOP)

9.1.1 ENCAPSULATION
Definition
• Encapsulation bundles data (attributes) and methods (functions) into a single unit
called a class.
Features
• Data Protection: Encapsulation hides the data inside a class, so it can't be easily
changed by mistake.
• Modularity: Encapsulation groups related data and functions together. This makes
the code easier to manage.
• Ease of Maintenance: A class can be modified without affecting other parts of the
program.

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-2
PROBLEM SOLVING AND PROGRAMMING USING C++
9.1.2 INHERITANCE
Definition
• Inheritance allows one class (child-class) to inherit properties and methods from
another class (parent-class).
Features
• Code Reusability: Inheritance allows the use of existing code in new classes,
eliminating the need to write it again.
• Extensibility: New features can be added to a class without altering the original
one.
• Hierarchical Organization: Inheritance helps organize classes in a way that
shows how they are related, like in a family tree.

9.1.3 POLYMORPHISM
Definition
• Polymorphism allows functions or objects to behave in different ways based on the
context.
Features
• Flexibility: Polymorphism allows the same function to work with different types of
objects.
• Simplified Code: The same method can be used for different purposes, making the
code simpler.
• Dynamic Binding: It lets the program choose which method to use while it’s
running.

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-3
PROBLEM SOLVING AND PROGRAMMING USING C++
9.1.4 ABSTRACTION
Definition
• Abstraction hides complex details and shows only the necessary parts to the user.
Features
• Complexity Management: Abstraction hides the complicated parts and shows only
what is needed. This makes it easier to understand.
• Improved Focus: It allows a focus on what an object does rather than how it does
it.
• Interface Implementation: Abstraction creates clear rules for what a class should
do, allowing different ways to do it.

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-4
PROBLEM SOLVING AND PROGRAMMING USING C++
9.2 CLASS AND OBJECT
9.2.1 CLASS
• Definition: A class is a user-defined data-type that represents a blueprint for
creating objects.
It encapsulates data-members (variables) and member-functions (methods)
that operate on the data.
• Definition: Member-variables hold the data for a class.
• Definition: Member-functions operate on the data of the class.
Member-functions are used to manipulate or access the member-variables.
• A class is declared using the `class` keyword.
• Syntax:
class ClassName {
DataType DataMember;
void Method();
};
• Example:
class Rectangle {
public:
int length; //Member-variable 1
int width; //Member-variable 2

int area() { //Member-function


return length * width;
}
};

ACCESS-SPECIFIERS
• Definition: Access-specifiers determine the visibility and accessibility of class-
members.
• Types:
i) Public: Members are accessible from outside the class.
ii) Private: Members are accessible only within the class.
iii) Protected: Members are accessible within the class and by derived-class.
• Syntax:
class ClassName {
public:
// Public-members
private:
// Private-members
protected:
// Protected-members
};

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-5
PROBLEM SOLVING AND PROGRAMMING USING C++
9.2.2 OBJECT
• Definition: Instances of a class is called object.
• Objects are used to access the member-variables and member-functions of the
class.
Object Creation
• Creating an object means allocating memory for a specific instance of a class.
• Syntax:
ClassName objectName;

Accessing Public-members
• Dot Operator: Used to access members of an object.
• Syntax:
objectName.memberName;
objectName.memberFunction();
Example: Program to illustrate class and object
class Rectangle {
public:
int length;
int width;

int area() {
return length * width;
}
};

int main() {
Rectangle rect; // Creating an object of the Rectangle class
rect.length = 5; // Accessing and setting the length attribute
rect.width = 10; // Accessing and setting the width attribute
cout << "Area: " << rect.area() << endl; // Accessing the area method
return 0;
}
Output:
Area: 50

Accessing Private-members
• Private-members cannot be accessed directly using the dot operator. They can only
be accessed through Public-member-functions.
• This is a key part of encapsulation, where the internal-data of the object is hidden
from the outside world.
class Rectangle {
private:
int length;
int width;

public:
void setDimensions(int l, int w) {

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-6
PROBLEM SOLVING AND PROGRAMMING USING C++
length = l;
width = w;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect;
rect.setDimensions(5, 10); // Using public-method to set Private-members
cout << "Area: " << rect.area() << endl;
return 0;
}
Output:
Area: 50

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-7
PROBLEM SOLVING AND PROGRAMMING USING C++
9.3 DEFINING MEMBER-FUNCTIONS
• Member-Functions can be defined in 2 ways
1) Inside the Class
• A Member-Function can be defined directly inside the class definition, which is
known as an inline definition.
2) Outside the Class
• A Member-Function can be declared inside the class and defined outside using the
scope resolution operator (::).
Case 1: Inside the Class
class Rectangle {
public:
int length, width;
int area() { // Definition inside the class
return length * width;
}
};
Case 2: Outside the Class
class Rectangle {
public:
int length, width;
int area(); // Declaration
};
int Rectangle::area() { // Definition outside the class
return length * width;
}
Types of Member-functions
• Accessor Functions: Used to retrieve the value of member-variables (often called
"getters").
• Mutator Functions: Used to modify the value of member-variables (often called
"setters").
• Utility Functions: Perform operations related to the class but may not directly
modify member-variables.
Example: Demonstrating Types of Member-functions
class Rectangle {
public:
void setLength(int l) { // Mutator function
length = l;
}
int getLength() { // Accessor function
return length;
}
int area() { // Utility function
return length * width;
}
private:
int length, width;
};

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-8
PROBLEM SOLVING AND PROGRAMMING USING C++
Usage in Program
• Member-functions are called using objects of the class.
• These functions perform tasks like setting values, performing calculations, and
displaying results.
int main() {
Rectangle rect;
rect.length=5;
rect.width=6;
cout << "Area: " << rect.area() << endl; // Calling a member-function
return 0;
}

"Const Member-Functions
• Functions that do not modify any member-variables can be declared as const
functions.
• This ensures that the function does not alter the state of the object.
class Rectangle {
public:
int area() const { // Const Member-Function
return length * width;
}
private:
int length, width;
};

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-9
PROBLEM SOLVING AND PROGRAMMING USING C++
9.4 STATIC MEMBER-DATA AND FUNCTIONS
Static Member-data
• Definition: A static member-data (or static data-member) is a variable that is
shared among all instances of a class.
• It is not specific to any individual object but belongs to the class itself.
• All objects of the class share the same static data-member, and changes made to it
by one object are reflected in all other objects.
Static Member-functions
• Definition: A static member-function can access only static data-members and
other static member-functions of the class.
• It can be called using the class-name without needing an object.
Accessing Static Member-data and Functions
• Static data-members are accessed using the class-name or through an object, but
using the class-name is the standard approach.
Advantages of Static Members
• Memory Efficiency: Static data-members save memory by not duplicating data for
each object instance.
• Class-Level Operations: Static member-functions can perform operations at the
class level rather than on individual objects.
Example: Demonstrating Static Member-Data and Functions
#include <iostream>

// Class definition
class Rectangle {
public:
int length;
int width;
static int rectangleCount; // Static data-member

// Default constructor to initialize the rectangle and increment the count


Rectangle() {
length = 0;
width = 0;
rectangleCount++; // Increment the count when a new object is created
}

// Parameterized constructor to initialize length & width, and increment the count
Rectangle(int l, int w) {
length = l;
width = w;
rectangleCount++; // Increment the count when a new object is created
}

// Member method to calculate the area of the rectangle


int area() const {
return length * width;
}

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-10
PROBLEM SOLVING AND PROGRAMMING USING C++

// Member method to set the dimensions of the rectangle


void setDimensions(int l, int w) {
length = l;
width = w;
}

// Static member-function to get the number of Rectangle objects created


static int getRectangleCount() {
return rectangleCount;
}
};

// Initialize static data-member outside the class


int Rectangle::rectangleCount = 0;

int main() {
// Create instances of the Rectangle class
Rectangle rect1(5, 10);
Rectangle rect2(7, 14);
Rectangle rect3(6, 12);

// Display dimensions and area for each rectangle


cout << "Rectangle 1 - << "Area: " << rect1.area() << endl;
cout << "Rectangle 2 - "Area: " << rect2.area() << endl;
cout << "Rectangle 3 - " Area: " << rect3.area() << endl;

// Display the total number of Rectangle objects created


cout << "No of Rectangles: " << Rectangle::getRectangleCount() << endl;

return 0;
}
Output:
Rectangle 1 - Area: 50
Rectangle 2 - Area: 98
Rectangle 3 - Area: 72
No of Rectangles: 3

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-11
PROBLEM SOLVING AND PROGRAMMING USING C++
9.5 ARRAY OF OBJECTS
• Definition: An array of objects is a collection of objects of the same class stored in
contiguous memory-locations.
• Each element in the array is an object that can have its own attributes and
methods.
• Example: Demonstrating Array of Objects
#include <iostream>
using namespace std;

// Class definition
class Rectangle {
public:
double length;
double width;

// Member method to calculate the area of the rectangle


double calculateArea() const {
return length * width;
}
};

int main() {
Rectangle rects[3]; // Array of 3 Rectangle objects

// Set dimensions for each rectangle


rects[0].length = 4.0;
rects[0].width = 2.0;

rects[1].length = 6.0;
rects[1].width = 3.0;

rects[2].length = 5.0;
rects[2].width = 5.0;

// Display area for each rectangle


for (int i = 0; i < 3; i++) {
cout << "Rectangle " << i+1 << " Area: " << rects[i].calculateArea() << endl;
}

return 0;
}
Output:
Rectangle 1 Area: 8
Rectangle 2 Area: 18
Rectangle 3 Area: 25

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-12
PROBLEM SOLVING AND PROGRAMMING USING C++
9.6 PROCEDURAL PROGRAMMING VS OBJECT-ORIENTED PROGRAMMING

OBJECT ORIENTED CONCEPTS, CLASSES AND OBJECTS


9-13
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 10: CONSTRUCTORS AND DESTRUCTORS

10.1 CONSTRUCTORS
10.2 TYPES OF CONSTRUCTORS
10.2.1 DEFAULT CONSTRUCTOR
10.2.2 PARAMETERIZED CONSTRUCTOR
10.2.3 COPY CONSTRUCTOR
10.2.4 DYNAMIC CONSTRUCTOR
10.3 CONSTRUCTOR OVERLOADING
10.4 DESTRUCTORS

CONSTRUCTORS AND DESTRUCTORS


10-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 10: CONSTRUCTORS AND DESTRUCTORS

10.1 CONSTRUCTORS
• Special Member Function: Constructors are special member functions that are
automatically called when an object of a class is created.
• Same Name as Class: A constructor has the same name as the class and does not
have a return type, not even `void`.
• Initialization of Objects: The primary purpose of a constructor is to initialize the
objects of its class.
• Automatic Invocation: Constructors are automatically invoked when an object is
created.
• Types
i) Default Constructor
ii) Parameterized Constructor
iii) Copy Constructor
iv) Dynamic Constructor

CONSTRUCTORS AND DESTRUCTORS


10-2
PROBLEM SOLVING AND PROGRAMMING USING C++
10.2 TYPES OF CONSTRUCTORS
10.2.1 DEFAULT CONSTRUCTOR
Definition
• A default constructor is a constructor that takes no arguments.
Purpose
• It initializes objects with default values.
Features
• It does not take any parameters.
• The compiler automatically creates a constructor if none is defined.
• It sets member variables to default values like `0` for integers.
Example
class Rectangle {
public:
Rectangle() { // Default Constructor
length = 0;
width = 0;
}
private:
int length;
int width;
};

10.2.2 PARAMETERIZED CONSTRUCTOR


Definition
• A parameterized constructor takes one or more arguments.
Purpose
• It allows objects to be initialized with specific values.
Features
• It requires arguments to initialize variables.
• Multiple constructors with different arguments can be created (overloading).
• It initializes the object with the provided values.
Example
class Rectangle {
public:
Rectangle(int l, int w) { // Parameterized Constructor
length = l;
width = w;
}
private:
int length;
int width;
};

CONSTRUCTORS AND DESTRUCTORS


10-3
PROBLEM SOLVING AND PROGRAMMING USING C++
10.2.3 COPY CONSTRUCTOR
Definition
• A copy constructor creates a new object by copying an existing one.
Purpose
• It ensures that all values from the original object are copied to the new one.
Features
• It takes one argument, which is a reference to an object of the same class.
• If the object has pointers, the copy constructor can create new memory (deep
copy).
• If not defined, the compiler provides a basic version (shallow copy).
Example
class Rectangle {
public:
Rectangle(const Rectangle &rect) { // Copy Constructor
length = rect.length;
width = rect.width;
}
private:
int length;
int width;
};

10.2.4 DYNAMIC CONSTRUCTOR


Definition
• A dynamic constructor allocates memory at runtime using the `new` keyword.
Purpose
• Memory for variables is allocated when an object is created.
Features
• It uses `new` to allocate memory for data members.
• A destructor is typically defined to free memory using `delete`.
• It allows the object to manage its own memory based on runtime needs.
Example
class Rectangle {
public:
Rectangle(int l, int w) { // Dynamic Constructor
length = new int(l);
width = new int(w);
}
~Rectangle() { // Destructor to release memory
delete length;
delete width;
}
private:
int *length;
int *width;
};

CONSTRUCTORS AND DESTRUCTORS


10-4
PROBLEM SOLVING AND PROGRAMMING USING C++
Example: Program to illustrate Default Constructor, Parameterized Constructor and
Copy Constructor
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Default Constructor
Rectangle() {
length = 0;
width = 0;
}

// Parameterized Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

// Copy Constructor
Rectangle(const Rectangle &rect) {
length = rect.length;
width = rect.width;
}

// Method to set dimensions


void setDimensions(int l, int w) {
length = l;
width = w;
}

// Method to calculate area


int area() {
return length * width;
}

// Method to display dimensions


void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};

CONSTRUCTORS AND DESTRUCTORS


10-5
PROBLEM SOLVING AND PROGRAMMING USING C++
int main() {
// Default Constructor
Rectangle rect1;
cout << "Rectangle 1 (Default Constructor):" << endl;
rect1.display();
cout << "Area: " << rect1.area() << endl << endl;

// Parameterized Constructor
Rectangle rect2(5, 10);
cout << "Rectangle 2 (Parameterized Constructor):" << endl;
rect2.display();
cout << "Area: " << rect2.area() << endl << endl;

// Copy Constructor
Rectangle rect3(rect2);
cout << "Rectangle 3 (Copy Constructor from Rectangle 2):" << endl;
rect3.display();
cout << "Area: " << rect3.area() << endl << endl;

return 0;
}
Output:
Rectangle 1 (Default Constructor):
Length: 0, Width: 0
Area: 0

Rectangle 2 (Parameterized Constructor):


Length: 5, Width: 10
Area: 50

Rectangle 3 (Copy Constructor from Rectangle 2):


Length: 5, Width: 10
Area: 50

CONSTRUCTORS AND DESTRUCTORS


10-6
PROBLEM SOLVING AND PROGRAMMING USING C++
Example: Program to illustrate Dynamic Constructor
#include <iostream>
using namespace std;

class Rectangle {
public:
// Dynamic Constructor
Rectangle(int l, int w) {
length = new int(l); // Dynamically allocate memory for length
width = new int(w); // Dynamically allocate memory for width
}

// Destructor to release memory


~Rectangle() {
delete length; // Free the dynamically allocated memory for length
delete width; // Free the dynamically allocated memory for width
}

// Method to calculate the area of the rectangle


int area() const {
return (*length) * (*width);
}

// Method to display the dimensions of the rectangle


void display() const {
cout << "Length: " << *length << ", Width: " << *width << endl;
}

private:
int *length; // Pointer to dynamically allocated length
int *width; // Pointer to dynamically allocated width
};

int main() {
// Create a Rectangle object using the dynamic constructor
Rectangle rect(5, 10);
// Display the dimensions of the rectangle
rect.display();
// Calculate and display the area of the rectangle
cout << "Area: " << rect.area() << endl;
// The destructor is called automatically when rect goes out of scope
return 0;
}
Output:
Length: 5, Width: 10
Area: 50

CONSTRUCTORS AND DESTRUCTORS


10-7
PROBLEM SOLVING AND PROGRAMMING USING C++
10.3 CONSTRUCTOR OVERLOADING
Definition
• Constructor overloading means having more than one constructor in a class, each
with different parameters.
Purpose
• This allows objects to be initialized in different ways.
Features
• Multiple Constructors: A class can have more than one constructor.
• Flexibility: Overloaded constructors allow the creation of objects with different initial
values.
• Easy to Read: Overloading constructors makes the code easier to read and
understand.
Example: Program to illustrate Constructor Overloading
#include <iostream>

class Rectangle {
private:
int length, width;

public:
// Default Constructor
Rectangle() {
length = 0;
width = 0;
}

// Parameterized Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

// Square Constructor (same length and width)


Rectangle(int size) {
length = width = size;
}

// Method to set dimensions


void setDimensions(int l, int w) {
length = l;
width = w;
}

// Method to calculate area


int area() {
return length * width;
}

CONSTRUCTORS AND DESTRUCTORS


10-8
PROBLEM SOLVING AND PROGRAMMING USING C++

// Method to display dimensions


void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};

int main() {
// Default Constructor
Rectangle rect1;
cout << "Rectangle 1 (Default Constructor):" << endl;
rect1.display();
cout << "Area: " << rect1.area() << endl << endl;

// Parameterized Constructor
Rectangle rect2(5, 10);
cout << "Rectangle 2 (Parameterized Constructor):" << endl;
rect2.display();
cout << "Area: " << rect2.area() << endl << endl;

// Square Constructor
Rectangle rect3(7);
cout << "Rectangle 3 (Square Constructor):" << endl;
rect3.display();
cout << "Area: " << rect3.area() << endl << endl;

return 0;
}
Output:
Rectangle 1 (Default Constructor):
Length: 0, Width: 0
Area: 0

Rectangle 2 (Parameterized Constructor):


Length: 5, Width: 10
Area: 50

Rectangle 3 (Square Constructor):


Length: 7, Width: 7
Area: 49

CONSTRUCTORS AND DESTRUCTORS


10-9
PROBLEM SOLVING AND PROGRAMMING USING C++
10.4 DESTRUCTORS
• Special Function: Destructors are special functions that run automatically when an
object is destroyed.
• Name with Tilde (~): A destructor has the same name as the class but starts with
a tilde (`~`). It has no return type or parameters.
• Cleans Up Resources: The main job of a destructor is to clean up resources like
memory or file handles when an object is no longer needed.
• Runs Automatically: Destructors run automatically when an object goes out of
scope or is deleted.
• Example: Program to illustrate Destructors
#include <iostream>
class Rectangle {
public:
// Public data members
int length, width;

// Constructor
Rectangle(int l, int w) {
length = l;
width = w;
cout << "Rectangle is created << endl;
}

// Destructor
~Rectangle() {
cout << "Rectangle is destroyed" << endl;
}

// Public member function to calculate area


int area() {
return length * width;
}
};

int main() {
// Creating an object of Rectangle class
Rectangle rect(10, 5);

// Displaying the area


cout << "Area: " << rect.area() << endl;
return 0;
}
Output:
Rectangle is created
Area: 50
Rectangle is destroyed

CONSTRUCTORS AND DESTRUCTORS


10-10
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 11: OPERATOR-OVERLOADING

11.1 INTRODUCTION TO OPERATOR-OVERLOADING


11.2 RULES FOR OPERATOR-OVERLOADING
11.3 OVERLOADING UNARY OPERATOR
11.3.1 UNARY OPERATOR-OVERLOADING USING MEMBER FUNCTIONS
11.3.2 UNARY OPERATOR-OVERLOADING USING NON-MEMBER FUNCTIONS
11.4 OVERLOADING BINARY OPERATOR
11.4.1 BINARY OPERATOR-OVERLOADING USING MEMBER FUNCTIONS
11.4.2 BINARY OPERATOR-OVERLOADING USING NON-MEMBER FUNCTIONS

OPERATOR OVERLOADING
11-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 11: OPERATOR-OVERLOADING

11.1 INTRODUCTION TO OPERATOR-OVERLOADING


• Definition: Operator overloading allows custom behaviors to be defined for
operators when used with objects of user-defined classes.
• Purpose: It enables the use of traditional operators like +, -, *, and == with
objects.
Features
• Custom Behavior: The behavior of operators with objects can be determined as
needed.
• Improved Readability: Operators can be used in expressions with objects, making
the code easier to read. For example, `a + b` can be used instead of `add(a, b)`.
• Member and Non-Member Functions: Operators can be overloaded using
member functions (affecting the object) or non-member functions (can involve
multiple objects).
• Syntax: Overloaded operators must be defined with the operator keyword, followed
by the operator symbol.

OPERATOR OVERLOADING
11-2
PROBLEM SOLVING AND PROGRAMMING USING C++
11.2 RULES FOR OPERATOR-OVERLOADING
1) Cannot Change Operator Precedence
• The order in which operators are evaluated and their grouping cannot be changed;
the existing rules still apply.
2) Cannot Overload Certain Operators
• Some operators like `::` (scope resolution), `.` (member access), `.*` (member
pointer access), and `?:` (ternary conditional) cannot be overloaded.
3) Operator Function Must Be Defined
• The operator function must be either a member function or a non-member function.
• Member functions operate on the object they are called on, while non-member
functions take two parameters.
4) Must Have a Return Type
• The operator function must return a value.
• The return type can be the class type or any other type as needed.
5) Overload Operators with Care
• Overloading should be done carefully to avoid confusing or unexpected behaviors.
• For example, `+` should combine objects in a meaningful way, and `-` should
negate or subtract values.
6) Operator-overloading Does Not Create New Operators
• Overloading an operator changes how an existing operator works with user-defined
types.
• It does not create a new operator.
7) No Default Operator-overloading
• The default behavior of operators for built-in types does not apply to user-defined
types.
• Each operator must be overloaded explicitly to define custom behavior.

OPERATOR OVERLOADING
11-3
PROBLEM SOLVING AND PROGRAMMING USING C++
11.3 OVERLOADING UNARY OPERATOR
• Definition: Overloading operators that take a single operand.
Examples: +, -, ++, --, !, ~
• Purpose: To extend the functionality of unary operators to work with objects.
• Typically, the unary operator is implemented as a member function.

11.3.1 UNARY OPERATOR-OVERLOADING USING MEMBER FUNCTIONS


Syntax:
ReturnType operator op();
Where:
- `ReturnType`: The type of value that the operator will return.
- `operator op`: The operator being overloaded. It does not take any parameters
other than the implicit `this` pointer.
Example: Program to complement a complex number
#include <iostream>
class Complex {
private:
int real, imag;
public:

// Overloading unary `-` operator


Complex operator-() const {
return Complex(-real, -imag);
}

// Function to display complex number


void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
// Create a Complex object
Complex c1(4, 5);

cout << "Original Complex number: ";


c1.display();

Complex c2 = -c1; // Apply unary `-` operator

cout << "After applying unary `-` operator: ";


c2.display();

return 0;
}
Output:
Original Complex number: 4 + 5i
After applying unary `-` operator: -4 + -5i

OPERATOR OVERLOADING
11-4
PROBLEM SOLVING AND PROGRAMMING USING C++
11.4 OVERLOADING BINARY OPERATOR
• Definition: Overloading operators that take two operands.
Examples: +, -, *, /, ==, <, !=
• Purpose: To extend the functionality of binary operators to work with objects.
• The binary operator can be implemented as a member function or a friend function.
11.4.1 BINARY OPERATOR-OVERLOADING USING MEMBER FUNCTIONS
Syntax:
ReturnType operator op(const ClassName& other);
Where:
- `ReturnType`: The type of value that the operator will return.
- `operator op`: The operator being overloaded. It takes one parameter
(`other`), which is the second operand of the binary operation.
- `const ClassName& other`: The parameter represents the second operand
Example: Program to add 2 complex numbers
#include <iostream>
class Complex {
private:
int real, imag;
public:
// Overloading binary `+` operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}

// Function to display the complex number


void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
// Create two Complex objects
Complex c1(4, 5), c2(1, 2);

// Add two Complex numbers using the overloaded `+` operator


Complex c3 = c1 + c2;

cout << "Complex number 1: ";


c1.display();

cout << "Complex number 2: ";


c2.display();

cout << "Result of adding: ";


c3.display();
return 0;
}
Output:
Complex number 1: 4 + 5i
Complex number 2: 1 + 2i
Result of adding : 5 + 7i

OPERATOR OVERLOADING
11-5
PROBLEM SOLVING AND PROGRAMMING USING C++
11.4.2 BINARY OPERATOR-OVERLOADING USING FRIEND FUNCTIONS
Syntax:
ReturnType operator op(const ClassName& lhs, const ClassName& rhs);
Where:
- `ReturnType`: The type of value that the operator will return.
- `operator op`: The operator being overloaded. It takes two parameters (`lhs`
and `rhs`), representing the left and right operands of the binary operation.
- `const ClassName& lhs` and `const ClassName& rhs`: The parameters
represent the two operands.
Example: Program to add 2 complex numbers
#include <iostream>
class Complex {
private:
int real, imag;
public:
// Overloading binary `+` operator as a non-member function
friend Complex operator+(const Complex& lhs, const Complex& rhs);

// Function to display the complex number


void display() const {
cout << real << " + " << imag << "i" << endl;
}
};

// Non-member function to overload binary `+` operator


Complex operator+(const Complex& lhs, const Complex& rhs) {
return Complex(lhs.real + rhs.real, lhs.imag + rhs.imag);
}
int main() {
// Create two Complex objects
Complex c1(4, 5), c2(1, 2);

// Add two Complex numbers using the overloaded `+` operator


Complex c3 = c1 + c2;

cout << "Complex number 1: ";


c1.display();

cout << "Complex number 2: ";


c2.display();

cout << "Result of adding: ";


c3.display();
return 0;
}
Output:
Complex number 1: 4 + 5i
Complex number 2: 1 + 2i
Result of adding: 5 + 7i

OPERATOR OVERLOADING
11-6
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 12: INHERITANCE

12.1 ACCESS-SPECIFIERS
12.2 TYPES OF INHERITANCE
12.2.1 SINGLE-INHERITANCE
12.2.2 MULTI LEVEL INHERITANCE
12.2.3 MULTIPLE-INHERITANCE
12.2.4 HIERARCHICAL-INHERITANCE
12.2.5 HYBRID-INHERITANCE
12.2.6 MULTI PATH INHERITANCE
12.3 VIRTUAL BASE-CLASSES
12.4 ABSTRACT-CLASSES
12.5 VIRTUAL-FUNCTIONS

INHERITANCE
12-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 12: INHERITANCE

12.1 INHERITANCE
Definition
• Inheritance allows a new-class to inherit properties & behaviors (methods) from an
existing-class.
The new-class is called as the derived-class.
The existing-class is called as the base-class.
Access-Specifiers
• Access-Specifiers determine the accessibility of the base-class-members in the
derived-class.
i) public: Public-members of the base-class become public in the derived-class
ii) protected: Public- and protected-members of the base-class become
protected in the derived-class
iii) private: Public- and protected-members of the base-class become private
in the derived-class
Syntax
class BaseClass {
public:
// Base-class-members
};

class DerivedClass : public BaseClass {


public:
// Derived-class members
};
Advantages
i) Code Reusability
• The derived-class can reuse code from the base-class. This reduces repeated-code.
ii) Extensibility
• New features can be added to existing-classes w/o modifying them directly.
• This enhances the system's flexibility.
iii) Maintainability
• Changes made to the base-class are automatically available to all derived-classes.
• This makes it easier to maintain the code.
Types of Inheritance
i) Single-Inheritance
ii) Multiple-Inheritance
iii) Multilevel Inheritance
iv) Hierarchical-Inheritance
v) Hybrid-Inheritance
vi) Multi-Path Inheritance

INHERITANCE
12-2
PROBLEM SOLVING AND PROGRAMMING USING C++

Figure 12.1: Types of Inheritance

INHERITANCE
12-3
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2 TYPES OF INHERITANCE
12.2.1 SINGLE-INHERITANCE
Definition
• Single-Inheritance allows a derived-class to inherit properties & behaviors from only
one base-class.

Figure 12.2: Single-Inheritance


Features
• Code Reusability: The derived-class can reuse code from the base-class. This
reduces repeated-code.
• Extensibility: New features can be added to existing-classes without modifying
them directly.
• Access Control: The derived-class can control how much of the base-class it
exposes.
• Hierarchical Representation: The relationship between classes is clear and easy
to understand.
Syntax
class BaseClass {
// Base-class-members
};

class DerivedClass : public BaseClass {


// Derived-class members
};
Where,
BaseClass: The class from which properties are inherited.
DerivedClass: The class that inherits properties.
public: Defines how the derived-class can use inherited-members.

INHERITANCE
12-4
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Single-Inheritance
#include <iostream>
using namespace std;

// Base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Derived-class
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};

int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal class
myDog.bark(); // Defined in Dog class
return 0;
}
Output:
Eating...
Barking...
Explanation
• The `Animal` class has a function called `eat()`.
• The `Dog` class inherits from `Animal` and has its own function called `bark()`.
• In the `main()` function, the `Dog` object can use both `eat()` from `Animal`
and `bark()` from `Dog`.

INHERITANCE
12-5
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2.2 MULTI-LEVEL INHERITANCE
Definition
• Multi-Level Inheritance is when a class is derived from another derived-class.
• This creates a chain where each class inherits from the one above it.

Figure 12.3: Multi-Level Inheritance

Features
• Code Reusability: The final-class can reuse code from all classes in the chain.
• Transitive Inheritance: A class can use features from its base-class and also from
classes higher in the chain.
• Hierarchical Structuring: It allows creating complex class-structures that show
clear relationships.
• Incremental Development: Each class can add features gradually as it inherits
from the previous one.
Syntax
class BaseClass {
// Base-class-members
};

class IntermediateClass : public BaseClass {


// Intermediate class members
};

class DerivedClass : public IntermediateClass {


// Derived-class members
};
Where
BaseClass: The class at the start of the chain.
IntermediateClass: A class that inherits from BaseClass and serves as a base
for the next class.
DerivedClass: The class that inherits from IntermediateClass.

INHERITANCE
12-6
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Multi-Level Inheritance
#include <iostream>

// Base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Intermediate derived-class
class Mammal : public Animal {
public:
void walk() {
cout << "Walking..." << endl;
}
};

// Final derived-class
class Dog : public Mammal {
public:
void bark() {
cout << "Barking..." << endl;
}
};

int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal class
myDog.walk(); // Inherited from Mammal class
myDog.bark(); // Defined in Dog class
return 0;
}
Output:
Eating...
Walking...
Barking...
Explanation
• The `Animal` class has a function `eat()`.
• The `Mammal` class inherits from `Animal` and has a function `walk()`.
• The `Dog` class inherits from `Mammal` and has a function `bark()`.
• In the `main()` function, the `Dog` object can use all three functions: `eat()`
from `Animal`, `walk()` from `Mammal`, and `bark()` from `Dog`.

INHERITANCE
12-7
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2.3 MULTIPLE-INHERITANCE
Definition
• Multiple-Inheritance allows a class to inherit from more than one base-class.
• This helps the derived-class to use features from multiple-classes.

Figure 12.4: Multiple Inheritance

Features
• Combining Features: The derived-class can use features from all its base-classes.
This makes it flexible.
• Complex Relationships: It helps create more complex class-structures.
• Avoiding Redundancy: Common features from different classes can be combined
in one class. This reduces repeated-code.
• Conflict Resolution: If two base-classes have functions with the same name, the
derived-class must decide which one to use.
Syntax
class BaseClass1 {
// Base-class 1 members
};

class BaseClass2 {
// Base-class 2 members
};

class DerivedClass : public BaseClass1, public BaseClass2 {


// Derived-class members
};

Where,
BaseClass1: The first base-class.
BaseClass2: The second base-class.
DerivedClass: The class that inherits from both BaseClass1 and BaseClass2.

INHERITANCE
12-8
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Multiple-Inheritance
#include <iostream>

// First base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Second base-class
class Bird {
public:
void fly() {
cout << "Flying..." << endl;
}
};

// Derived-class
class Bat : public Animal, public Bird {
public:
void sleep() {
cout << "Sleeping..." << endl;
}
};

int main() {
Bat myBat;
myBat.eat(); // Inherited from Animal class
myBat.fly(); // Inherited from Bird class
myBat.sleep(); // Defined in Bat class
return 0;
}
Output:
Eating...
Flying...
Sleeping...
Explanation
• The `Animal` class has a function `eat()`.
• The `Bird` class has a function `fly()`.
• The `Bat` class inherits from both `Animal` and `Bird` and has a function
`sleep()`.
• In the `main()` function, the `Bat` object can use all three functions: `eat()` from
`Animal`, `fly()` from `Bird`, and `sleep()` from `Bat`.

INHERITANCE
12-9
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2.4 HIERARCHICAL-INHERITANCE
Definition
• Hierarchical-Inheritance is when multiple derived-classes inherit from the same
base-class.
• This lets different classes share features of one common class.

Figure 12.5: Hierarchical-Inheritance

Features
• Shared Base-class: Different derived-classes use the features of the same base-
class.
• Code Reusability: Common code in the base-class is reused by all derived-classes.
This reduces repeated-code.
• Organized Structure: It organizes related classes under one base-class, making
the structure clear.
• Extended Functionality: Each derived-class can add features while still inheriting
from the base-class.
Syntax
class BaseClass {
// Base-class-members
};

class DerivedClass1 : public BaseClass {


// Derived-class 1 members
};

class DerivedClass2 : public BaseClass {


// Derived-class 2 members
};
Where,
BaseClass: The class from which other classes inherit.
DerivedClass1: A class that inherits from BaseClass.
DerivedClass2: Another class that inherits from BaseClass.

INHERITANCE
12-10
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Hierarchical-Inheritance
#include <iostream>
// Base-class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
// First derived-class
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};

// Second derived-class
class Cat : public Animal {
public:
void meow() {
cout << "Meowing..." << endl;
}
};

int main() {
Dog myDog;
Cat myCat;

myDog.eat(); // Inherited from Animal class


myDog.bark(); // Defined in Dog class

myCat.eat(); // Inherited from Animal class


myCat.meow(); // Defined in Cat class
return 0;
}
Output:
Eating...
Barking...
Eating...
Meowing...
Explanation
• The `Animal` class has a function `eat()`.
• The `Dog` class inherits from `Animal` and adds a function `bark()`.
• The `Cat` class also inherits from `Animal` and adds a function `meow()`.
• In the `main()` function, the `Dog` and `Cat` objects can both use the `eat()`
function from `Animal`, and their own specific functions (`bark()` and `meow()`).

INHERITANCE
12-11
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2.5 HYBRID-INHERITANCE
Definition
• Hybrid-Inheritance combines two or more types of inheritance in a single program.
• It mixes different inheritance styles, like single, multiple and multilevel.

Figure 12.6: Hybrid-Inheritance


Features
• Flexible Structure: Hybrid-Inheritance creates a flexible and complex class-
structure by combining different inheritance types.
• Code Reusability: It allows reusing code from multiple base-classes across
different inheritance chains.
• Combining Features: The derived-class can use features from multiple base-
classes, even if they follow different inheritance patterns.
• Conflict Resolution: Hybrid-Inheritance may require careful handling to resolve
conflicts when base-classes have methods with the same name.
Syntax
class BaseClass1 {
// Base-class 1 members
};

class BaseClass2 {
// Base-class 2 members
};

class IntermediateClass : public BaseClass1 {


// Intermediate class members
};

class DerivedClass : public IntermediateClass, public BaseClass2 {


// Derived-class members
};
Where,
BaseClass1: One base-class.
BaseClass2: Another base-class.
IntermediateClass: A class that inherits from BaseClass1.
DerivedClass: The final-class that inherits from both IntermediateClass and
BaseClass2.

INHERITANCE
12-12
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Hybrid-Inheritance
#include <iostream>
// Base-class 1
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Base-class 2
class Mammal {
public:
void breathe() {
cout << "Breathing..." << endl;
}
};

// Intermediate class (inherits from Animal)


class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};

// Derived-class (inherits from Dog and Mammal)


class Bulldog : public Dog, public Mammal {
public:
void display() {
cout << "I am a Bulldog." << endl;
}
};

int main() {
Bulldog myBulldog;
myBulldog.eat(); // Inherited from Animal class
myBulldog.breathe(); // Inherited from Mammal class
myBulldog.bark(); // Inherited from Dog class
myBulldog.display(); // Defined in Bulldog class
return 0;
}
Output:
Eating...
Breathing...
Barking...
I am a Bulldog.

INHERITANCE
12-13
PROBLEM SOLVING AND PROGRAMMING USING C++
Explanation
• The `Animal` class has a function `eat()`.
• The `Mammal` class has a function `breathe()`.
• The `Dog` class inherits from `Animal` and adds a function `bark()`.
• The `Bulldog` class inherits from both `Dog` and `Mammal` and adds a function
`display()`.
• In the `main()` function, the `Bulldog` object can use all functions from `Animal`,
`Mammal`, and `Dog`, along with its own function `display()`.

INHERITANCE
12-14
PROBLEM SOLVING AND PROGRAMMING USING C++
12.2.6 MULTI-PATH INHERITANCE
Definition
• Multi-Path Inheritance happens when a class inherits from multiple base-classes.
• These base-classes might also have a common base-class.
• This creates multiple-paths of inheritance.

Figure 12.7: Multi-Path Inheritance


Features
• Multiple-paths: A derived-class inherits features from several base-classes, which
may share a common base-class.
• Complex Hierarchy: It creates a complex inheritance structure with many paths.
• Code Reusability: The derived-class can reuse code from multiple base-classes.
• Conflict Resolution: It requires careful handling to avoid conflicts when base-
classes have similar features.
Syntax
class BaseClass {
// Base-class-members
};

class BaseClass1 : public BaseClass {


// Base-class 1 members
};

class BaseClass2 : public BaseClass {


// Base-class 2 members
};

class DerivedClass : public BaseClass1, public BaseClass2 {


// Derived-class members
};
Where,
BaseClass: The common base-class.
BaseClass1: Inherits from BaseClass.
BaseClass2: Also inherits from BaseClass.
DerivedClass: Inherits from both BaseClass1 and BaseClass2.

INHERITANCE
12-15
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Multi-Path Inheritance
#include <iostream>
using namespace std;

// Common base-class
class LivingBeing {
public:
void breathe() {
cout << "Breathing..." << endl;
}
};

// First base-class
class Animal : public LivingBeing {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Second base-class
class Plant : public LivingBeing {
public:
void photosynthesize() {
cout << "Photosynthesizing..." << endl;
}
};

// Derived-class (inherits from both Animal and Plant)


class Hybrid : public Animal, public Plant {
public:
void display() {
cout << "I am a Hybrid." << endl;
}
};

int main() {
Hybrid myHybrid;
myHybrid.breathe(); // From LivingBeing class
myHybrid.eat(); // From Animal class
myHybrid.photosynthesize(); // From Plant class
myHybrid.display(); // From Hybrid class
return 0;
}
Output:
Breathing...
Eating...
Photosynthesizing...
I am a Hybrid.

INHERITANCE
12-16
PROBLEM SOLVING AND PROGRAMMING USING C++
Explanation
• The `LivingBeing` class has a function `breathe()`.
• The `Animal` class inherits from `LivingBeing` and has a function `eat()`.
• The `Plant` class also inherits from `LivingBeing` and has a function
`photosynthesize()`.
• The `Hybrid` class inherits from both `Animal` and `Plant` and adds a function
`display()`.
• In the `main()` function, the `Hybrid` object can use functions from `LivingBeing`,
`Animal`, and `Plant`, plus its own function `display()`.

INHERITANCE
12-17
PROBLEM SOLVING AND PROGRAMMING USING C++
12.3 VIRTUAL BASE-CLASSES
Definition
• Virtual Base-classes make sure there is only one instance of a base-class when
using multiple-Inheritance.
• This avoids having multiple copies of the same base-class.

Figure 12.8: Non-virtual & Virtual Base-classes


Features
• Single Instance: Ensures only one instance of the virtual base-class is created.
• Solves Diamond Problem: Fixes the diamond problem where a base-class is
inherited through multiple-paths.
• Reduces Ambiguity: Avoids confusion by keeping one copy of base-class data.
• Consistency: Keeps behavior consistent by sharing the same base-class instance.
Syntax
class BaseClass {
// Base-class-members
};

class DerivedClass1 : virtual public BaseClass {


// Derived-class 1 members
};

class DerivedClass2 : virtual public BaseClass {


// Derived-class 2 members
};

class FinalDerivedClass : public DerivedClass1, public DerivedClass2 {


// Final derived-class members
};

Where,
BaseClass: The virtual base-class.
DerivedClass1: Inherits from BaseClass as a virtual base-class.
DerivedClass2: Also inherits from BaseClass as a virtual base-class.
FinalDerivedClass: Inherits from both DerivedClass1 and DerivedClass2, using
only one instance of BaseClass.

INHERITANCE
12-18
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Virtual Base-classes
#include <iostream>
using namespace std;

// Virtual base-class
class Base {
public:
int value;
Base() : value(0) {}
void showValue() {
cout << "Value: " << value << endl;
}
};

// Derived-class 1 (inherits Base virtually)


class Derived1 : virtual public Base {
public:
void setValue(int v) {
value = v;
}
};

// Derived-class 2 (inherits Base virtually)


class Derived2 : virtual public Base {
public:
void increaseValue() {
value++;
}
};

// Final derived-class (inherits from Derived1 and Derived2)


class FinalDerived : public Derived1, public Derived2 {
public:
void display() {
showValue();
}
};

int main() {
FinalDerived obj;
obj.setValue(10);
obj.increaseValue();
obj.display(); // Outputs: Value: 11
return 0;
}
Output:
Value: 11

INHERITANCE
12-19
PROBLEM SOLVING AND PROGRAMMING USING C++
Explanation
• The `Base` class has a member `value` and a method `showValue()`.
• `Derived1` inherits from `Base` virtually and has a method `setValue()`.
• `Derived2` also inherits from `Base` virtually and has a method `increaseValue()`.
• `FinalDerived` inherits from both `Derived1` and `Derived2`, using only one
instance of `Base`.
• In the `main()` function, the `FinalDerived` object uses methods from `Derived1`,
`Derived2`, and `Base`, with correct behavior.

INHERITANCE
12-20
PROBLEM SOLVING AND PROGRAMMING USING C++
12.4 ABSTRACT-CLASSES
Definition
• Abstract classes are classes from which objects cannot be created directly.
• They define functions that derived-classes must implement.
• They have at least one pure virtual-function.

Figure 12.9: Abstract classes


Features
• Cannot be Instantiated: Objects cannot be created from an abstract class.
• Pure Virtual-functions: They have at least one pure virtual-function, which is a
function with no definition.
• Defines Interface: They provide a common interface that derived-classes must
follow.
• Encourages Reusability: They allow methods to be defined that can be reused
and overridden in derived classes.
Syntax
class AbstractClass {
public:
virtual void pureVirtualFunction() = 0; // Pure virtual-function
// Other members
};

Where,
AbstractClass: The class with at least one pure virtual-function.
pureVirtualFunction(): A pure virtual-function, marked with `= 0`.
Example Program: Demonstrating Abstract-Classes
#include <iostream>
#include <cmath> // For M_PI constant

using namespace std;

// Abstract base class


class Shape {
public:
// Pure virtual function for calculating area
virtual double calcArea() = 0;
};

// Derived class for Circle

INHERITANCE
12-21
PROBLEM SOLVING AND PROGRAMMING USING C++
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}

// Override calcArea to calculate the area of the circle


double calcArea() override {
return M_PI * radius * radius;
}
};

// Derived class for Rectangle


class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}

// Override calcArea to calculate the area of the rectangle


double calcArea() override {
return length * width;
}
};

int main() {
// Create objects of derived classes
Circle myCircle(5.0);
Rectangle myRectangle(4.0, 6.0);

// Calculate and display areas


cout << "Area of Circle: " << myCircle.calcArea() << endl;
cout << "Area of Rectangle: " << myRectangle.calcArea() << endl;
return 0;
}
Output:
Area of Circle: 78.5398
Area of Rectangle: 24
Explanation:
- Shape Class: This is an abstract base class with a pure virtual function
`calcArea()`. This makes `Shape` an abstract class, meaning it cannot be
instantiated on its own.
- Circle Class: This class inherits from `Shape` and implements the `calcArea()`
function to calculate the area of a circle using the formula Area = π times radius^2 .
- Rectangle Class: This class also inherits from `Shape` and implements the
`calcArea()` function to calculate the area of a rectangle using the formula Area =
length X width
- Main Function: In the `main()` function, objects of `Circle` and `Rectangle` are
created, and their areas are calculated and displayed.

INHERITANCE
12-22
PROBLEM SOLVING AND PROGRAMMING USING C++
VIRTUAL BASE-CLASSES VS. ABSTRACT-CLASSES

INHERITANCE
12-23
PROBLEM SOLVING AND PROGRAMMING USING C++
12.5 VIRTUAL-FUNCTIONS
Definition
• Virtual-functions are functions in a base-class that can be overridden in derived-
classes.
• They enable dynamic (runtime) polymorphism, where the function called depends
on the type-of-object.

Figure 12.10: Virtual-functions

Features
• Dynamic Polymorphism: Allows base-class pointers to call derived-class methods.
• Function Overriding: Lets derived-classes provide their own version of a base-
class method.
• Base-class Pointer: A base-class pointer can be used to call functions in derived
classes.
• Virtual Table (vtable): Stores pointers to virtual-functions, supporting their
dynamic behavior.
yntax
class BaseClass {
public:
virtual void virtualFunction() {
// Base-class implementation
}
};

class DerivedClass : public BaseClass {


public:
void virtualFunction() override {
// Derived-class implementation
}
};

Where,
BaseClass: Contains a virtual-function.
virtual void virtualFunction(): Marks the function as virtual.
DerivedClass: Provides its own implementation of the virtual-function.

INHERITANCE
12-24
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Virtual-functions
#include <iostream>

using namespace std;

// Base class
class Shape {
public:
// Virtual function for drawing the shape
virtual void draw() {
cout << "Drawing a shape." << endl;
}
};

// Derived class for Circle


class Circle : public Shape {
public:
// Override draw to provide a specific implementation for Circle
void draw() override {
cout << "Drawing a Circle." << endl;
}
};

// Derived class for Rectangle


class Rectangle : public Shape {
public:
// Override draw to provide a specific implementation for Rectangle
void draw() override {
cout << "Drawing a Rectangle." << endl;
}
};

int main() {
// Create objects of derived classes
Circle myCircle;
Rectangle myRectangle;

// Demonstrating polymorphism
Shape* shapePtr;

shapePtr = &myCircle;
shapePtr->draw(); // Outputs: Drawing a Circle.

shapePtr = &myRectangle;
shapePtr->draw(); // Outputs: Drawing a Rectangle.

return 0;
}
Output:
Drawing a Circle.
Drawing a Rectangle

INHERITANCE
12-25
PROBLEM SOLVING AND PROGRAMMING USING C++
Explanation:
- Shape Class: This is the base class with a virtual function `draw()`. The base class
provides a general implementation for drawing a shape.
- Circle Class: This class inherits from `Shape` and overrides the `draw()` function
to provide a specific implementation for drawing a circle.
- Rectangle Class: This class also inherits from `Shape` and overrides the `draw()`
function to provide a specific implementation for drawing a rectangle.
- Main Function: In the `main()` function, objects of `Circle` and `Rectangle` are
created, and their `draw()` methods are called. Additionally, polymorphism is
demonstrated by using a `Shape` pointer to call the `draw()` function on `Circle`
and `Rectangle` objects.

Aspect Single- Multi-Level Multiple- Hierarchical- Hybrid- Multi-Path


Inheritance Inheritance Inheritance Inheritance Inheritance Inheritance
Definition A class A class inherits A class inherits Multiple- Combines A class inherits
inherits from from another from more classes inherit Multiple- from multiple
only one base- derived-class, than one base- from a single Inheritance base-classes,
class. forming a chain. class. base-class. types, such as which inherit
hierarchical and from a common
Multiple- base-class.
Inheritance.
Hierarchy Simple Chain-like Complex Tree-like Complex Complex
Structure hierarchy with hierarchy with hierarchy with structure with a structure with structure with
one parent. multiple levels. multiple common parent mixed types of Multiple-
parents. base-class. inheritance. Inheritance
paths.
Class Direct A chain of Direct Multiple Combination of Multiple-
Relation relationship derived-classes, relationship derived-classes Multiple- Inheritance paths
ships between the each inheriting with multiple branching from Inheritance due to shared
base-class and from its base-classes. one base-class. paths, base-classes,
the derived- predecessor. potentially with potentially
class. both leading to the
hierarchical and diamond
multiple. problem.
Complexity Low Moderate High Moderate High High
complexity; complexity; complexity; complexity; complexity; complexity;
straightforwar multiple levels multiple base- common base- combines potential for the
d inheritance but classes can class shared different diamond
model. straightforward. lead to among derived- inheritance problem and
ambiguity. classes. models. requires careful
management.
Potential Minimal Fewer issues; Ambiguity and Typically Ambiguity and Diamond
Issues issues; easy to clear hierarchy complexity straightforward; complexity due problem;
implement and with less due to multiple issues arise if to mixed requires virtual
manage. ambiguity. base-classes. base-class is inheritance inheritance to
complex. types. manage

INHERITANCE
12-26
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 13: I/O STREAMS

13.1 INTRODUCTION TO I/O STREAMS


13.2 UNFORMATTED-I/O
13.3 FORMATTED-I/O
13.4 BUILT IN CLASSES FOR I/O
13.5 ios CLASS FUNCTIONS AND FLAGS
13.6 UNFORMATTED-I/O VS FORMATTED-I/O

I/O STREAMS
13-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 13: I/O STREAMS

13.1 INTRODUCTION TO I/O STREAMS


Stream Concept
• C++ I/O operations use the stream concept.
• The stream refers to a series of bytes or data flow.
• Streams improve performance by managing the flow of data between the main-
memory and devices like printers, screens, and network connections.
Output Operation
• Bytes are transferred from the main-memory to an output device (e.g., printer,
screen) during an output operation.
Input Operation
• Bytes flow from an input device (e.g., keyboard) to the main-memory during an
input operation.
Header Files for I/O
• C++ provides predefined functions and declarations through header files to handle
I/O tasks efficiently.
`<iostream>` Header File
• Essential for input/output operations in C++.
• Includes classes like `istream` (input stream) and `ostream` (output stream).
• Commonly used classes:
`cin`: Standard input stream.
`cout`: Standard output stream
Standard Output Stream (`cout`)
• An object of the `ostream` class, connected to the standard output device (typically
a display screen).
• Used with the insertion operator (`<<`), to display output on the console.
Standard Input Stream (`cin`)
• An object of the `istream` class, connected to the standard input device (typically a
keyboard).
• Used with the extraction operator (`>>`), to read input from the console.
Example
#include <iostream>
using namespace std;

int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
return 0;
}
Output:
Enter your age: 22
Your age is: 22

I/O STREAMS
13-2
PROBLEM SOLVING AND PROGRAMMING USING C++
13.2 UNFORMATTED-I/O
• Definition: Input- and output-operations where data is read or written without
applying any specific formatting-rules.
The data is transferred in its raw, unmodified form.
Purpose
• To perform simple, direct input- and output-operations without any concern for how
the data is presented or formatted.
• Useful for efficient, low-level data handling where formatting is not necessary.
Usage
• Often used when handling binary-data or performing low-level file operations.
• Provides more control over how data is managed and transferred, without altering
its format.
• Common unformatted-I/O functions are listed in below table:

getline(istream &input, string &str, char delim = '\n');


• Description: This function reads a line-of-text from the input-stream and stores it
in a string.
It reads until it encounters a newline-character (`'\n'`) or the end of the file,
and then discards the newline-character.
• Parameters:
`istream &input`: The input-stream from which the line is read (e.g., `cin`).
`string &str`: A reference to a `string` variable where the line-of-text will be
stored.
`char delim` (optional): A delimiter-character that specifies where the input
should stop. By default, it is `'\n'`.

I/O STREAMS
13-3
PROBLEM SOLVING AND PROGRAMMING USING C++
• Example Usage: Demonstrating getline()
#include <iostream>
#include <string>
using namespace std;

int main() {
string line;
cout << "Enter a line-of-text: ";
getline(cin, line); // Reads a line-of-text from the user
cout << "You entered: " << line << endl; // Outputs the entered line
return 0;
}
Output:
Enter a line-of-text: Hello World
You entered: Hello World

get(char &ch)
• Description: This function reads a single character from the input-stream and
stores it in the variable `ch`.
• Parameters:
`char &ch`: A reference to a `char` variable where read character will be stored
put(char ch)
• Description: This function writes a single character to the output stream.
• Parameters:
`char ch`: The character to be written to the output stream.
• Example Usage: Demonstrating get() and put()
#include <iostream>
using namespace std;

int main() {
char c;
cout << "Enter a single character: ";
cin.get(c); // Reads a single character from the input
cout << "You entered: ";
cout.put(c); // Writes the character to the output
cout << endl;
return 0;
}
Output:
Enter a single character: A
You entered: A

I/O STREAMS
13-4
PROBLEM SOLVING AND PROGRAMMING USING C++
read(char *buffer, streamsize count);`
• Description: This function reads a block of characters from the input-stream and
stores them in the array pointed to by `buffer`.
• Parameters:
`char *buffer`: A pointer to a character-array where the read characters will
be stored.
`streamsize count`: The maximum number of characters to read.
write(const char *buffer, streamsize count)
• Description: This function writes a block of characters from the array pointed to by
`buffer` to the output stream.
• Parameters:
`const char *buffer`: A pointer to a character-array containing the data to be
written.
`streamsize count`: The number of characters to write.
• Example Usage: Demonstrating read() and write()
#include <iostream>
using namespace std;

int main() {
char data[20];
cout << "Enter up to 20 characters: ";
cin.read(data, 20); // Reads up to 20 characters into the 'data' array

cout << "The data you entered: ";


cout.write(data, 20); // Writes 20 characters from 'data' to the output
cout << endl;

return 0;
}
Output:
Enter up to 20 characters: gcwmaddur
The data you entered: gcwmaddur

I/O STREAMS
13-5
PROBLEM SOLVING AND PROGRAMMING USING C++
13.3 FORMATTED-I/O
• Definition: Input- and output-operations where data is formatted according to
specific rules or styles before being written to or read from a stream.
Purpose
• To present data in a readable and structured format.
• To ensure data is aligned, padded, or displayed in a particular way according to user
requirements.
Usage
• Formatted-I/O functions are used with output streams (cout) to control how data is
formatted when displayed.
• They can be applied to both numbers and text to ensure consistent and readable
output.
• Common formatted-I/O functions are listed in below table:

setprecision(int n)
• Description: This function sets the number of digits to display after the decimal
point for floating-point numbers in the output stream.
• Parameters:
`int n`: The number of digits to display
• Example Usage:
cout << setprecision(3) << 3.14159; // Outputs: 3.14

setw(int width)
• Description: This function sets the width of the next input/output field. If the data
is shorter than the specified width, it will be padded with spaces or another character
(set by `setfill()`).
• Parameters:
- `int width`: The width of the field for the next input/output operation.
• Example Usage:
cout << setw(10) << 123; // Outputs: " 123" (7 spaces before 123)

setfill(char c)
• Description: This function sets the fill character used to pad fields in the output
stream. It is used in conjunction with `setw()` to pad the output with a specific
character instead of spaces.
• Parameters:
`char c`: The character used to pad the output field.
• Example Usage:
cout << setfill('*') << setw(10) << 1234; // Outputs:"1234" (padded with *)

I/O STREAMS
13-6
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating Formatted-I/O
#include <iostream>
#include <iomanip> // For setprecision, setw, and setfill

using namespace std;

int main() {
// Setting precision to 3 digits after the decimal point
cout << setprecision(3) << 3.14159 << endl; // Outputs: 3.14

// Setting width to 10 and displaying the number 123


cout << setw(10) << 123 << endl; // O/Ps: " 123" (7 spaces before 123)

// Setting fill character to '*' and width to 10, then displaying the number 1234
cout << setfill('*') << setw(10) << 1234 << endl; // Outputs: "******1234"

return 0;
}
Output:
3.14
123
******1234
Explanation:
- Precision Example: `setprecision(3)` formats the floating-point number
`3.14159` to show only 3 digits after the decimal point, resulting in `3.14`.
- Width Example: `setw(10)` sets the width of the field to 10 characters. Since the
integer `123` only takes up 3 characters, 7 spaces are added before it.
- Padding with Fill Character Example: setfill('*') << setw(10) << 1234 sets the
width of the output field to 10 characters and uses the asterisk (*) as the padding
character.

I/O STREAMS
13-7
PROBLEM SOLVING AND PROGRAMMING USING C++
13.4 BUILT-IN CLASSES FOR I/O
Definition
• Built-in Classes for I/O handle input and output-operations.
• These classes simplify file and console I/O.
Features
• Stream-Based I/O: I/O-classes use streams to manage data flow.
This provides a consistent way to handle data from different sources like the
console or files.
• Overloaded Operators: I/O-classes support overloaded operators.
The `<<` operator is used for output, and the `>>` operator is used for input.
This makes it easy to format and handle data.
• Common built-in classes are listed in below table:
1) `iostream`
2) `istream`
3) `ostream`
1) `iostream`
• Description: The Base-class for input and output-stream classes.
• It provides functionalities for both input and output-operations.
• Derived-classes:
`istream`: For input-operations.
`ostream`: For output-operations.
2) `istream`
• Description: A class for input-stream operations.
• It is used for reading data from input-sources like the keyboard or files.
• Common Functions:
`>>` (extraction-operator) for reading formatted data.
`getline()` for reading lines of text.
`eof()` to check if the end of the input-stream is reached.
3) `ostream`
• Description: A class for output-stream operations.
• It is used for writing data to output-destinations like the console or files.
• Common Functions:
`<<` (insertion-operator) for writing formatted data.
`flush()` to flush the output buffer.
`endl` for inserting a newline and flushing the stream.
Example Program: Demonstrating istream and ostream
#include <iostream>
int main() {
int number;
cout << "Enter an integer: "; // Using ostream to print to console
cin >> number; // Using istream to read from keyboard
cout << "You entered: " << number << endl;
return 0;
}
Output:
Enter an integer: 42
You entered: 42

I/O STREAMS
13-8
PROBLEM SOLVING AND PROGRAMMING USING C++
13.5 `ios` CLASS FUNCTIONS AND FLAGS
• Definition: The `ios` class is a Base-class for streams like `istream`, `ostream`,
and `fstream`.
• It provides functions and flags to manage stream operations.

Table: ios Class Functions

Table: ios Class Flags

I/O STREAMS
13-9
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating ios` Class Functions and Flags
#include <iostream>
#include <iomanip> // For formatting functions like setw, setprecision, etc.

int main() {
// Example of ios class functions and flags

// Stream state checking


cout << "Stream state checks:" << endl;
if (cout.good()) {
cout << "Stream is good." << endl;
}
if (cout.fail()) {
cout << "Stream has failed." << endl;
}
if (cout.eof()) {
cout << "End of file has been reached." << endl;
}

// Using flags
cout << "Hexadecimal and octal outputs:" << endl;

// Use hexadecimal formatting


cout << hex << "Hex: " << 255 << endl;

// Use additional flags


cout << "Additional flags:" << endl;

// Show base prefix


cout << showbase;
cout << "Hex with base: " << hex << 255 << endl;

// Show positive sign


cout << showpos;
cout << "Positive sign: " << 123 << endl;

return 0;
}
Output:
Stream state checks:
Stream is good.
Hexadecimal and octal outputs:
Hex: ff
Additional flags:
Hex with base: 0xff
Positive sign: +123

I/O STREAMS
13-10
PROBLEM SOLVING AND PROGRAMMING USING C++
Explanation:
1) Stream State Checking:
• Checks the state of the stream with `good()`, `fail()`, and `eof()` methods.
2) Using Flags:
• `hex` formats numbers in hexadecimal.
• `oct` formats numbers in octal.
• `dec` resets the formatting to decimal.
• `showbase` displays the base prefix for hexadecimal (0x) and octal (0).
• `showpos` displays the positive sign for numbers.
3) Skipping Whitespace:
• Demonstrates `skipws`, though it's more relevant for input-streams. In the given
output, it shows how spaces are managed (not impactful in this specific context).

13.6 UNFORMATTED-I/O VS. FORMATTED-I/O

I/O STREAMS
13-11
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 14: FILE-HANDLING

14.1 INTRODUCTION TO FILE-HANDLING


14.2 FILE STREAM-CLASSES
14.2.1 ifstream
14.2.2 ofstream
14.2.3 fstream
14.3 STANDARD CLASS-FUNCTIONS FOR FILE I/O
14.4.1 FILE OPENING-MODES
14.4 TYPES OF FILES
14.4.1 TEXT-FILES
14.4.2 BINARY-FILES
14.4.3 TEXT-FILES VS. BINARY-FILES

FILE HANDLING
14-1
PROBLEM SOLVING AND PROGRAMMING USING C++

CHAPTER 14: FILE-HANDLING

14.1 INTRODUCTION TO FILE-HANDLING


• Definition: Files are named-locations on a storage-medium where data can be
stored & retrieved by programs.
• Typically, the storage-medium is a disk.

FILE-HANDLING
• Definition: File-handling refers to the management and manipulation of files stored
on a storage-device.
Purpose
• Data Storage: Enables programs to store large amounts of data permanently.
• Data Retrieval: Facilitates retrieving stored-data for processing or display.
• Data Manipulation: Supports operations such as updating existing data,
appending new data, and deleting data.
• File Management: Includes file-operations such as opening, reading, writing, and
closing files.

FILE HANDLING
14-2
PROBLEM SOLVING AND PROGRAMMING USING C++
14.2 FILE STREAM-CLASS
• Definition: File-stream-classes are specialized classes used for performing input
and output operations on files.
• File-stream-classes include
ifstream (Input File Stream)
ofstream (Output File Stream)
fstream (File Stream)

14.2.1 ifstream
• Purpose: Used to read data from files.
• Functionality: It allows opening a file and reading its contents, operating in input
mode by default.
• Example Usage:
ifstream inFile("example.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();

14.2.2 ofstream
• Purpose: Used to write data to files.
• Functionality: It allows creating a file or opening an existing file to write data to it,
operating in output mode by default.
• Example Usage:
ofstream outFile("example.txt");
outFile << "Hello, World!" << endl;
outFile.close();

14.2.3 fstream
• Purpose: Combines both input and output file-operations.
• Functionality: It allows both reading from and writing to files and can be used in
input, output, or both modes.
• Example Usage:
fstream file("example.txt", ios::in | ios::out);
string line;
while (getline(file, line)) {
cout << line << endl;
}
file << "New line added." << endl;
file.close();

FILE HANDLING
14-3
PROBLEM SOLVING AND PROGRAMMING USING C++
Example Program: Demonstrating ifstream and ofstream
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
// Step 1: Write to the file using ofstream
ofstream outFile("example.txt");
outFile << "Hello, World!" << endl;
outFile.close();
cout << "Data written to file successfully." << endl;

// Step 2: Read from the file using ifstream


ifstream inFile("example.txt");
string line;
while (getline(inFile, line)) {
cout << "Read from file: " << line << endl;
}
inFile.close();

return 0;
}
Output:
Data written to file successfully.
Read from file: Hello, World!

FILE HANDLING
14-4
PROBLEM SOLVING AND PROGRAMMING USING C++
COMPARISON OF ifstream, ofstream AND fstream

FILE HANDLING
14-5
PROBLEM SOLVING AND PROGRAMMING USING C++
14.3 STANDARD CLASS-FUNCTIONS FOR FILE I/O
Definition
• These are functions provided by the file stream-classes to handle file-operations.
• The file stream-classes include `ifstream`, `ofstream`, `fstream`
Purpose
• To manage file input and output with built-in classes that handle file stream
operations.
• To enable the reading from and writing to files in a structured and efficient manner.
• Common Standard Class-functions for File I/O are listed in below table:

`open(const char* filename, ios_base::openmode mode)`


• Description: This function opens a file for reading, writing, or both.
• Parameters:
`const char* filename`: The name of the file to be opened.
`ios_base::openmode mode`: The mode in which the file should be opened
e.g., `ios::in`, `ios::out`, `ios::app`, `ios::binary`
• Example Usage:
ofstream outFile;
outFile.open("example.txt", ios::out); // Opens the file "example.txt" for writing

`close()`
• Description: This function closes the file that was opened.
Closing a file ensures that all data is properly saved and frees system-resources.
• Parameters: None.
• Example Usage:
outFile.close(); // Closes the file after writing

`read(char* buffer, streamsize size)`


• Description: This function reads a block-of-data from the file into a buffer.
This function is typically used for reading binary-data.
• Parameters:
`char* buffer`: The memory-location where the read data will be stored.
`streamsize size`: The number of bytes to read from the file.
• Example Usage:
ifstream inFile("data.bin", ios::binary);
inFile.read(data, sizeof(data)); // Reads 'sizeof(data)' bytes from the file into 'data'

FILE HANDLING
14-6
PROBLEM SOLVING AND PROGRAMMING USING C++
`write(const char* buffer, streamsize size)`
• Description: This function writes a block-of-data from a buffer to a file.
This function is typically used for writing binary-data.
• Parameters:
`const char* buffer`: The memory-location containing the data to be written.
`streamsize size`: The no. of bytes to write to the file.
• Example Usage:
outFile.write(reinterpret_cast<const char*>(&number), sizeof(number));
// Writes 'sizeof(number)' bytes from 'number' to the file

Example Program: Demonstrating open(), close(), read() and write()


#include <iostream>
#include <fstream> // Include the fstream library for file I/O

using namespace std;

int main() {
// Part 1: Writing to a text file
ofstream outFile; // Create an ofstream object for writing to a file
outFile.open("example.txt", ios::out); // Opens the file "example.txt" for writing

if (outFile.is_open()) {
outFile << "Hello, this is a sample text file." << endl; // Write some text to the file
outFile.close(); // Closes the file after writing
cout << "Text file written successfully." << endl;
} else {
cout << "Failed to open the file for writing." << endl;
}

// Part 2: Reading from a binary file


ifstream inFile("data.bin",ios::binary);// Create ifstream object for reading from binary file
char data[100]; // Buffer to store the read data

if (inFile.is_open()) {
inFile.read(data, sizeof(data)); // Reads 'sizeof(data)' bytes from the file into 'data'
inFile.close(); // Closes the file after reading
cout << "Binary file read successfully." << endl;
} else {
cout << "Failed to open the binary file for reading." << endl;
}

// Part 3: Writing a number to a binary file


int number = 12345; // Example number to write to the file

outFile.open("data.bin", ios::binary | ios::out); // Opens file "data.bin" for binary writing

if (outFile.is_open()) {
outFile.write(reinterpret_cast<const char*>(&number), sizeof(number));
// Writes 'sizeof(number)' bytes from 'number' to the file
outFile.close(); // Closes the file after writing
cout << "Number written to binary file successfully." << endl;

FILE HANDLING
14-7
PROBLEM SOLVING AND PROGRAMMING USING C++
} else {
cout << "Failed to open the binary file for writing." << endl;
}
return 0;
}
Output:
Text file written successfully.
Binary file read successfully.
Number written to binary file successfully.

FILE HANDLING
14-8
PROBLEM SOLVING AND PROGRAMMING USING C++
14.3.1 FILE OPENING-MODES
• File opening-modes determine how a file is accessed and modified during file-
operations.
• They are specified when opening a file using file stream-classes (`ifstream`,
`ofstream`, `fstream`).
• Common file opening-modes are listed in below table:

FILE HANDLING
14-9
PROBLEM SOLVING AND PROGRAMMING USING C++
14.4 TYPES OF FILES
14.4.1 TEXT-FILES
• Definition: Text-files store data as readable-characters and -strings.
• Features
- Data is in plain-text, with lines separated by newline-characters.
- Can be edited with any text-editor.
- Used for configuration-files, logs, and simple data-storage.
• Example Usage:
#include <fstream>
using namespace std;
int main() {
ifstream inFile("example.txt");
// Read from file
inFile.close();
}

14.4.2 BINARY-FILES
• Definition: Binary-files store data in a non-readable format, using bytes.
• Features
- Data is stored in binary-form, specific to the data-type.
- Cannot be easily edited with text-editors.
- Useful for storing images, executables, and complex data.
• Example Usage:
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.bin", ios::binary);
// Write to file
outFile.close();
}

FILE HANDLING
14-10
PROBLEM SOLVING AND PROGRAMMING USING C++
14.4.3 TEXT-FILES VS. BINARY-FILES

FILE HANDLING
14-11
PROBLEM SOLVING AND PROGRAMMING USING C++

BASIC C++ PROGRAMS

Program to Print a Sentence


#include <iostream.h>

int main() {
cout << "C++ Programming" << endl; // Displays the content inside quotation
return 0;
}
OUTPUT:
C++ Programming

Program to Read and Display an Integer


#include <iostream.h>

int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Storing an integer entered by user in variable num
cout << "You entered: " << num << endl;
return 0;
}
OUTPUT:
Enter an integer: 25
You entered: 25

Program to Add Two Integers


#include <iostream.h>

int main() {
int num1, num2, sum;
cout << "Enter two integers: ";
cin >> num1 >> num2;
sum = num1 + num2; // Performs addition and stores it in variable sum
cout << "Sum: " << sum << endl; // Displays sum
return 0;
}
OUTPUT:
Enter two integers: 12 11
Sum: 23

P-1
PROBLEM SOLVING AND PROGRAMMING USING C++
Program To Find Average Of Two Integers
#include <iostream.h>

int main() {
int num1, num2;
float average;

// Input two integers


cout << "Enter the first integer: ";
cin >> num1;
cout << "Enter the second integer: ";
cin >> num2;

// Calculate the average


average = (num1 + num2) / 2.0;

// Display the average


cout << " average =" << average << endl;

return 0;
}
OUTPUT:
Enter the first integer: 10
Enter the second integer: 20
average = 15.0

Program to Multiply Two Floating Point Numbers


#include <iostream.h>

int main() {
float num1, num2, product;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
product = num1 * num2; // Performs multiplication and stores it
cout << "Product: " << product << endl;
return 0;
}
OUTPUT:
Enter two numbers: 2 3
Product: 6

P-2
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find Quotient and Remainder of Two Integers
#include <iostream.h>

int main() {
int dividend, divisor, quotient, remainder;
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
quotient = dividend / divisor; // Computes quotient
remainder = dividend % divisor; // Computes remainder
cout << "Quotient = " << quotient << endl;
cout << "Remainder = " << remainder << endl;
return 0;
}
OUTPUT:
Enter dividend: 7
Enter divisor: 2
Quotient = 3
Remainder = 1

Program to Find the Area and perimeter of a Rectangle


#include <iostream.h>

int main() {
int length, breadth, area, perimeter;

cout << "Enter length and breadth: ";


cin >> length >> breadth;

area = length * breadth;


perimeter = 2 * (length + breadth);

cout << "Area of rectangle = " << area << endl;


cout << "Perimeter of rectangle = " << perimeter << endl;

return 0;
}
OUTPUT:
Enter length and breadth: 3 4
Area of rectangle = 12
Perimeter of rectangle = 14

P-3
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find the Area of a Circle
#include <iostream.h>

int main() {
float r, area;
cout << "Enter radius: ";
cin >> r;
area = 3.14 * r * r;
cout << "Area of circle = " << area << endl;
return 0;
}
OUTPUT:
Enter radius: 4
Area of circle = 50.24

Program to Find the Area of a Triangle


#include <iostream.h>

int main() {
float base, height, area;

// Prompt the user for input


cout << "Enter the base of the triangle: ";
cin >> base;

cout << "Enter the height of the triangle: ";


cin >> height;

// Calculate the area of the triangle


area = 0.5 * base * height;

// Display the result


cout << "The area of the triangle is: " << area << endl;

return 0;
}
OUTPUT:
Enter the base of the triangle: 10
Enter the height of the triangle: 5
The area of the triangle is: 25

P-4
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Calculate the Volume of a Cube
#include <iostream.h>

int main() {
float side, volume;

// Prompt the user for input


cout << "Enter the side length of the cube: ";
cin >> side;

// Calculate the volume of the cube


volume = side * side * side;

// Display the result


cout << "The volume of the cube is: " << volume << endl;

return 0;
}
OUTPUT:
Enter the side length of the cube: 4
The volume of the cube is: 64

Program to Find Simple Interest


#include <iostream.h>

int main() {
float amount, rate, time, si;
cout << "Enter Principal Amount: ";
cin >> amount;
cout << "Enter Rate of Interest: ";
cin >> rate;
cout << "Enter Period of Time: ";
cin >> time;
si = (amount * rate * time) / 100;
cout << "Simple Interest: " << si << endl;
return 0;
}
OUTPUT:
Enter Principal Amount: 500
Enter Rate of Interest: 5
Enter Period of Time: 2
Simple Interest: 50

P-5
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Calculate Compound Interest
#include <iostream.h>
#include <math.h> // Use <math.h> instead of <cmath> in Turbo C++ 3

int main() {
float principal, rate, time, amount, compoundInterest;

// Prompt the user for input


cout << "Enter principal amount: ";
cin >> principal;
cout << "Enter annual interest rate (in percentage): ";
cin >> rate;
cout << "Enter time (in years): ";
cin >> time;

// Calculate compound interest


amount = principal * pow((1 + rate / 100), time);
compoundInterest = amount - principal;

cout << "Compound Interest: " << compoundInterest << endl;

return 0;
}
OUTPUT:
Enter principal amount: 1000
Enter annual interest rate (in percentage): 5
Enter time (in years): 2
Compound Interest: 102.50

Program to Find Square of a Number


#include <iostream.h>

int main() {
int n, p;
cout << "Enter a number: ";
cin >> n;
p = n * n;
cout << "The square of the number is " << p << endl;
return 0;
}
OUTPUT:
Enter a number: 4
The square of the number is 16

P-6
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Convert Kilometers to Miles
#include <iostream.h>

int main() {
// Define the conversion factor from kilometers to miles
const float CONVERSION_FACTOR = 0.621371;

// Variables to hold the input and result


float kilometers, miles;

// Input: Get kilometers from the user


cout << "Enter distance in kilometers: ";
cin >> kilometers;

// Calculation: Convert kilometers to miles


miles = kilometers * CONVERSION_FACTOR;

// Output: Display the result


cout << kilometers << " kilometers is equal to " << miles << " miles.";

return 0;
}
OUTPUT:
Enter distance in kilometers: 10
10 kilometers is equal to 6.21371 miles.

Program to Convert Celsius to Fahrenheit


#include <iostream.h>

int main() {
float celsius, fahrenheit;

// Prompt the user for input


cout << "Enter temperature in Celsius: ";
cin >> celsius;

// Convert Celsius to Fahrenheit


fahrenheit = (celsius * 9/5) + 32;

cout << "Temperature in Fahrenheit: " << fahrenheit << endl;

return 0;
}
OUTPUT:
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77

P-7
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Swap Two Numbers
#include <iostream.h>

int main() {
int a, b, temp;
cout << "Enter value of a: ";
cin >> a;
cout << "Enter value of b: ";
cin >> b;
temp = a; // Value of a is stored in variable temp
a = b; // Value of b is stored in variable a
b = temp; // Value of temp is stored in variable b
cout << "After swapping, value of a = " << a << endl;
cout << "After swapping, value of b = " << b << endl;
return 0;
}
OUTPUT:
Enter value of a: 3
Enter value of b: 4
After swapping, value of a = 4
After swapping, value of b = 3

Program to illustrate Sizeof Basic Data Types


#include <iostream>
using namespace std;

int main() {
int integerVar;
float floatVar;
double doubleVar;
char charVar;

cout << "Size of int: " << sizeof(integerVar) << " bytes" << endl;
cout << "Size of float: " << sizeof(floatVar) << " bytes" << endl;
cout << "Size of double: " << sizeof(doubleVar) << " bytes" << endl;
cout << "Size of char: " << sizeof(charVar) << " bytes" << endl;

return 0;
}
OUTPUT:
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte

P-8
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Post-Increment and Pre-Increment
#include <iostream>
using namespace std;

int main() {
int a = 5;
int b;

// Post-increment
b = a++; // Assigns value of a to b, then increments a
cout << "After post-increment: " << endl;
cout << "a = " << a << endl; // a is now 6
cout << "b = " << b << endl; // b is 5

a = 5; // Reset a
// Pre-increment
b = ++a; // Increments a, then assigns value to b
cout << "After pre-increment: " << endl;
cout << "a = " << a << endl; // a is 6
cout << "b = " << b << endl; // b is 6

return 0;
}
OUTPUT:
After post-increment:
a = 6
b = 5
After pre-increment:
a = 6
b = 6

P-9
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Post-Decrement and Pre-Decrement
#include <iostream.h>
using namespace std;

int main() {
int x = 10;
int y;

// Post-decrement
y = x--; // Assigns value of x to y, then decrements x
cout << "After post-decrement: " << endl;
cout << "x = " << x << endl; // x is now 9
cout << "y = " << y << endl; // y is 10

x = 10; // Reset x
// Pre-decrement
y = --x; // Decrements x, then assigns value to y
cout << "After pre-decrement: " << endl;
cout << "x = " << x << endl; // x is 9
cout << "y = " << y << endl; // y is 9

return 0;
}
OUTPUT:
After post-decrement:
x = 9
y = 10
After pre-decrement:
x = 9
y = 9

P-10
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Operator Precedence
#include <iostream.h>
using namespace std;

int main() {
int a = 10;
int b = 5;
int c = 2;

// Operator Precedence: Multiplication and Division before Addition and


Subtraction
int result1 = a + b * c;
int result2 = (a + b) * c;

cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "a + b * c = " << result1 << endl;
cout << "(a + b) * c = " << result2 << endl;

return 0;
}
OUTPUT:
a = 10, b = 5, c = 2
a + b * c = 20
(a + b) * c = 30

Program to illustrate Associativity of Addition and Subtraction


#include <iostream.h>
using namespace std;

int main() {
int a = 10;
int b = 5;
int c = 2;

// Associativity: Left-to-Right for Addition and Subtraction


int result1 = a - b - c;
int result2 = (a - b) - c;

cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "a - b - c = " << result1 << endl;
cout << "(a - b) - c = " << result2 << endl;

return 0;
}
OUTPUT:
a = 10, b = 5, c = 2
a - b - c = 3
(a - b) - c = 3

P-11
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Implicit Type Conversion (Automatic Conversion)
#include <iostream.h>
using namespace std;

int main() {
int intValue = 10;
double doubleValue = 5.5;

// Implicit conversion: int to double


double result = intValue + doubleValue;

cout << "intValue = " << intValue << endl;


cout << "doubleValue = " << doubleValue << endl;
cout << "Result (int + double): " << result << endl;

return 0;
}
OUTPUT:
intValue = 10
doubleValue = 5.5
Result (int + double): 15.5

Program to illustrate Explicit Type Conversion (Type Casting)


#include <iostream.h>
using namespace std;

int main() {
double doubleValue = 9.8;
int intValue;

// Explicit conversion: double to int


intValue = static_cast<int>(doubleValue);

cout << "doubleValue = " << doubleValue << endl;


cout << "intValue (after casting) = " << intValue << endl;

return 0;
}
OUTPUT:
doubleValue = 9.8
intValue (after casting) = 9

P-12
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate static_cast for Basic Type Conversion
#include <iostream.h>
using namespace std;

int main() {
double doubleValue = 10.75;
// Static cast to convert double to int
int intValue = static_cast<int>(doubleValue);

cout << "Original double value: " << doubleValue << endl;
cout << "After static_cast to int: " << intValue << endl;

return 0;
}
OUTPUT:
Original double value: 10.75
After static_cast to int: 10

P-13
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS BASED ON BRANCHING


Program to Find the Largest Number of Two Numbers Using Basic `if` Statement
#include <iostream.h>

int main() {
float a, b;
// Prompt the user for input
cout << "Enter 2 different numbers: \n";
cin >> a >> b;
// Determine the largest number
if (a > b) {
cout << "Largest number = " << a << endl;
}
if (b > a) {
cout << "Largest number = " << b << endl;
}
return 0;
}
OUTPUT:
Enter 2 different numbers:
13.452 10.193
Largest number = 13.452

Program to Check for Positive or Negative using Basic `if` Statement


#include <iostream>

int main() {
int number;
cout << "Enter a non-zero integer: ";
cin >> number;

if (number > 0) {
cout << number << " is positive." << endl;
}

if (number < 0) {
cout << number << " is negative." << endl;
}
return 0;
}
OUTPUT:
Enter an non-zero integer: -5
-5 is negative.

P-14
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find the Largest Number Among Three Numbers Using If Statement
#include <iostream.h>
int main() {
float a, b, c;
// Prompt the user for input
cout << "Enter three different numbers: ";
cin >> a >> b >> c;
// Determine the largest number
if (a >= b && a >= c) {
cout << "Largest number = " << a << endl;
}
if (b >= a && b >= c) {
cout << "Largest number = " << b << endl;
}
if (c >= a && c >= b) {
cout << "Largest number = " << c << endl;
}
return 0;
}
OUTPUT:
Enter three different numbers: 11 12 13
Largest number = 13

Program to Check Whether a Number is Even or Odd Using if else Statement


#include <iostream.h>

int main() {
int num;

// Prompt the user for input


cout << "Enter an integer you want to check: ";
cin >> num;

// Check if the number is even or odd


if ((num % 2) == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}

return 0;
}
OUTPUT:
Enter an integer you want to check: 25
25 is odd.

P-15
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Check Whether a Character is an Alphabet or Not Using if else
Statement
#include <iostream.h>

int main() {
char c;

// Prompt the user for input


cout << "Enter a character: ";
cin >> c;

// Check if the character is an alphabet


if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
cout << c << " is an alphabet." << endl;
} else {
cout << c << " is not an alphabet." << endl;
}

return 0;
}
OUTPUT:
Enter a character: 2
2 is not an alphabet.

Program to Check Whether a Character is a Digit or Not Using if else Statement


#include <iostream.h>

int main() {
char ch;

cout << "Enter a character: ";


cin >> ch;

if (ch >= '0' && ch <= '9') {


cout << ch << " is a digit." << endl;
} else {
cout << ch << " is not a digit." << endl;
}

return 0;
}
OUTPUT:
Enter a character: 3
3 is a digit.

P-16
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Check Voting Eligibility Using if else Statement
#include <iostream.h>

int main() {
int age;

cout << "Enter your age: ";


cin >> age;

if (age >= 18) {


cout << "You are eligible to vote." << endl;
} else {
cout << "You are not eligible to vote." << endl;
}

return 0;
}
OUTPUT:
Enter your age: 23
You are eligible to vote.

P-17
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement Age Classification using if-else ladder Statement
#include <iostream.h>

int main() {
int age;
cout << "Enter your age: ";
cin >> age;

if (age >= 65) {


cout << "Senior Citizen" << endl;
} else if (age >= 18) {
cout << "Adult" << endl;
} else if (age >= 13) {
cout << "Teenager" << endl;
} else {
cout << "Child" << endl;
}

return 0;
}
OUTPUT:
Enter your age: 23
Adult

Program to Determine the Type of Triangle Based on Side Lengths Using If Else
ladder Statement
#include <iostream.h>

int main() {
float a, b, c;
cout << "Enter the lengths of three sides of a triangle: ";
cin >> a >> b >> c;

if (a == b && b == c) {
cout << "The triangle is an equilateral triangle." << endl;
} else if (a == b || b == c || a == c) {
cout << "The triangle is an isosceles triangle." << endl;
} else {
cout << "The triangle is a scalene triangle." << endl;
}

return 0;
}
OUTPUT:
Enter the lengths of three sides of a triangle: 5 5 5
The triangle is an equilateral triangle.

P-18
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to check Bank Account Status using if-else ladder Statement
#include <iostream.h>

int main() {
double balance;
cout << "Enter your bank account balance: ";
cin >> balance;

if (balance > 10000) {


cout << "High Balance" << endl;
} else if (balance > 5000) {
cout << "Moderate Balance" << endl;
} else if (balance > 0) {
cout << "Low Balance" << endl;
} else {
cout << "Overdrawn" << endl;
}

return 0;
}
OUTPUT:
Enter your bank account balance: 4500
Low Balance

Program to find the largest of three numbers using nested if-else statements:
#include <iostream.h>

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

if (a >= b) {
if (a >= c) {
cout << "Largest number = " << a << endl;
} else {
cout << "Largest number = " << c << endl;
}
} else {
if (b >= c) {
cout << "Largest number = " << b << endl;
} else {
cout << "Largest number = " << c << endl;
}
}
return 0;
}
OUTPUT:
Enter three numbers: 5 3 8
Largest number = 8

P-19
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Check Whether a Number is Positive or Negative Using Nested If Else
Statement
#include <iostream.h>

int main() {
int num;

// Prompt the user for input


cout << "Enter a number: ";
cin >> num;

// Check if the number is positive or negative


if (num <= 0) {
if (num == 0) {
cout << "You entered zero." << endl;
} else {
cout << num << " is negative." << endl;
}
} else {
cout << num << " is positive." << endl;
}
return 0;
}
OUTPUT:
Enter a number: -7
-7 is negative.

Program to Find All Roots of a Quadratic Equation Using Else If Ladder


#include <iostream.h>
#include <cmath> // For sqrt() function

int main() {
float a, b, c, determinant, r1, r2, real, imag;

// Prompt the user for input


cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;

// Calculate the determinant


determinant = b * b - 4 * a * c;

// Determine the roots based on the determinant


if (determinant > 0) {
r1 = (-b + sqrt(determinant)) / (2 * a);
r2 = (-b - sqrt(determinant)) / (2 * a);
cout << "Roots are: " << r1 << " and " << r2 << endl;
} else if (determinant == 0) {
r1 = r2 = -b / (2 * a);
cout << "Roots are: " << r1 << " and " << r2 << endl;
} else {
real = -b / (2 * a);
imag = sqrt(-determinant) / (2 * a);
cout << "Roots are: " << real << "+" << imag << "i and " << real << "-" << imag << "i" << endl;
}
return 0;
}
OUTPUT:
Enter coefficients a, b and c: 2.3 4 5.6
Roots are: -0.87+1.30i and -0.87-1.30i

P-20
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to determine Day of the Week using switch Statement
#include <iostream.h>

int main() {
int day;
cout << "Enter a number (1-7) to get the day of the week: ";
cin >> day;

switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid input! Please enter number b/w 1 and 7." << endl;
break;
}
return 0;
}
OUTPUT:
Enter a number (1-7) to get the day of the week: 3
Wednesday

P-21
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement Basic Calculator using switch Statement
#include <iostream.h>

int main() {
char op;
double num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> op;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

switch (op) {
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;
} else {
cout << "Error! Division by zero." << endl;
}
break;
default:
cout << "Error! Operator is not correct." << endl;
break;
}

return 0;
}
OUTPUT:
Enter an operator (+, -, *, /): *
Enter two numbers: 5 4
Result: 20

P-22
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement Simple Traffic Light System using switch Statement
#include <iostream.h>

int main() {
int light;
cout << "Enter traffic light color (1 for Red, 2 for Yellow, 3 for Green):
";
cin >> light;

switch (light) {
case 1:
cout << "Stop" << endl;
break;
case 2:
cout << "Get Ready" << endl;
break;
case 3:
cout << "Go" << endl;
break;
default:
cout << "Invalid color! Please enter 1, 2, or 3." << endl;
break;
}

return 0;
}
OUTPUT:
Enter traffic light color (1 for Red, 2 for Yellow, 3 for Green): 2
Get Ready

P-23
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement Menu Selection using switch Statement
#include <iostream.h>

int main() {
int choice;
cout << "Menu:\n";
cout << "1. Pizza\n";
cout << "2. Burger\n";
cout << "3. Pasta\n";
cout << "4. Salad\n";
cout << "Enter your choice (1-4): ";
cin >> choice;

switch (choice) {
case 1:
cout << "You selected Pizza." << endl;
break;
case 2:
cout << "You selected Burger." << endl;
break;
case 3:
cout << "You selected Pasta." << endl;
break;
case 4:
cout << "You selected Salad." << endl;
break;
default:
cout << "Invalid choice! Please enter number b/w 1 and 4." << endl;
break;
}

return 0;
}
OUTPUT:
Menu:
1. Pizza
2. Burger
3. Pasta
4. Salad
Enter your choice (1-4): 3
You selected Pasta.

P-24
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS BASED ON LOOPING


Program to Print First 10 Natural Numbers Using For Loop
#include <iostream.h>

int main() {
for (int num = 1; num <= 10; ++num) {
cout << num << " ";
}
cout << endl;
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10

Program to Print First 10 Natural Numbers Using While Loop


#include <iostream.h>

int main() {
int num = 1;
while (num <= 10) {
cout << num << " ";
++num;
}
cout << endl;
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10

Program to Print First 10 Natural Numbers Using Do-While Loop


#include <iostream.h>

int main() {
int num = 1;
do {
cout << num << " ";
++num;
} while (num <= 10);
cout << endl;
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10

P-25
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Print Sum of First 50 Natural Numbers Using For Loop
#include <iostream.h>

int main() {
int sum = 0;
for (int num = 1; num <= 50; ++num) {
sum += num;
}
cout << "Sum = " << sum << endl;
return 0;
}
OUTPUT:
Sum = 1275

Program to Print Sum of First 50 Natural Numbers Using While Loop


#include <iostream.h>

int main() {
int num = 1, sum = 0;
while (num <= 50) {
sum += num;
++num;
}
cout << "Sum = " << sum << endl;
return 0;
}
OUTPUT:
Sum = 1275

Program to Print Sum of First 50 Natural Numbers Using Do-While Loop


#include <iostream.h>

int main() {
int num = 1, sum = 0;
do {
sum += num;
++num;
} while (num <= 50);
cout << "Sum = " << sum << endl;
return 0;
}
OUTPUT:
Sum = 1275

P-26
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Print Multiples of 3 Less Than 30 using for Statement
#include <iostream.h>

int main() {
for (int num = 3; num < 30; num += 3) {
cout << num << " ";
}
cout << endl;
return 0;
}
OUTPUT:
3 6 9 12 15 18 21 24 27

Program to Print Multiples of 3 Less Than 30 using while Statement


#include <iostream.h>

int main() {
int num = 3;
while (num < 30) {
cout << num << " ";
num += 3;
}
cout << endl;
return 0;
}
OUTPUT:
3 6 9 12 15 18 21 24 27

Program to Print Multiples of 3 Less Than 30 using do-while Statement


#include <iostream.h>

int main() {
int num = 3;
do {
cout << num << " ";
num += 3;
} while (num < 30);
cout << endl;
return 0;
}
OUTPUT:
3 6 9 12 15 18 21 24 27

P-27
PROBLEM SOLVING AND PROGRAMMING USING C++
Program for Counting from 5 to 1 using for Statement
#include <iostream.h>

int main() {
for (int i = 5; i >= 1; i--) {
cout << i << " ";
}
cout << endl;
return 0;
}
OUTPUT:
5 4 3 2 1

Program for Counting from 5 to 1 using while Statement


#include <iostream.h>

int main() {
int i = 5;
while (i >= 1) {
cout << i << " ";
i--;
}
cout << endl;
return 0;
}
OUTPUT:
5 4 3 2 1

Program for Counting from 5 to 1 using do-while Statement


#include <iostream.h>

int main() {
int i = 5;
do {
cout << i << " ";
i--;
} while (i >= 1);
cout << endl;
return 0;
}
OUTPUT:
1 2 3 4 5

P-28
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find HCF and LCM of 2 Numbers using while Statement
#include <iostream.h>
int main() {
int a, b, gcd, lcm, x, y, t;
cout << "Enter two integers: ";
cin >> x >> y;

a = x;
b = y;

while (b != 0) {
t = b;
b = a % b;
a = t;
}

gcd = a;
lcm = (x * y) / gcd;

cout << "GCD of " << x << " and " << y << " = " << gcd << endl;
cout << "LCM of " << x << " and " << y << " = " << lcm << endl;
return 0;
}
OUTPUT:
Enter two integers: 9 24
GCD of 9 and 24 = 3
LCM of 9 and 24 = 72

Program to Count Number of Digits of an Integer using while Statement


#include <iostream.h>
int main() {
int n, count = 0;
cout << "Enter an integer: ";
cin >> n;
// Handle the case where n is 0
if (n == 0) {
count = 1;
} else {
while (n != 0) {
n /= 10;
++count;
}
}
cout << "Number of digits: " << count << endl;
return 0;
}
OUTPUT:
Enter an integer: 34523
Number of digits: 5

P-29
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Reverse a Number using while Statement
#include <iostream.h>

int main() {
int n, reverse = 0, rem;
cout << "Enter an integer: ";
cin >> n;

while (n != 0) {
rem = n % 10;
reverse = reverse * 10 + rem;
n /= 10;
}

cout << "Reversed Number = " << reverse << endl;


return 0;
}
OUTPUT:
Enter an integer: 2345
Reversed Number = 5432

Program to Check Whether a Number is Palindrome or Not using while Statement


#include <iostream.h>

int main() {
int n, reverse = 0, rem, temp;
cout << "Enter an integer: ";
cin >> n;

temp = n;
while (temp != 0) {
rem = temp % 10;
reverse = reverse * 10 + rem;
temp /= 10;
}

if (reverse == n)
cout << n << " is a palindrome." << endl;
else
cout << n << " is not a palindrome." << endl;

return 0;
}
OUTPUT:
Enter an integer: 12321
12321 is a palindrome.

P-30
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to find Factorial of a Number using while Statement
#include <iostream.h>

int main() {
int num, factorial = 1;

cout << "Enter a positive integer: ";


cin >> num;

while (num > 0) {


factorial *= num;
num--;
}

cout << "Factorial is " << factorial << endl;


return 0;
}
OUTPUT:
Enter a positive integer: 5
Factorial is 120

Program to Display Fibonacci Series using for statement


#include <iostream.h>

int main() {
int n, t1 = 0, t2 = 1, display = 0;
cout << "Enter number of terms: ";
cin >> n;

cout << "Fibonacci Series: " << t1 << " " << t2 << " ";
for (int count = 2; count < n; ++count) {
display = t1 + t2;
t1 = t2;
t2 = display;
cout << display << " ";
}
cout << endl;

return 0;
}
OUTPUT:
Enter number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

P-31
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Check Whether a Number is Prime or Not
#include <iostream.h>

int main() {
int n, i;
bool flag = false;
cout << "Enter a positive integer: ";
cin >> n;

if (n <= 1) {
cout << n << " is not a prime number." << endl;
} else {
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag = true;
break;
}
}
if (!flag)
cout << n << " is a prime number." << endl;
else
cout << n << " is not a prime number." << endl;
}
return 0;
}
OUTPUT:
Enter a positive integer: 29
29 is a prime number.

P-32
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Generate First N Prime Numbers
#include <iostream.h>

int main() {
int n, i = 3, count, c;
cout << "Enter the number of prime numbers required: ";
cin >> n;

if (n >= 1) {
cout << "First " << n << " prime numbers are:" << endl;
cout << "2" << endl;
}

for (count = 2; count <= n;) {


bool isPrime = true;
for (c = 2; c <= i / 2; ++c) {
if (i % c == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << i << endl;
++count;
}
++i;
}

return 0;
}
OUTPUT:
Enter the number of prime numbers required: 5
First 5 prime numbers are:
2
3
5
7
11

P-33
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Count Vowels in a String using for statement
#include <iostream.h>
#include <cstring>

int main() {
char str[100];
int vowelCount = 0;

cout << "Enter a string: ";


cin.getline(str, 100);

for (int i = 0; str[i] != '\0'; i++) {


char ch = tolower(str[i]); // Convert character to lowercase
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
cout << "The number of vowels in the string is: " << vowelCount << endl;
return 0;
}
OUTPUT:
Enter a string: Hello World
The number of vowels in the string is: 3

Program to Reverse a String using for statement


#include <iostream.h>
#include <cstring>

int main() {
char str[100], reversedStr[100];
int length;

cout << "Enter a string: ";


cin.getline(str, 100);

length = strlen(str);

for (int i = 0; i < length; i++) {


reversedStr[i] = str[length - i - 1];
}
reversedStr[length] = '\0'; // Null-terminate the reversed string

cout << "The reversed string is: " << reversedStr << endl;
return 0;
}
OUTPUT:
Enter a string: Hello World
The reversed string is: dlroW olleH

P-34
PROBLEM SOLVING AND PROGRAMMING USING C++
Program for Printing a Multiplication Table using nested for statement
#include <iostream.h>

int main() {
int size = 5;

for (int i = 1; i <= size; i++) {


for (int j = 1; j <= size; j++) {
cout << i * j << "\t";
}
cout << endl;
}

return 0;
}
OUTPUT:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Program for Printing a Rectangle of Stars using nested for Statement


#include <iostream.h>

int main() {
int rows = 4, cols = 6;

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
cout << "* ";
}
cout << endl;
}

return 0;
}
OUTPUT:
* * * * * *
* * * * * *
* * * * * *
* * * * * *

P-35
PROBLEM SOLVING AND PROGRAMMING USING C++
Program for Printing a Triangle of Stars using nested for Statement
#include <iostream.h>

int main() {
int height = 5;

for (int i = 1; i <= height; i++) {


for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}

return 0;
}
OUTPUT:
*
* *
* * *
* * * *
* * * * *

Program for Printing a Number Pyramid using nested for Statement


#include <iostream.h>

int main() {
int height = 5;

for (int i = 1; i <= height; i++) {


for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}

return 0;
}
OUTPUT:
1
1 2
1 2 3
1 2 4
1 2 3 4

P-36
PROBLEM SOLVING AND PROGRAMMING USING C++
Program for Finding the First Number Greater Than 10 using break Statement
#include <iostream.h>

int main() {
int limit = 20;

for (int i = 1; i <= limit; i++) {


if (i > 10) {
cout << "First number greater than 10 is " << i << endl;
break; // Exit the loop when the condition is met
}
}

return 0;
}
OUTPUT:
First number greater than 10 is 11

Program for Checking for Prime Number using break Statement


#include <iostream.h>

int main() {
int num = 29;
bool isPrime = true;

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0) {
isPrime = false;
cout << num << " is not a prime number." << endl;
break; // Exit the loop when a divisor is found
}
}

if (isPrime) {
cout << num << " is a prime number." << endl;
}

return 0;
}
OUTPUT:
29 is a prime number.

P-37
PROBLEM SOLVING AND PROGRAMMING USING C++
Program for Printing Multiples of 3 Up to 20 using break Statement
#include <iostream.h>

int main() {
for (int i = 3; i <= 20; i += 3) {
cout << i << " ";
if (i == 15) {
cout << endl << "Reached 15, stopping the loop." << endl;
break; // Exit the loop when the value reaches 15
}
}

return 0;
}
OUTPUT:
3 6 9 12 15
Reached 15, stopping the loop.

Program for Skipping Even Numbers using continue Statement


#include <iostream.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the rest of the loop for even numbers
}
cout << i << " ";
}
cout << endl;
return 0;
}
OUTPUT:
1 3 5 7 9

Program for Printing Multiples of 5 Except 15 using continue Statement


#include <iostream.h>

int main() {
for (int i = 5; i <= 50; i += 5) {
if (i == 15) {
continue; // Skip printing 15
}
cout << i << " ";
}
cout << endl;
return 0;
}
OUTPUT:
5 10 20 25 30 35 40 45 50

P-38
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS BASED ON ARRAYS


Program to Calculate Sum & Average of an 1d-Array
#include <iostream.h>
#define MAXSIZE 100

int main() {
int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;

cout << "Enter the value of N: ";


cin >> num;

cout << "Enter " << num << " numbers (-ve, +ve and zero): ";
for (i = 0; i < num; i++) {
cin >> array[i];
}

// Summation starts
for (i = 0; i < num; i++) {
if (array[i] < 0) {
negative_sum += array[i];
} else if (array[i] > 0) {
positive_sum += array[i];
}
total += array[i];
}
average = total / num;

cout << "Sum of all negative numbers = " << negative_sum << endl;
cout << "Sum of all positive numbers = " << positive_sum << endl;
cout << "Average of all input numbers = " << average << endl;

return 0;
}
OUTPUT:
Enter the value of N: 10
Enter 10 numbers (-ve, +ve and zero): -8 9 -100 -80 90 45 -23 -1 0 16
Sum of all negative numbers = -212
Sum of all positive numbers = 160
Average of all input numbers = -5.20

P-39
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find Largest Element of an 1d-Array
#include <iostream.h>

int main() {
int n;
float arr[100];

cout << "Enter total number of elements (1 to 100): ";


cin >> n;

for (int i = 0; i < n; ++i) {


cout << "Enter Number " << i + 1 << ": ";
cin >> arr[i];
}

float largest = arr[0];


for (int i = 1; i < n; ++i) {
if (arr[i] > largest) {
largest = arr[i];
}
}

cout << "Largest element = " << largest << endl;

return 0;
}
OUTPUT:
Enter total number of elements (1 to 100): 8
Enter Number 1: 23.4
Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5
Largest element = 55.5

P-40
PROBLEM SOLVING AND PROGRAMMING USING C++
PROGRAM TO CALCULATE THE SUM OF 2 1D-ARRAYS
#include <iostream.h>
#define MAXSIZE 100

int main() {
int size;

// Ask the user for the size of the arrays


cout << "Enter the size of the arrays: ";
cin >> size;

int array1[MAXSIZE], array2[MAXSIZE], sumArray[MAXSIZE];

// Input elements for the first array


cout << "Enter elements of the first array: ";
for (int i = 0; i < size; i++) {
cin >> array1[i];
}

// Input elements for the second array


cout << "Enter elements of the second array: ";
for (int i = 0; i < size; i++) {
cin >> array2[i];
}

// Calculate the sum of the two arrays


for (int i = 0; i < size; i++) {
sumArray[i] = array1[i] + array2[i];
}

// Output the sum array


cout << "Sum of the two arrays: ";
for (int i = 0; i < size; i++) {
cout << sumArray[i] << " ";
}
cout << endl;

return 0;
}
OUTPUT:
Enter the size of the arrays: 3
Enter elements of the first array: 1 2 3
Enter elements of the second array: 4 5 6
Sum of the two arrays: 5 7 9

P-41
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Generate Fibonacci Series Using an 1D-Array
#include <iostream.h>
#define MAXSIZE 100

int main() {
int fib[MAXSIZE];
int n;

cout << "Enter n value: ";


cin >> n;

if (n > 0) fib[0] = 0; // Ensure that we don't access invalid indices


if (n > 1) fib[1] = 1;

for (int i = 2; i < n; i++) {


fib[i] = fib[i - 1] + fib[i - 2];
}

cout << "Fibo series is: ";


for (int i = 0; i < n; i++) {
cout << fib[i] << " ";
}
cout << endl;

return 0;
}
OUTPUT:
Enter n value: 7
Fibo series is: 0 1 1 2 3 5 8

P-42
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find the Mean of an Array
#include <iostream.h>
#define MAXSIZE 100 // Define a maximum size for the array

int main() {
int size;

// Input the size of the array


cout << "Enter the number of elements in the array: ";
cin >> size;

// Ensure the size does not exceed MAXSIZE


if (size > MAXSIZE) {
cout << "Size exceeds maximum limit of " << MAXSIZE << endl;
return 1;
}

// Create an array of the given size


float array[MAXSIZE];
float sum = 0.0;

// Input the elements of the array


cout << "Enter " << size << " elements:" << endl;
for (int i = 0; i < size; ++i) {
cin >> array[i];
sum += array[i];
}

// Calculate the mean


float mean = sum / size;

// Output the mean


cout << "The mean of the array is: " << mean << endl;

return 0;
}
OUTPUT:
Enter the number of elements in the array: 5
Enter 5 elements:
10
20
30
40
50
The mean of the array is: 30

P-43
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Sort N Numbers in Ascending Order Using Bubble Sort
#include <iostream.h>
#define MAXSIZE 10

int main() {
int array[MAXSIZE];
int num;

cout << "Enter the value of num: ";


cin >> num;

cout << "Enter the elements one by one: ";


for (int i = 0; i < num; i++) {
cin >> array[i];
}

cout << "Input array is: ";


for (int i = 0; i < num; i++) {
cout << array[i] << " ";
}
cout << endl;

// Bubble sorting begins


for (int i = 0; i < num - 1; i++) {
for (int j = 0; j < num - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
cout << "Sorted array is: ";
for (int i = 0; i < num; i++) {
cout << array[i] << " ";
}
cout << endl;

return 0;
}
OUTPUT:
Enter the value of num: 6
Enter the elements one by one: 23 45 67 89 12 34
Input array is: 23 45 67 89 12 34
Sorted array is: 12 23 34 45 67 89

P-44
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Implement Linear Search
#include <iostream.h>

int main() {
int array[10];
int num, keynum, found = 0;

cout << "Enter the value of num (up to 10): ";


cin >> num;

cout << "Enter the elements one by one: ";


for (int i = 0; i < num; i++) {
cin >> array[i];
}

cout << "Enter the element to be searched: ";


cin >> keynum;

// Linear search begins


for (int i = 0; i < num; i++) {
if (keynum == array[i]) {
found = 1;
break;
}
}

if (found == 1) {
cout << "Element is present in the array" << endl;
} else {
cout << "Element is not present in the array" << endl;
}

return 0;
}
OUTPUT:
Enter the value of num: 5
Enter the elements one by one: 23 90 56 15 58
Enter the element to be searched: 56
Element is present in the array

P-45
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Accept Sorted Array and Do Search Using Binary Search
#include <iostream.h>
int main() {
int array[10];
int num, keynum;
int low, mid, high;

cout << "Enter the value of num (up to 10): ";


cin >> num;

cout << "Enter the elements one by one (sorted): ";


for (int i = 0; i < num; i++) {
cin >> array[i];
}

cout << "Input array elements: ";


for (int i = 0; i < num; i++) {
cout << array[i] << " ";
}
cout << endl;

cout << "Enter the element to be searched: ";


cin >> keynum;

low = 0;
high = num - 1;

// Binary searching begins


bool found = false;
while (low <= high) {
mid = (low + high) / 2;
if (keynum < array[mid]) {
high = mid - 1;
} else if (keynum > array[mid]) {
low = mid + 1;
} else {
found = true;
break;
}
}
if (found) {
cout << "SEARCH SUCCESSFUL" << endl;
} else {
cout << "SEARCH FAILED" << endl;
}
return 0;
}
OUTPUT:
Enter the value of num: 5
Enter the elements one by one (sorted): 15 23 56 58 90
Input array elements: 15 23 56 58 90
Enter the element to be searched: 58
SEARCH SUCCESSFUL

P-46
PROBLEM SOLVING AND PROGRAMMING USING C++
PROGRAM TO CALCULATE THE SUM OF 2 MATRICES
#include <iostream.h>
int main() {
const int MAX_SIZE = 10;
int array1[10][10], array2[10][10], arraysum[10][10];
int i, j, m, n;

cout << "Enter the order of the matrix array1 and array2: ";
cin >> m >> n;

cout << "Enter the elements of matrix array1: " << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cin >> array1[i][j];
}
}

cout << "Enter the elements of matrix array2: " << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cin >> array2[i][j];
}
}
// Addition
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
arraysum[i][j] = array1[i][j] + array2[i][j];
}
}
cout << "Sum matrix is: " << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cout << arraysum[i][j] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT:
Enter the order of the matrix array1 and array2: 3 3
Enter the elements of matrix array1:
1 1
1 1
Enter the elements of matrix array2:
1 1
1 1
Sum matrix is:
2 2
2 2

P-47
PROBLEM SOLVING AND PROGRAMMING USING C++
PROGRAM TO COMPUTE THE PRODUCT OF TWO MATRICES
#include <iostream.h>
int main() {
const int MAX_SIZE = 10;
int array1[10][10], array2[10][10], array3[10][10];
int m, n;
int i, j, k;

cout << "Enter the value of m and n: ";


cin >> m >> n;

cout << "Enter Matrix array1: " << endl;


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cin >> array1[i][j];
}
}

cout << "Enter Matrix array2: " << endl;


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cin >> array2[i][j];
}
}

// Initialize array3 to zero


for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
array3[i][j] = 0;
}
}
// Compute the product of array1 and array2
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
array3[i][j] += array1[i][k] * array2[k][j];
}
}
}
cout << "The product matrix is: " << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cout << array3[i][j] << " ";
}
cout << endl;
}

return 0;
}

P-48
PROBLEM SOLVING AND PROGRAMMING USING C++
OUTPUT:
Enter the value of m and n: 2 2
Enter Matrix array1:
1 1
1 1
Enter Matrix array2:
1 1
1 1
The product matrix is:
2 2
2 2

PROGRAM TO FIND THE TRANSPOSE OF A GIVEN MATRIX.


#include <iostream.h>
int main() {
int array[10][10];
int transpose[10][10];
int i, j, m, n;
cout << "Enter the order of the matrix (rows columns): ";
cin >> m >> n;
cout << "Enter the coefficients of the matrix:" << endl;
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
cin >> array[i][j];
}
}
// Compute transpose
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
transpose[j][i] = array[i][j];
}
}
cout << "Transpose of the matrix is:" << endl;
for (j = 0; j < n; ++j) {
for (i = 0; i < m; ++i) {
cout << transpose[j][i] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT:
Enter the order of the matrix (rows columns): 22
Enter the coefficients of the matrix:
1 2
3 4
Transpose of the matrix is:
1 3
2 4

P-49
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Find the Length of a String without using built-in functions
#include <iostream.h>

int main() {
char str[100];
int length = 0;

// Prompt the user for input


cout << "Enter a string: ";
cin.getline(str, 100);

// Calculate the length of the string


while (str[length] != '\0') {
length++;
}

// Output the length of the string


cout << "The length of the string is: " << length << endl;

return 0;
}
OUTPUT:
Enter a string: HelloWorld
The length of the string is: 10

P-50
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Concatenate Two Strings without using built-in functions
#include <iostream.h>

int main() {
char str1[100], str2[50];

// Prompt user for input


cout << "Enter the first string: ";
cin.getline(str1, 100);

cout << "Enter the second string: ";


cin.getline(str2, 50);

// Find the end of the first string


int i = 0;
while (str1[i] != '\0') {
i++;
}

// Append the second string to the first string


int j = 0;
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}

// Null-terminate the concatenated string


str1[i] = '\0';

// Output the concatenated string


cout << "The concatenated string is: " << str1 << endl;

return 0;
}
OUTPUT:
Enter the first string: Hello
Enter the second string: World
The concatenated string is: HelloWorld

P-51
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement any 5 String related built-in functions
#include <iostream>
#include <cstring> // Include the cstring header for string functions
using namespace std;

int main() {
// 1. strlen(): Get the length of a string
char str1[] = "Hello, World!";
cout << "Length of str1: " << strlen(str1) << endl;

// 2. strcpy(): Copy one string to another


char str2[50];
strcpy(str2, str1);
cout << "Copied str1 to str2: " << str2 << endl;

// 3. strcat(): Concatenate two strings


char str3[50] = "Welcome ";
strcat(str3, "Home");
cout << "Concatenated string: " << str3 << endl;

// 4. strcmp(): Compare two strings


char str4[] = "apple";
char str5[] = "banana";
int result = strcmp(str4, str5);
if (result == 0) {
cout << "str4 and str5 are equal." << endl;
} else if (result < 0) {
cout << "str4 is less than str5." << endl;
} else {
cout << "str4 is greater than str5." << endl;
}

// 5. strstr(): Find a substring within a string


char str6[] = "This is a simple string";
char* substr = strstr(str6, "simple");
if (substr != nullptr) {
cout << "Substring found: " << substr << endl;
} else {
cout << "Substring not found." << endl;
}

return 0;
}
OUTPUT:
Length of str1: 13
Copied str1 to str2: Hello, World!
Concatenated string: Welcome Home
str4 is less than str5.
Substring found: simple string

P-52
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS BASED ON FUNCTIONS


Program to Find the Square of a Number Using a Function
#include <iostream.h>

int square(int n) {
return n * n;
}

int main() {
int n, p;
cout << "Enter a number: ";
cin >> n;
p = square(n);
cout << "The square of the number is " << p << endl;
return 0;
}
OUTPUT:
Enter a number: 4
The square of the number is 16

Program to Find the Cube of a Number Using a Function


#include <iostream.h>

int cube(int n) {
return n * n * n;
}

int main() {
int n, p;
cout << "Enter a number: ";
cin >> n;
p = cube(n);
cout << "The cube of the number is " << p << endl;
return 0;
}
OUTPUT:
Enter a number: 4
The cube of the number is 64

P-53
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Calculate the Power of a Number Using Recursion
#include <iostream.h>

int power(int base, int exp) {


if (exp == 0) return 1;
return base * power(base, exp - 1);
}

int main() {
int base, exp;
cout << "Enter base number: ";
cin >> base;
cout << "Enter power number (positive integer): ";
cin >> exp;
cout << base << "^" << exp << " = " << power(base, exp) << endl;
return 0;
}
OUTPUT:
Enter base number: 3
Enter power number (positive integer): 3
3^3 = 27

Program to Print Fibonacci Series Using Recursion


#include <iostream.h>

int Fib(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return Fib(n - 1) + Fib(n - 2);
}

int main() {
int n;
cout << "Enter n value: ";
cin >> n;
cout << "Fibonacci series . . . " << endl;
for (int i = 0; i < n; i++) {
cout << Fib(i) << "\t";
}
cout << endl;
return 0;
}
OUTPUT:
Enter n value: 7
Fibonacci series . . .
0 1 1 2 3 5 8

P-54
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Calculate Factorial of a Number Using Recursion
#include <iostream.h>

long long fact(int n) {


if (n == 0) return 1;
return n * fact(n - 1);
}

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << fact(n) << endl;
return 0;
}
OUTPUT:
Enter a positive integer: 6
Factorial of 6 = 720

Program to Solve Tower of Hanoi Problem Using Recursion


#include <iostream.h>

void towers(int num, char frompeg, char topeg, char auxpeg) {


if (num == 1) {
cout << "\nMove disk 1 from peg " << frompeg << " to peg " << topeg;
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
cout << "\nMove disk " << num << " from peg " << frompeg << " to peg " << topeg;
towers(num - 1, auxpeg, topeg, frompeg);
}

int main() {
int num;
cout << "Enter the number of disks: ";
cin >> num;
cout << "The sequence of moves involved in the Tower of Hanoi are:\n";
towers(num, 'A', 'C', 'B');
cout << endl;
return 0;
}
OUTPUT:
Enter the number of disks: 2
The sequence of moves involved in the Tower of Hanoi are:

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B

P-55
PROBLEM SOLVING AND PROGRAMMING USING C++
PROGRAM TO PERFORM BINARY SEARCH USING RECURSION
#include <iostream.h>

// Function to perform bubble sort


void bubble_sort(int list[], int size) {
int temp;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (list[i] > list[j]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}

// Function to perform binary search recursively


void binary_search(int list[], int lo, int hi, int key) {
if (lo > hi) {
cout << "Key not found" << endl;
return;
}

int mid = (lo + hi) / 2;

if (list[mid] == key) {
cout << "Key found" << endl;
} else if (list[mid] > key) {
binary_search(list, lo, mid - 1, key);
} else {
binary_search(list, mid + 1, hi, key);
}
}

int main() {
int key, size;

cout << "Enter size of the list: ";


cin >> size;

int list[25];
cout << "Enter " << size << " numbers: ";
for (int i = 0; i < size; i++) {
cin >> list[i];
}

bubble_sort(list, size);

P-56
PROBLEM SOLVING AND PROGRAMMING USING C++
cout << "\nEnter key to search: ";
cin >> key;

binary_search(list, 0, size - 1, key);

return 0;

OUTPUT:
Enter size of the list: 10
Enter 10 numbers: 83 86 77 15 93 35 86 92 49 21
Enter key to search: 21

Program to illustrate Accessing Global and Local Variables


#include <iostream.h>

// Global variable
int value = 10;

void display() {
int value = 20; // Local variable
// Accessing global variable using scope resolution operator
cout << "Local value: " << value << endl;
cout << "Global value: " << ::value << endl;
}

int main() {
display();
return 0;
}
OUTPUT:
Local value: 20
Global value: 10

P-57
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS BASED ON STRUCTURES & UNIONS


Program to Store and Display Student Information Using Structure
#include <iostream.h>
#include <iomanip.h> // for setting precision

struct Student {
char name[50];
int roll;
float marks;
};

int main() {
Student s;

cout << "Enter information of student:" << endl;


cout << "Enter name: ";
cin >> s.name;
cout << "Enter roll number: ";
cin >> s.roll;
cout << "Enter marks: ";
cin >> s.marks;

cout << "\nDisplaying Information\n";


cout << "Name: " << s.name << endl;
cout << "Roll: " << s.roll << endl;
cout << "Marks: " << fixed << setprecision(2) << s.marks << endl;

return 0;
}
OUTPUT:
Enter information of student:
Enter name: Adele
Enter roll number: 21
Enter marks: 334.5

Displaying Information
Name: Adele
Roll: 21
Marks: 334.50

P-58
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Add Two Complex Numbers Using Structure and Function
#include <iostream.h>

struct Complex {
float real;
float imag;
};

Complex add(Complex n1, Complex n2) {


Complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return temp;
}

int main() {
Complex n1, n2, temp;

cout << "For 1st complex number\n";


cout << "Enter real and imaginary respectively:\n";
cin >> n1.real >> n1.imag;

cout << "\nFor 2nd complex number\n";


cout << "Enter real and imaginary respectively:\n";
cin >> n2.real >> n2.imag;

temp = add(n1, n2);


cout << "Sum = " << temp.real << " + " << temp.imag << "i" << endl;

return 0;
}
OUTPUT:
For 1st complex number
Enter real and imaginary respectively:
2.3 4.5

For 2nd complex number


Enter real and imaginary respectively:
3.4 5

Sum = 5.7 + 9.5i

P-59
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Store and Display Information of Multiple Students Using Structure
#include <iostream.h>

struct Student {
char name[50];
int roll;
float marks;
};

int main() {
Student s[10];

cout << "Enter information of students:" << endl;


for (int i = 0; i < 10; ++i) {
s[i].roll = i + 1;
cout << "\nFor roll number " << s[i].roll << endl;
cout << "Enter name: ";
cin >> s[i].name;
cout << "Enter marks: ";
cin >> s[i].marks;
cout << endl;
}

cout << "Displaying information of students:" << endl << endl;


for (int i = 0; i < 10; ++i) {
cout << "\nInformation for roll number " << s[i].roll << ":\n";
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}

return 0;
}
OUTPUT:
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
For roll number 2
Enter name: Jerry
Enter marks: 89

Displaying information of students:


Information for roll number 1:
Name: Tom
Marks: 98
Information for roll number 2:
Name: Jerry
Marks: 89

P-60
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to demonstrate union
#include <iostream.h>

union Data {
int intValue;
float floatValue;
char charValue;
};

int main() {
Data data;

// Assign and display integer value


data.intValue = 42;
cout << "data.intValue: " << data.intValue << endl;

// Assign and display float value


data.floatValue = 3.14;
cout << "data.floatValue: " << data.floatValue << endl;

// Assign and display char value


data.charValue = 'A';
cout << "data.charValue: " << data.charValue << endl;

// Note: Only the last assigned value is valid; previous values are overwritten
cout << "After assigning char
OUTPUT:
data.intValue: 42
data.floatValue: 3.14
data.charValue: A
After assigning charValue, intValue: 65
After assigning charValue, floatValue: 6.11598e-44

P-61
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to implement employee data using union
#include <iostream.h>
#include <string.h> // Use string.h for Turbo C++ instead of cstring

// Define a union to hold different data types


union EmployeeData {
int id;
float salary;
char name[50];
};

int main() {
// Create a union variable
EmployeeData employee;

// Store an integer ID in the union


employee.id = 12345;
cout << "Employee ID: " << employee.id << endl;

// Store a float salary in the union (overwrites the ID)


employee.salary = 45678.90;
cout << "Employee Salary: " << employee.salary << endl;

// Store a name in the union (overwrites the salary)


strcpy(employee.name, "John Doe");
cout << "Employee Name: " << employee.name << endl;

// Display values to show how they overlap in memory


cout << "After storing name value:" << endl;
cout << "Employee ID (overwritten): " << employee.id << endl;
cout << "Employee Salary (overwritten): " << employee.salary << endl;

return 0;
}
OUTPUT:
Employee ID: 12345
Employee Salary: 45678.9
Employee Name: John Doe
After storing name value:
Employee ID (overwritten): 1125827
Employee Salary (overwritten): 2.16608e-38

P-62
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS ON CLASSES AND OBJECTS

Program to illustrate Person Class with Public and Private Members


#include <iostream>
using namespace std;

class Person {
private:
string name;
int age;

public:
void setName(string n) {
name = n;
}

void setAge(int a) {
age = a;
}

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person person;
person.setName("John Doe");
person.setAge(25);
person.display();

return 0;
}
OUTPUT:
Name: John Doe, Age: 25

P-63
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Employee Class with Public and Private Members
#include <iostream>
using namespace std;

class Employee {
private:
string name;
double salary;

public:
void setName(string n) {
name = n;
}

void setSalary(double s) {
salary = s;
}

void display() {
cout << "Employee Name: " << name << ", Salary: $" << salary << endl;
}
};

int main() {
Employee emp;
emp.setName("Alice Smith");
emp.setSalary(75000.50);
emp.display();

return 0;
}
OUTPUT:
Employee Name: Alice Smith, Salary: $75000.5

P-64
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Rectangle Objects
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Member function to set dimensions
void setDimensions(int l, int w) {
length = l;
width = w;
}

// Member function to calculate area


int area() {
return length * width;
}
};

int main() {
Rectangle rect1, rect2; // Create two Rectangle objects

// Set dimensions for rect1


rect1.setDimensions(5, 3);
cout << "Area of Rectangle 1: " << rect1.area() << endl;

// Set dimensions for rect2


rect2.setDimensions(7, 4);
cout << "Area of Rectangle 2: " << rect2.area() << endl;

return 0;
}
OUTPUT:
Area of Rectangle 1: 15
Area of Rectangle 2: 28

P-65
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Student Objects
#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

public:
// Member function to set student details
void setDetails(string n, int a) {
name = n;
age = a;
}

// Member function to display student details


void displayDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student student1, student2; // Create two Student objects

// Set and display details for student1


student1.setDetails("Alice", 20);
student1.displayDetails();

// Set and display details for student2


student2.setDetails("Bob", 22);
student2.displayDetails();

return 0;
}
OUTPUT:
Name: Alice, Age: 20
Name: Bob, Age: 22

P-66
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Static Data Member for ID Generation
#include <iostream>
using namespace std;

class IDGenerator {
private:
static int nextID;
int id;

public:
IDGenerator() {
id = nextID++;
}

void displayID() {
cout << "Object ID: " << id << endl;
}
};

int IDGenerator::nextID = 1;

int main() {
IDGenerator obj1, obj2, obj3;
obj1.displayID();
obj2.displayID();
obj3.displayID();

return 0;
}
OUTPUT:
Object ID: 1
Object ID: 2
Object ID: 3

P-67
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Counting Objects Using static member functions
#include <iostream>
using namespace std;

class Counter {
private:
static int count;

public:
Counter() {
count++;
}

static int getCount() {


return count;
}
};

int Counter::count = 0;

int main() {
Counter c1, c2, c3;
cout << "Number of objects created: " << Counter::getCount() << endl;
return 0;
}
OUTPUT:
Number of objects created: 3

P-68
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Array of Objects
#include <iostream>
using namespace std;

class Student {
public:
string name;
int age;

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student students[3]; // Array of 3 Student objects

students[0].name = "Alice";
students[0].age = 20;

students[1].name = "Bob";
students[1].age = 21;

students[2].name = "Charlie";
students[2].age = 22;

for (int i = 0; i < 3; i++) {


students[i].display();
}

return 0;
}
OUTPUT:
Name: Alice, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 22

P-69
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Average Calculation of students’ marks
#include <iostream>
using namespace std;

class Student {
public:
int marks;

Student() {
marks = 0;
}
};

int main() {
Student students[5];
int totalMarks = 0;

// Input marks for each student


for (int i = 0; i < 5; i++) {
cout << "Enter marks for student " << i + 1 << ": ";
cin >> students[i].marks;
totalMarks += students[i].marks;
}

// Calculate and display total and average marks


double averageMarks = static_cast<double>(totalMarks) / 5;
cout << "Total Marks: " << totalMarks << endl;
cout << "Average Marks: " << averageMarks << endl;

return 0;
}
OUTPUT:
Enter marks for student 1: 85
Enter marks for student 2: 90
Enter marks for student 3: 78
Enter marks for student 4: 88
Enter marks for student 5: 92
Total Marks: 433
Average Marks: 86.6

P-70
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate a friend Function
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box() : length(0) {}

// Friend function declaration


friend void displayLength(Box b);
};

// Friend function definition


void displayLength(Box b) {
cout << "Length: " << b.length << endl;
}

int main() {
Box box;
displayLength(box); // Accesses private data member using the friend
function

return 0;
}
OUTPUT:
Length: 0

P-71
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate using a friend Function to Add Two Objects
#include <iostream>
using namespace std;

class Sum {
private:
int num;

public:
Sum(int n) : num(n) {}

// Friend function declaration


friend int add(Sum s1, Sum s2);
};

// Friend function definition


int add(Sum s1, Sum s2) {
return s1.num + s2.num;
}

int main() {
Sum s1(10), s2(20);
cout << "Sum: " << add(s1, s2) << endl; // Accesses private data members
using the friend function

return 0;
}
OUTPUT:
Sum: 30

P-72
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Simple Inline Function
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Constructor
Rectangle(int l, int w) : length(l), width(w) {}

// Inline function to calculate area


inline int area() {
return length * width;
}
};

int main() {
Rectangle rect(10, 5);
cout << "Area of Rectangle: " << rect.area() << endl;

return 0;
}
OUTPUT:
Area of Rectangle: 50

P-73
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Inline Function with Parameters
#include <iostream>
using namespace std;

class Circle {
private:
float radius;

public:
// Constructor
Circle(float r) : radius(r) {}

// Inline function to calculate circumference


inline float circumference() {
return 2 * 3.14159 * radius;
}
};

int main() {
Circle circle(5.0);
cout << "Circumference of Circle: " << circle.circumference() << " units"
<< endl;

return 0;
}
OUTPUT:
Circumference of Circle: 31.4159 units

P-74
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Accessing Class Member Functions using Scope Resolution
Operator (::)
#include <iostream>
using namespace std;

class MyClass {
public:
void show() {
cout << "Member function of MyClass" << endl;
}

// Static member function


static void staticShow() {
cout << "Static member function of MyClass" << endl;
}
};

int main() {
MyClass obj;
obj.show(); // Calls non-static member function
MyClass::staticShow(); // Calls static member function
return 0;
}
OUTPUT:
Member function of MyClass
Static member function of MyClass

P-75
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS ON CONSTRUCTORS AND DESTRUCTORS

Program to illustrate Basic Default Constructor


#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Default Constructor
Rectangle() {
length = 5;
width = 10;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect; // Default constructor is called
cout << "Area of Rectangle: " << rect.area() << endl;
return 0;
}
OUTPUT:
Area of Rectangle: 50

P-76
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Default Constructor with Initialization
#include <iostream>

class Circle {
private:
double radius;

public:
// Default Constructor
Circle() : radius(7.5) {}

double area() {
return 3.14159 * radius * radius;
}
};

int main() {
Circle circle; // Default constructor is called
cout << "Area of Circle: " << circle.area() << endl;
return 0;
}
OUTPUT:
Area of Circle: 176.715

Program to illustrate Default Constructor with User-defined Values


#include <iostream>

class Square {
private:
int side;

public:
// Default Constructor
Square() {
side = 4;
}

int area() {
return side * side;
}
};

int main() {
Square sq; // Default constructor is called
cout << "Area of Square: " << sq.area() << endl;
return 0;
}
OUTPUT:
Area of Square: 16

P-77
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Objects Using Default Constructor
#include <iostream>
using namespace std;

class Triangle {
private:
int base;
int height;

public:
// Default Constructor
Triangle() {
base = 3;
height = 6;
}

int area() {
return (base * height) / 2;
}
};

int main() {
Triangle tri1, tri2; // Default constructor is called for both objects
cout << "Area of Triangle 1: " << tri1.area() << endl;
cout << "Area of Triangle 2: " << tri2.area() << endl;
return 0;
}
OUTPUT:
Area of Triangle 1: 9
Area of Triangle 2: 9

P-78
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Default Constructor with Multiple Data Members
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;
int height;

public:
// Default Constructor
Rectangle() {
length = 5;
width = 10;
height = 15;
}

int volume() {
return length * width * height;
}
};

int main() {
Rectangle rect; // Default constructor is called
cout << "Volume of Rectangle: " << rect.volume() << endl;
return 0;
}
OUTPUT:
Volume of Rectangle: 750

P-79
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Parameterized Constructor
#include <iostream>
class Rectangle {
private:
int length, width;

public:
// Parameterized Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect(5, 10); // Parameterized constructor is called
cout << "Area of Rectangle: " << rect.area() << endl;
return 0;
}
OUTPUT:
Area of Rectangle: 50

Parameterized Constructor with Multiple Parameters


#include <iostream>
class Circle {
private:
double radius;

public:
// Parameterized Constructor
Circle(double r) {
radius = r;
}

double area() {
return 3.14159 * radius * radius;
}
};
int main() {
Circle circle(7.5); // Parameterized constructor is called
cout << "Area of Circle: " << circle.area() << endl;
return 0;
}
OUTPUT:
Area of Circle: 176.715

P-80
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Parameterized Constructor for a Square
#include <iostream>
using namespace std;

class Square {
private:
int side;

public:
// Parameterized Constructor
Square(int s) {
side = s;
}

int area() {
return side * side;
}
};

int main() {
Square sq(4); // Parameterized constructor is called
cout << "Area of Square: " << sq.area() << endl;
return 0;
}
OUTPUT:
Area of Square: 16

P-81
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Parameterized Constructor for Multiple Objects
#include <iostream>
using namespace std;

class Triangle {
private:
int base;
int height;

public:
// Parameterized Constructor
Triangle(int b, int h) {
base = b;
height = h;
}

int area() {
return (base * height) / 2;
}
};

int main() {
Triangle tri1(3, 6); // Parameterized constructor is called
Triangle tri2(5, 10); // Parameterized constructor is called
cout << "Area of Triangle 1: " << tri1.area() << endl;
cout << "Area of Triangle 2: " << tri2.area() << endl;
return 0;
}
OUTPUT:
Area of Triangle 1: 9
Area of Triangle 2: 25

P-82
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Parameterized Constructor with Default Values
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Parameterized Constructor with default values
Rectangle(int l = 5, int w = 10) {
length = l;
width = w;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect1; // Calls constructor with default values
Rectangle rect2(7, 12); // Calls constructor with custom values
cout << "Area of Rectangle 1: " << rect1.area() << endl;
cout << "Area of Rectangle 2: " << rect2.area() << endl;
return 0;
}
OUTPUT:
Area of Rectangle 1: 50
Area of Rectangle 2: 84

P-83
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Copy Constructor on rectantle class
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
// Parameterized Constructor
Rectangle(int l, int w) : length(l), width(w) {}

// Copy Constructor
Rectangle(const Rectangle &rect) {
length = rect.length;
width = rect.width;
}

int area() {
return length * width;
}
};

int main() {
Rectangle rect1(5, 10); // Create object using parameterized constructor
Rectangle rect2(rect1); // Create object using copy constructor

cout << "Area of Rectangle 1: " << rect1.area() << endl;


cout << "Area of Rectangle 2: " << rect2.area() << endl;

return 0;
}
OUTPUT:
Area of Rectangle 1: 50
Area of Rectangle 2: 50

P-84
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Copy Constructor on point class
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}

// Copy Constructor
Point(const Point &p) {
x = p.x;
y = p.y;
}

void display() const {


cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
Point p1(3, 4); // Create object using parameterized constructor
Point p2(p1); // Create object using copy constructor

cout << "Point 1: ";


p1.display();
cout << "Point 2 (Copy of Point 1): ";
p2.display();

return 0;
}
OUTPUT:
Point 1: (3, 4)
Point 2 (Copy of Point 1): (3, 4)

P-85
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Copy Constructor in a Class with Multiple Data Members
#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

public:
// Parameterized Constructor
Student(string n, int a) : name(n), age(a) {}

// Copy Constructor
Student(const Student &s) {
name = s.name;
age = s.age;
}

void display() const {


cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Student s1("Alice", 20); // Create object using parameterized constructor
Student s2(s1); // Create object using copy constructor

cout << "Student 1: ";


s1.display();
cout << "Student 2 (Copy of Student 1): ";
s2.display();

return 0;
}
OUTPUT:
Student 1: Name: Alice, Age: 20
Student 2 (Copy of Student 1): Name: Alice, Age: 20

P-86
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Dynamic Constructor
#include <iostream>

class Array {
private:
int* data;
int size;

public:
// Dynamic Constructor
Array(int s) {
size = s;
data = new int[size];
}

~Array() {
delete[] data;
}

void setValue(int index, int value) {


if (index >= 0 && index < size) {
data[index] = value;
}
}

void display() {
for (int i = 0; i < size; i++) {
cout << data[i] << " ";
}
cout << endl;
}
};

int main() {
Array arr(5); // Create an array of size 5

arr.setValue(0, 10);
arr.setValue(1, 20);
arr.setValue(2, 30);
arr.setValue(3, 40);
arr.setValue(4, 50);

cout << "Array contents: ";


arr.display(); // Display array contents

return 0;
}
OUTPUT:
Array contents: 10 20 30 40 50

P-87
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Copy Constructor with Dynamic Memory Allocation
#include <iostream>
using namespace std;

class Circle {
private:
double *radius;

public:
// Parameterized Constructor
Circle(double r) {
radius = new double(r);
}

// Copy Constructor
Circle(const Circle &c) {
radius = new double(*c.radius);
}

~Circle() {
delete radius;
}

double area() const {


return 3.14159 * (*radius) * (*radius);
}
};

int main() {
Circle c1(7.5); // Create object using parameterized constructor
Circle c2(c1); // Create object using copy constructor

cout << "Area of Circle 1: " << c1.area() << endl;


cout << "Area of Circle 2: " << c2.area() << endl;

return 0;
}
OUTPUT:
Area of Circle 1: 176.715
Area of Circle 2: 176.715

P-88
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Overloading Constructors for a Circle Class
#include <iostream>
using namespace std;

class Circle {
private:
double radius;

public:
// Default Constructor
Circle() : radius(1.0) {
cout << "Default Constructor called" << endl;
}

// Parameterized Constructor
Circle(double r) : radius(r) {
cout << "Parameterized Constructor called" << endl;
}

// Copy Constructor
Circle(const Circle &c) {
radius = c.radius;
cout << "Copy Constructor called" << endl;
}

void display() {
cout << "Radius: " << radius << endl;
}
};

int main() {
Circle c1; // Calls default constructor
Circle c2(4.5); // Calls parameterized constructor
Circle c3(c2); // Calls copy constructor

cout << "Circle c1: ";


c1.display();

cout << "Circle c2: ";


c2.display();

cout << "Circle c3: ";


c3.display();

return 0;
}
OUTPUT:
Default Constructor called
Parameterized Constructor called
Copy Constructor called
Circle c1: Radius: 1
Circle c2: Radius: 4.5
Circle c3: Radius: 4.5

P-89
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Overloading Constructors in a Point Class
#include <iostream>

class Point {
private:
int x, y;

public:
// Default Constructor
Point() : x(0), y(0) {
cout << "Default Constructor called" << endl;
}

// Parameterized Constructor
Point(int a, int b) : x(a), y(b) {
cout << "Parameterized Constructor called" << endl;
}

// Copy Constructor
Point(const Point &p) {
x = p.x;
y = p.y;
cout << "Copy Constructor called" << endl;
}

void display() {
cout << "X: " << x << ", Y: " << y << endl;
}
};

int main() {
Point p1; // Calls default constructor
Point p2(3, 4); // Calls parameterized constructor
Point p3(p2); // Calls copy constructor

cout << "Point p1: ";


p1.display();

cout << "Point p2: ";


p2.display();

cout << "Point p3: ";


p3.display();

return 0;
}
OUTPUT:
Default Constructor called
Parameterized Constructor called
Copy Constructor called
Point p1: X: 0, Y: 0
Point p2: X: 3, Y: 4
Point p3: X: 3, Y: 4

P-90
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Overloading Constructors in a Complex Number Class
#include <iostream>

class Complex {
private:
int real, imag;

public:
// Default Constructor
Complex() : real(0), imag(0) {
cout << "Default Constructor called" << endl;
}

// Parameterized Constructor
Complex(int r, int i) : real(r), imag(i) {
cout << "Parameterized Constructor called" << endl;
}

// Copy Constructor
Complex(const Complex &c) {
real = c.real;
imag = c.imag;
cout << "Copy Constructor called" << endl;
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1; // Calls default constructor
Complex c2(5, 10); // Calls parameterized constructor
Complex c3(c2); // Calls copy constructor

cout << "Complex c1: ";


c1.display();

cout << "Complex c2: ";


c2.display();

cout << "Complex c3: ";


c3.display();

return 0;
}
OUTPUT:
Default Constructor called
Parameterized Constructor called
Copy Constructor called
Complex c1: 0 + 0i
Complex c2: 5 + 10i
Complex c3: 5 + 10i

P-91
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Destructor for Releasing Dynamically Allocated Memory
#include <iostream>
using namespace std;

class SimpleClass {
private:
int* data;

public:
// Constructor to allocate memory
SimpleClass(int value) {
data = new int(value);
cout << "Constructor: Memory allocated for data with value " << *data
<< endl;
}

// Destructor to release memory


~SimpleClass() {
delete data;
cout << "Destructor: Memory released for data" << endl;
}
};

int main() {
SimpleClass obj(10);
return 0;
}
OUTPUT:
Constructor: Memory allocated for data with value 10
Destructor: Memory released for data

P-92
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Destructor for Releasing Arrays
#include <iostream>
using namespace std;

class ArrayClass {
private:
int* arr;
int size;

public:
// Constructor to allocate an array
ArrayClass(int n) {
size = n;
arr = new int[size];
cout << "Constructor: Array of size " << size << " allocated." << endl;
}

// Destructor to release the array


~ArrayClass() {
delete[] arr;
cout << "Destructor: Array memory released." << endl;
}
};

int main() {
ArrayClass obj(5);
return 0;
}
OUTPUT:
Constructor: Array of size 5 allocated.
Destructor: Array memory released.

P-93
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS ON OPERATOR-OVERLOADING

Program to Overload the ++ Operator (Prefix) to Increment a Counter


#include <iostream>
using namespace std;

class Counter {
private:
int value;

public:
Counter(int v = 0) : value(v) {}

// Overloading the unary ++ operator (pre-increment)


void operator++() {
++value;
}

void display() const {


cout << "Value: " << value << endl;
}
};

int main() {
Counter c(5);
cout << "Original Value: ";
c.display();

++c; // Increment the value using overloaded ++ operator


cout << "Value After Increment: ";
c.display();

return 0;
}
OUTPUT:
Original Value: 5
Value After Increment: 6

P-94
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Overload the - Operator to Negate a Point's Coordinates
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
Point(int xCoord = 0, int yCoord = 0) : x(xCoord), y(yCoord) {}

// Overloading the unary - operator to negate the coordinates


Point operator-() const {
return Point(-x, -y);
}

void display() const {


cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
Point p1(3, 4);
Point p2 = -p1; // Calls the overloaded unary - operator
p2.display(); // Output: (-3, -4)

return 0;
}
OUTPUT:
(-3, -4)

P-95
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to overload the unary ! operator
#include <iostream>
using namespace std;

class Boolean {
private:
bool value;

public:
Boolean(bool v = true) : value(v) {}

// Overloading the unary ! operator


bool operator!() {
return !value;
}

void display() const {


cout << "Value: " << (value ? "true" : "false") << endl;
}
};

int main() {
Boolean b1(true);
cout << "Original Value: ";
b1.display();

Boolean b2 = !b1; // Toggle the boolean value using overloaded ! operator


cout << "Value After Toggle: ";
b2.display();

return 0;
}
OUTPUT:
Original Value: true
Value After Toggle: false

P-96
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Overload the * Operator for Multiplying Fractions
#include <iostream>
using namespace std;

class Fraction {
private:
int numerator;
int denominator;

public:
Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {}

// Overloading the * operator to multiply two fractions


Fraction operator*(const Fraction &f) {
return Fraction(numerator * f.numerator, denominator * f.denominator);
}

void display() {
cout << numerator << "/" << denominator << endl;
}
};

int main() {
Fraction f1(2, 3), f2(3, 4);
Fraction f3 = f1 * f2; // Calls the overloaded * operator
f3.display(); // Output: 6/12

return 0;
}
OUTPUT:
6/12

P-97
PROBLEM SOLVING AND PROGRAMMING USING C++
Program To Overload the - Operator for Subtracting 2D Points
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
Point(int xCoord = 0, int yCoord = 0) : x(xCoord), y(yCoord) {}

// Overloading the - operator to subtract two points


Point operator-(const Point &p) {
return Point(x - p.x, y - p.y);
}

void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
Point p1(5, 7), p2(2, 3);
Point p3 = p1 - p2; // Calls the overloaded - operator
p3.display(); // Output: (3, 4)

return 0;
}
OUTPUT:
(3, 4)

P-98
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Overload the / Operator for Dividing Vectors by a Scalar
#include <iostream>
using namespace std;

class Vector {
private:
int x, y;

public:
Vector(int xCoord = 0, int yCoord = 0) : x(xCoord), y(yCoord) {}

// Overloading the / operator to divide a vector by a scalar


Vector operator/(int scalar) {
return Vector(x / scalar, y / scalar);
}

void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
Vector v(10, 20);
Vector result = v / 2; // Calls the overloaded / operator
result.display(); // Output: (5, 10)

return 0;
}
OUTPUT:
(5, 10)

P-99
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS ON INHERITANCE

Program to illustrate Basic Single Inheritance


#include <iostream>
using namespace std;

class Base {
public:
void showBase() {
cout << "Base class function called." << endl;
}
};

class Derived : public Base {


public:
void showDerived() {
cout << "Derived class function called." << endl;
}
};

int main() {
Derived obj;
obj.showBase();
obj.showDerived();
return 0;
}
OUTPUT:
Base class function called.
Derived class function called.

P-100
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Single Inheritance with Data Members
#include <iostream>
using namespace std;

class Base {
protected:
int num;
public:
void setNum(int n) {
num = n;
}
};

class Derived : public Base {


public:
void showNum() {
cout << "Number: " << num << endl;
}
};

int main() {
Derived obj;
obj.setNum(100);
obj.showNum();
return 0;
}
OUTPUT:
Number: 100

P-101
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Single Inheritance with Constructor
#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base class constructor called." << endl;
}
};

class Derived : public Base {


public:
Derived() {
cout << "Derived class constructor called." << endl;
}
};

int main() {
Derived obj;
return 0;
}
OUTPUT:
Base class constructor called.
Derived class constructor called.

P-102
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Single Inheritance with Accessing Protected Data Members
via Public Methods
#include <iostream>
using namespace std;

class Base {
protected:
int protectedNum;
public:
int publicNum;
void setNums(int p, int q) {
protectedNum = p;
publicNum = q;
}
};

class Derived : public Base {


public:
void showNums() {
cout << "Protected Number: " << protectedNum << endl;
cout << "Public Number: " << publicNum << endl;
}
};

int main() {
Derived obj;
obj.setNums(50, 100);
obj.showNums();
return 0;
}
OUTPUT:
Protected Number: 50
Public Number: 100

P-103
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Single Inheritance with Accessing Private Data Members
via Public Methods
#include <iostream>
using namespace std;

class Base {
private:
int privateNum;
public:
void setPrivateNum(int p) {
privateNum = p;
}
int getPrivateNum() {
return privateNum;
}
};

class Derived : public Base {


public:
void showPrivateNum() {
cout << "Private Number: " << getPrivateNum() << endl;
}
};

int main() {
Derived obj;
obj.setPrivateNum(90);
obj.showPrivateNum();
return 0;
}
OUTPUT:
Private Number: 90

P-104
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Multi-level Inheritance
#include <iostream>
using namespace std;

class A {
public:
void displayA() {
cout << "Class A method called." << endl;
}
};

class B : public A {
public:
void displayB() {
cout << "Class B method called." << endl;
}
};

class C : public B {
public:
void displayC() {
cout << "Class C method called." << endl;
}
};

int main() {
C obj;
obj.displayA(); // Calling method from class A
obj.displayB(); // Calling method from class B
obj.displayC(); // Calling method from class C
return 0;
}
OUTPUT:
Class A method called.
Class B method called.
Class C method called.

P-105
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multi-level Inheritance with Data Members
#include <iostream>
using namespace std;

class A {
protected:
int x;
public:
void setX(int val) {
x = val;
}
};

class B : public A {
protected:
int y;
public:
void setY(int val) {
y = val;
}
};

class C : public B {
public:
void display() {
cout << "x = " << x << ", y = " << y << ", Sum = " << (x + y) << endl;
}
};

int main() {
C obj;
obj.setX(10);
obj.setY(20);
obj.display();
return 0;
}
OUTPUT:
x = 10, y = 20, Sum = 30

P-106
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multi-level Inheritance with Constructors
#include <iostream>
using namespace std;

class A {
public:
A() {
cout << "Constructor of Class A" << endl;
}
};

class B : public A {
public:
B() {
cout << "Constructor of Class B" << endl;
}
};

class C : public B {
public:
C() {
cout << "Constructor of Class C" << endl;
}
};

int main() {
C obj; // Creating an object of class C
return 0;
}
OUTPUT:
Constructor of Class A
Constructor of Class B
Constructor of Class C

P-107
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multi-level Inheritance with Protected Access Specifier
#include <iostream>
using namespace std;

class A {
protected:
int num;
public:
void setNum(int val) {
num = val;
}
};

class B : public A {
public:
void doubleNum() {
num *= 2;
}
};

class C : public B {
public:
void displayNum() {
cout << "Value of num: " << num << endl;
}
};

int main() {
C obj;
obj.setNum(15);
obj.doubleNum();
obj.displayNum(); // Should display 30
return 0;
}
OUTPUT:
Value of num: 30

P-108
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Hierarchical Inheritance
#include <iostream>
using namespace std;

class A {
public:
void displayA() {
cout << "Class A method called." << endl;
}
};

class B : public A {
public:
void displayB() {
cout << "Class B method called." << endl;
}
};

class C : public A {
public:
void displayC() {
cout << "Class C method called." << endl;
}
};

int main() {
B objB;
C objC;

objB.displayA(); // Class B inherits displayA from Class A


objB.displayB();

objC.displayA();
OUTPUT:
Class A method called.
Class B method called.
Class A method called.
Class C method called.

P-109
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Hierarchical Inheritance with Different Data Members
#include <iostream>
using namespace std;

class A {
public:
int baseValue;

void setBaseValue(int val) {


baseValue = val;
}
};

class B : public A {
public:
int derivedValueB;

void setDerivedValueB(int val) {


derivedValueB = val;
}

void display() {
cout << "Base Value: " << baseValue << ", Derived Value in B: " << derivedValueB <<
endl;
}
};

class C : public A {
public:
int derivedValueC;

void setDerivedValueC(int val) {


derivedValueC = val;
}

void display() {
cout << "Base Value: " << baseValue << ", Derived Value in C: " << derivedValueC <<
endl;
}
};

int main() {
B objB;
C objC;

objB.setBaseValue(10);
objB.setDerivedValueB(20);
objB.display();

objC.setBaseValue(30);
objC.setDerivedValueC(40);
objC.display();

return 0;
}
OUTPUT:
Base Value: 10, Derived Value in B: 20
Base Value: 30, Derived Value in C: 40

P-110
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Hierarchical Inheritance with Constructors
#include <iostream>
using namespace std;

class A {
public:
A() {
cout << "Constructor of Class A" << endl;
}
};

class B : public A {
public:
B() {
cout << "Constructor of Class B" << endl;
}
};

class C : public A {
public:
C() {
cout << "Constructor of Class C" << endl;
}
};

int main() {
B objB; // Creates an object of class B
C objC; // Creates an object of class C

return 0;
}
OUTPUT:
Constructor of Class A
Constructor of Class B
Constructor of Class A
Constructor of Class C

P-111
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Hierarchical Inheritance with Common Method
#include <iostream>
using namespace std;

class A {
public:
void show() {
cout << "Common method in Base Class A" << endl;
}
};

class B : public A {
public:
void display() {
cout << "Derived Class B" << endl;
}
};

class C : public A {
public:
void display() {
cout << "Derived Class C" << endl;
}
};

int main() {
B objB;
C objC;

objB.show(); // Calls show method from Class A


objB.display(); // Calls display method from Class B

objC.show(); // Calls show method from Class A


objC.display(); // Calls display method from Class C

return 0;
}
OUTPUT:
Common method in Base Class A
Derived Class B
Common method in Base Class A
Derived Class C

P-112
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Multiple Inheritance
#include <iostream>
using namespace std;

class A {
public:
void showA() {
cout << "Class A method called." << endl;
}
};

class B {
public:
void showB() {
cout << "Class B method called." << endl;
}
};

class C : public A, public B {


public:
void showC() {
cout << "Class C method called." << endl;
}
};

int main() {
C objC;
objC.showA(); // Accessing method from class A
objC.showB(); // Accessing method from class B
objC.showC(); // Accessing method from class C

return 0;
}
OUTPUT:
Class A method called.
Class B method called.
Class C method called.

P-113
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Inheritance with Data Members
#include <iostream>
using namespace std;

class A {
public:
int a;
void setA(int value) {
a = value;
}
};

class B {
public:
int b;
void setB(int value) {
b = value;
}
};

class C : public A, public B {


public:
void display() {
cout << "Value of a: " << a << ", Value of b: " << b << endl;
}
};

int main() {
C objC;
objC.setA(10);
objC.setB(20);
objC.display();

return 0;
}
OUTPUT:
Value of a: 10, Value of b: 20

P-114
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Inheritance with Constructors
#include <iostream>
using namespace std;

class A {
public:
A() {
cout << "Constructor of Class A" << endl;
}
};

class B {
public:
B() {
cout << "Constructor of Class B" << endl;
}
};

class C : public A, public B {


public:
C() {
cout << "Constructor of Class C" << endl;
}
};

int main() {
C objC; // Creates an object of class C

return 0;
}
OUTPUT:
Constructor of Class A
Constructor of Class B
Constructor of Class C

P-115
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Multiple Inheritance with Ambiguity Resolution
#include <iostream>
using namespace std;

class A {
public:
void show() {
cout << "Class A method called." << endl;
}
};

class B {
public:
void show() {
cout << "Class B method called." << endl;
}
};

class C : public A, public B {


public:
void show() {
A::show(); // Resolving ambiguity by specifying the class name
B::show(); // Resolving ambiguity by specifying the class name
}
};

int main() {
C objC;
objC.show(); // Calls both show methods from Class A and Class B

return 0;
}
OUTPUT:
Class A method called.
Class B method called.

P-116
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Hybrid Inheritance
#include <iostream>
using namespace std;

// Base class 1
class A {
public:
void showA() {
cout << "Class A method called." << endl;
}
};

// Base class 2
class B : public A {
public:
void showB() {
cout << "Class B method called." << endl;
}
};

// Derived class from both A and B


class C : public B {
public:
void showC() {
cout << "Class C method called." << endl;
}
};

// Another derived class directly from A


class D : public A {
public:
void showD() {
cout << "Class D method called." << endl;
}
};

int main() {
C objC;
objC.showA(); // Inherited from class A
objC.showB(); // Inherited from class B
objC.showC(); // Method from class C

D objD;
objD.showA(); // Inherited from class A
objD.showD(); // Method from class D
return 0;
}
OUTPUT:
Class A method called.
Class B method called.
Class C method called.
Class A method called.
Class D method called.

P-117
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Multi-path Inheritance
#include <iostream>
using namespace std;

// Grandparent class
class A {
public:
void showA() {
cout << "Class A method called." << endl;
}
};

// Parent class 1
class B : public A {
public:
void showB() {
cout << "Class B method called." << endl;
}
};

// Parent class 2
class C : public A {
public:
void showC() {
cout << "Class C method called." << endl;
}
};

// Derived class
class D : public B, public C {
public:
void showD() {
cout << "Class D method called." << endl;
}
};

int main() {
D objD;
objD.showB();
objD.showC();
objD.showD();

// Ambiguity if we try to call showA() without resolving


// objD.showA(); // This would cause an error

return 0;
}
OUTPUT:
Class B method called.
Class C method called.
Class D method called.

P-118
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Simple Virtual Base Class Example
#include <iostream>
using namespace std;

class Base {
public:
int baseVar;
Base() : baseVar(0) {}
};

class Derived1 : virtual public Base {


public:
void setDerived1(int val) {
baseVar = val;
}
};

class Derived2 : virtual public Base {


public:
void setDerived2(int val) {
baseVar = val;
}
};

class DerivedFinal : public Derived1, public Derived2 {


public:
void display() {
cout << "Final Value of baseVar: " << baseVar << endl;
}
};

int main() {
DerivedFinal obj;
obj.setDerived1(10);
obj.setDerived2(20);
obj.display(); // Output: Final Value of baseVar: 20

return 0;
}
OUTPUT:
Final Value of baseVar: 20

P-119
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Virtual Base Class with Multiple Inheritance
#include <iostream>
using namespace std;

class Base {
public:
int baseVar;
Base() : baseVar(1) {}
void show() {
cout << "Base class variable: " << baseVar << endl;
}
};

class Derived1 : virtual public Base {


public:
void increment() {
baseVar++;
}
};

class Derived2 : virtual public Base {


public:
void decrement() {
baseVar--;
}
};

class DerivedFinal : public Derived1, public Derived2 {


public:
void result() {
show();
}
};

int main() {
DerivedFinal obj;
obj.increment();
obj.decrement();
obj.result(); // Output: Base class variable: 1

return 0;
}
OUTPUT:
Base class variable: 1

P-120
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Abstract Class with Multiple Derived Classes
#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() {
cout << "Drawing Circle" << endl;
}
};

class Square : public Shape {


public:
void draw() {
cout << "Drawing Square" << endl;
}
};

int main() {
Circle c;
Square s;
c.draw();
s.draw();
return 0;
}
OUTPUT:
Drawing Circle
Drawing Square

P-121
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Basic Virtual Function Example
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override {
cout << "Derived class show function" << endl;
}
};

int main() {
Base *bptr;
Derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->show();
return 0;
}
OUTPUT:
Derived class show function

P-122
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to illustrate Virtual Function in Action with Multiple Derived Classes
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived1 : public Base {


public:
void show() override {
cout << "Derived1 class show function" << endl;
}
};

class Derived2 : public Base {


public:
void show() override {
cout << "Derived2 class show function" << endl;
}
};

int main() {
Base *bptr;
Derived1 d1;
Derived2 d2;

bptr = &d1;
bptr->show();

bptr = &d2;
bptr->show();

return 0;
}
OUTPUT:
Derived1 class show function
Derived2 class show function

P-123
PROBLEM SOLVING AND PROGRAMMING USING C++

C++ PROGRAMS ON I/O STREAMS

Program to Demonstrate Unformatted-I/O Functions


#include <iostream.h>
using namespace std;

int main() {
char ch;

// Prompt user to enter a character


cout << "Enter a character: ";

// Read a single character from input using unformatted I/O function


ch = cin.get();

// Display the character using unformatted I/O function


cout << "You entered: ";
cout.put(ch);

// New line for clarity


cout << endl;

return 0;
}
OUTPUT:
Enter a character: A
You entered: A

P-124
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Demonstrate formatted-I/O Functions
#include <iostream>
#include <iomanip> // For manipulators
using namespace std;

int main() {
// Variables
int age = 25;
double height = 175.567;
double weight = 68.12345;

// Output using formatted I/O


cout << "Formatted Output Example:\n";

// Set width and alignment


cout << left << setw(15) << "Age:" << age << endl;
cout << left << setw(15) << "Height (cm):" << fixed << setprecision(2) << height << endl;
cout << left << setw(15) << "Weight (kg):" << fixed << setprecision(2) << weight << endl;

// Input example
int inputAge;
double inputHeight, inputWeight;

cout << "\nEnter your age: ";


cin >> inputAge;

cout << "Enter your height in cm: ";


cin >> inputHeight;

cout << "Enter your weight in kg: ";


cin >> inputWeight;

// Output the input values with formatting


cout << "\nYour Details:\n";
cout << left << setw(15) << "Age:" << inputAge << endl;
cout << left << setw(15) << "Height (cm):"<<fixed <<setprecision(2) << inputHeight << endl;
cout << left << setw(15) << "Weight (kg):"<<fixed <<setprecision(2) << inputWeight << endl;

return 0;
}
OUTPUT:
Formatted Output Example:
Age: 25
Height (cm): 175.57
Weight (kg): 68.12

Enter your age: 30


Enter your height in cm: 180.5
Enter your weight in kg: 75.0

Your Details:
Age: 30
Height (cm): 180.50
Weight (kg): 75.00

P-125
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Demonstrate Built In Classes For I/O
#include <iostream>
#include <string>
using namespace std;

int main() {
// Create instances of built-in I/O classes
ostream& out = cout; // 'cout' is an instance of the 'ostream' class
istream& in = cin; // 'cin' is an instance of the 'istream' class

// Using 'ostream' class to output data


out << "Demonstrating built-in I/O classes in C++:" << endl;

// Variables to store user input


string name;
int age;
double height;

// Using 'istream' class to input data


out << "Enter your name: ";
getline(in, name); // Read a line of text (name)

out << "Enter your age: ";


in >> age; // Read integer value (age)

out << "Enter your height in cm: ";


in >> height; // Read double value (height)

// Output the collected data


out << "\nYour Details:" << endl;
out << "Name: " << name << endl;
out << "Age: " << age << endl;
out << "Height: " << height << " cm" << endl;

return 0;
}
OUTPUT:
Demonstrating built-in I/O classes in C++:
Enter your name: Alice
Enter your age: 25
Enter your height in cm: 165.5

Your Details:
Name: Alice
Age: 25
Height: 165.5 cm

P-126
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Demonstrate ios Class Functions And Flags
#include <iostream>
#include <iomanip> // For manipulating I/O formatting
using namespace std;

int main() {
// Use the ios class functions and flags to format output

// Setting precision and format for floating-point numbers


double pi = 3.14159265358979323846;

// Default output
cout << "Default precision: " << pi << endl;

// Set precision to 2 decimal places


cout << fixed << setprecision(2);
cout << "Fixed precision (2 decimal places): " << pi << endl;

// Set precision to 5 decimal places


cout << setprecision(5);
cout << "Fixed precision (5 decimal places): " << pi << endl;

// Reset to default precision


cout.unsetf(ios::fixed); // Unset fixed flag
cout << setprecision(6); // Reset to default precision (6 is default)
cout << "Default precision (after unset): " << pi << endl;

// Set field width and alignment


int number = 42;

// Set field width to 10 and align to right


cout << setw(10) << right << number << endl;

// Set field width to 10 and align to left


cout << setw(10) << left << number << endl;

// Reset field width


cout << setw(0); // Reset to default field width

// Demonstrating scientific notation


cout << scientific;
cout << "Scientific notation: " << pi << endl;

// Reset to default notation


cout.unsetf(ios::scientific); // Unset scientific flag
cout << "Default notation: " << pi << endl;

return 0;
}
OUTPUT:
Default precision: 3.14159
Fixed precision (2 decimal places): 3.14
Fixed precision (5 decimal places): 3.14159
Default precision (after unset): 3.14159
42
42
Scientific notation: 3.141593e+00
Default notation: 3.14159

P-127
PROBLEM SOLVING AND PROGRAMMING USING C++
Program to Demonstrate File Stream-Classes
#include <iostream>
#include <fstream> // Include for file stream classes
#include <string>
using namespace std;

int main() {
// File names
const string filename = "example.txt";

// Writing to a file using ofstream


ofstream outFile(filename);

if (!outFile) {
cerr << "Error opening file for writing!" << endl;
return 1;
}

outFile << "Hello, File Stream!" << endl;


outFile << "This is a demonstration of file streams in C++." << endl;

outFile.close(); // Close the file after writing

// Reading from a file using ifstream


ifstream inFile(filename);

if (!inFile) {
cerr << "Error opening file for reading!" << endl;
return 1;
}

string line;
cout << "Contents of the file:" << endl;

while (getline(inFile, line)) {


cout << line << endl;
}

inFile.close(); // Close the file after reading

return 0;
}
OUTPUT:
Contents of the file:
Hello, File Stream!
This is a demonstration of file streams in C++.

P-128

You might also like