1: Problem Solving, Algorithm & Flowchart
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) 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.
INTRODUCTION TO C++
2-1
PROBLEM SOLVING AND PROGRAMMING USING C++
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
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:
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;
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++
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)
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
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
• 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
int main() {
return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1
!0 : 1
int main() {
int a = 9, b = 4, c;
c = a + b;
cout << "a+b=" << c << endl;
return 0;
}
Output:
a+b=13
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
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
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
int main() {
int a = 1, b = 2, c = 3;
// 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
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
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
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
int main() {
int localVar = 50; // Local variable
return 0;
}
Output:
Global-variable: 100
Local variable: 50
Accessing globalVar: 100
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
int main() {
cout << "7 && 0 : " << (7 && 0) << endl;
cout << "7 || 0 : " << (7 || 0) << endl;
return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1
Precedence Table
int main() {
int result = 10 - 5 + 3; // Left-associative operators: subtraction and addition
return 0;
}
Output:
Result: 8
int main() {
int a = 5;
double b = 10.5;
double result = a + b; // Implicit conversion of 'a' to double before addition
return 0;
}
Output:
Result: 15.5
return 0;
}
Output:
b = 11
c = 22
d = 0.5
CONTROL STRUCTURES
4-1
PROBLEM SOLVING AND PROGRAMMING USING C++
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:
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:
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:
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;
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:
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:
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:
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:
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);
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:
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
FUNCTION
5-1
PROBLEM SOLVING AND PROGRAMMING USING C++
CHAPTER 5: FUNCTION
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.
FUNCTION
5-3
PROBLEM SOLVING AND PROGRAMMING USING C++
5.4 STRUCTURE OF USER-DEFINED-FUNCTIONS
#include <iostream> // C++ standard input/output library
int main()
{
...........
...........
function_name(); // function-call
...........
...........
}
FUNCTION
5-4
PROBLEM SOLVING AND PROGRAMMING USING C++
• Program to print a sentence using function
#include <iostream>
using namespace std;
int main() {
display(); // Function-call
return 0;
}
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;
int main() {
// Call the function without specifying width and height (default-values used)
int default_area = calculate_rectangle_area();
// 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
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
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
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.
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.
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;
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'
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;
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;
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;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
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;
// MyClass definition
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}
// 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
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++
int main() {
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
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
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.
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
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
int main() {
int age[5], i;
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
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:
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
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
int main() {
int matrix[2][2], i, j;
return 0;
}
int main() {
int c[3] = {2, 3, 4};
display(c[2]); // Passing array element c[2] only.
return 0;
}
Output:
4
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
int main() {
// Reading a string from user input
string input;
cout << "Enter a string: ";
getline(cin, input); // reads entire line, including spaces
return 0;
}
Output:
Enter a string: rama
You entered: rama
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
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!"
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
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:
• 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.
• Here, the statement initializes p1 with name "rama", cit_no 24, and salary 23000.
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
// 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;
int main() {
// Initialize an array of structures
Person people[3] = {
{"Arjuna", 1, 88000},
{"Krishna", 2, 92000},
{"Bhima", 3, 79000}
};
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
union Person {
string name;
int cit_no;
float salary;
};
int main() {
// Initialize the Union
Person p1;
// Print salary
cout << "Initial salary: " << p1.salary << endl;
return 0;
}
Output:
Initial salary: 23000
Enter new salary: 35000
Updated salary: 35000
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
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
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
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;
POINTERS
8-5
PROBLEM SOLVING AND PROGRAMMING USING C++
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.
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.
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
};
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) {
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
"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;
};
// Class definition
class Rectangle {
public:
int length;
int width;
static int rectangleCount; // Static data-member
// 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
}
int main() {
// Create instances of the Rectangle class
Rectangle rect1(5, 10);
Rectangle rect2(7, 14);
Rectangle rect3(6, 12);
return 0;
}
Output:
Rectangle 1 - Area: 50
Rectangle 2 - Area: 98
Rectangle 3 - Area: 72
No of Rectangles: 3
// Class definition
class Rectangle {
public:
double length;
double width;
int main() {
Rectangle rects[3]; // Array of 3 Rectangle objects
rects[1].length = 6.0;
rects[1].width = 3.0;
rects[2].length = 5.0;
rects[2].width = 5.0;
return 0;
}
Output:
Rectangle 1 Area: 8
Rectangle 2 Area: 18
Rectangle 3 Area: 25
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
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
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;
}
// 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
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
}
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
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;
}
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
// Constructor
Rectangle(int l, int w) {
length = l;
width = w;
cout << "Rectangle is created << endl;
}
// Destructor
~Rectangle() {
cout << "Rectangle is destroyed" << endl;
}
int main() {
// Creating an object of Rectangle class
Rectangle rect(10, 5);
OPERATOR OVERLOADING
11-1
PROBLEM SOLVING AND PROGRAMMING USING C++
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.
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);
}
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);
OPERATOR OVERLOADING
11-6
PROBLEM SOLVING AND PROGRAMMING USING C++
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++
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
};
INHERITANCE
12-2
PROBLEM SOLVING AND PROGRAMMING USING C++
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.
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.
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
};
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.
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
};
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.
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
};
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;
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.
class BaseClass2 {
// Base-class 2 members
};
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;
}
};
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.
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;
}
};
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.
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;
}
};
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.
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
INHERITANCE
12-21
PROBLEM SOLVING AND PROGRAMMING USING C++
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
int main() {
// Create objects of derived classes
Circle myCircle(5.0);
Rectangle myRectangle(4.0, 6.0);
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.
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
}
};
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>
// Base class
class Shape {
public:
// Virtual function for drawing the shape
virtual void draw() {
cout << "Drawing a shape." << 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.
INHERITANCE
12-26
PROBLEM SOLVING AND PROGRAMMING USING C++
I/O STREAMS
13-1
PROBLEM SOLVING AND PROGRAMMING USING C++
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:
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
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
int main() {
// Setting precision to 3 digits after the decimal point
cout << setprecision(3) << 3.14159 << endl; // Outputs: 3.14
// 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.
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
// Using flags
cout << "Hexadecimal and octal outputs:" << 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).
I/O STREAMS
13-11
PROBLEM SOLVING AND PROGRAMMING USING C++
FILE HANDLING
14-1
PROBLEM SOLVING AND PROGRAMMING USING C++
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>
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;
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:
`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
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
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;
}
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;
}
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++
int main() {
cout << "C++ Programming" << endl; // Displays the content inside quotation
return 0;
}
OUTPUT:
C++ Programming
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
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;
return 0;
}
OUTPUT:
Enter the first integer: 10
Enter the second integer: 20
average = 15.0
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
int main() {
int length, breadth, area, perimeter;
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
int main() {
float base, height, area;
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;
return 0;
}
OUTPUT:
Enter the side length of the cube: 4
The volume of the cube is: 64
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;
return 0;
}
OUTPUT:
Enter principal amount: 1000
Enter annual interest rate (in percentage): 5
Enter time (in years): 2
Compound Interest: 102.50
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;
return 0;
}
OUTPUT:
Enter distance in kilometers: 10
10 kilometers is equal to 6.21371 miles.
int main() {
float celsius, fahrenheit;
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
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;
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
int main() {
int a = 10;
int b = 5;
int c = 2;
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;
return 0;
}
OUTPUT:
intValue = 10
doubleValue = 5.5
Result (int + double): 15.5
int main() {
double doubleValue = 9.8;
int intValue;
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++
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
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
int main() {
int num;
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;
return 0;
}
OUTPUT:
Enter a character: 2
2 is not an alphabet.
int main() {
char ch;
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;
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;
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;
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;
int main() {
float a, b, c, determinant, r1, r2, real, imag;
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++
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
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
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
int main() {
int num = 1, sum = 0;
while (num <= 50) {
sum += num;
++num;
}
cout << "Sum = " << sum << endl;
return 0;
}
OUTPUT:
Sum = 1275
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
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
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
int main() {
int i = 5;
while (i >= 1) {
cout << i << " ";
i--;
}
cout << endl;
return 0;
}
OUTPUT:
5 4 3 2 1
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
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;
}
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;
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;
}
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;
int main() {
char str[100], reversedStr[100];
int length;
length = strlen(str);
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;
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
int main() {
int rows = 4, cols = 6;
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;
return 0;
}
OUTPUT:
*
* *
* * *
* * * *
* * * * *
int main() {
int height = 5;
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;
return 0;
}
OUTPUT:
First number greater than 10 is 11
int main() {
int num = 29;
bool isPrime = true;
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.
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
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++
int main() {
int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;
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];
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;
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;
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;
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;
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;
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;
low = 0;
high = num - 1;
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;
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
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;
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];
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;
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++
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
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 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
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>
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
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:
P-55
PROBLEM SOLVING AND PROGRAMMING USING C++
PROGRAM TO PERFORM BINARY SEARCH USING RECURSION
#include <iostream.h>
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;
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;
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
// 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++
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
Student s;
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;
};
int main() {
Complex n1, n2, temp;
return 0;
}
OUTPUT:
For 1st complex number
Enter real and imaginary respectively:
2.3 4.5
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];
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
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;
// 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
int main() {
// Create a union variable
EmployeeData employee;
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++
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;
}
int main() {
Rectangle rect1, rect2; // Create two Rectangle objects
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;
}
int main() {
Student student1, student2; // Create two Student objects
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++;
}
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;
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;
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) {}
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) {}
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) {}
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) {}
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;
}
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++
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
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
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
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;
}
int main() {
Point p1(3, 4); // Create object using parameterized constructor
Point p2(p1); // Create object using copy constructor
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;
}
int main() {
Student s1("Alice", 20); // Create object using parameterized constructor
Student s2(s1); // Create object using copy constructor
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 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);
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;
}
int main() {
Circle c1(7.5); // Create object using parameterized constructor
Circle c2(c1); // Create object using copy constructor
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
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
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
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;
}
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;
}
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++
class Counter {
private:
int value;
public:
Counter(int v = 0) : value(v) {}
int main() {
Counter c(5);
cout << "Original Value: ";
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) {}
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) {}
int main() {
Boolean b1(true);
cout << "Original Value: ";
b1.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) {}
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) {}
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) {}
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++
class Base {
public:
void showBase() {
cout << "Base 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;
}
};
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;
}
};
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;
}
};
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;
}
};
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;
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;
class B : public A {
public:
int derivedValueB;
void display() {
cout << "Base Value: " << baseValue << ", Derived Value in B: " << derivedValueB <<
endl;
}
};
class C : public A {
public:
int derivedValueC;
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;
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;
}
};
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;
}
};
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;
}
};
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;
}
};
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;
}
};
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();
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) {}
};
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;
}
};
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
};
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;
}
};
int main() {
Base *bptr;
Derived d;
bptr = &d;
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;
}
};
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++
int main() {
char ch;
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;
// Input example
int inputAge;
double inputHeight, inputWeight;
return 0;
}
OUTPUT:
Formatted Output Example:
Age: 25
Height (cm): 175.57
Weight (kg): 68.12
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
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
// Default output
cout << "Default precision: " << 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";
if (!outFile) {
cerr << "Error opening file for writing!" << endl;
return 1;
}
if (!inFile) {
cerr << "Error opening file for reading!" << endl;
return 1;
}
string line;
cout << "Contents of the file:" << endl;
return 0;
}
OUTPUT:
Contents of the file:
Hello, File Stream!
This is a demonstration of file streams in C++.
P-128