PROBLEM SOLVING USING C++
C++ is a high-performance, compiled, general-purpose programming language developed by
Bjarne Stroustrup in 1979 as an extension of the C programming language. It is widely celebrated
for giving programmers fine-grained control over system resources and memory. Because of its
execution speed, it is the industry standard for building operating systems, game engines, high-
frequency trading applications, and embedded software.
What is C++?
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 5 major times in 2011, 2014, 2017, 2020, and 2023 to C++11, C++14,
C++17, C++20, and C++23.
Why Use C++
C++ is one of the world's most popular programming languages.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
C++ is fun and easy to learn!
As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa.
Difference between C and C++
C++ was developed as an extension of C, and both languages have almost the same syntax.
The main difference between C and C++ is that C++ supports classes and objects, while C does not.
Example
#include <iostream>
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
#include <iostream>: A preprocessor directive that imports the Standard Input/Output Stream
library. This library allows the program to read data from the keyboard or print text to the screen.
int main(): The starting point (entry point) of every C++ program. Execution always begins
here.
std::cout: Represents "character output". The << operator inserts the text sequence into the
output stream to show it on your monitor.
std::endl: Ends the line and flushes the output buffer. Alternatively, using "\n" achieves a faster
newline insertion.
return 0;: Concludes the main function, signaling to the operating system that the software
executed successfully.
Semicolons ;: Must cap the end of every individual statement or command.
Flow Control
Control structures dictate how code routes behave based on logic conditions. [1, 2]
Conditionals (if / else): Chooses execution branches based on a truth criteria.
Loops (for / while): Runs a block of code multiple times consecutivel
if (age >= 18) {
std::cout << "Adult" << std::endl;
} else {
std::cout << "Minor" << std::endl;
}
for (int i = 0; i < 5; i++) {
std::cout << i << " "; // Prints: 0 1 2 3 4
}
UNIT - I
Introduction: Steps Involved in Problem Solving Using Computers – Characteristics of
Algorithms- Symbols Used in Flow Charts - Pseudocode: Sequence, Selection andIteration -
Principles of Object-Oriented Programming: Basic Concepts of Object-Oriented
Programming-Benefits of OOP- Applications of OOP - Beginning with C++: Simple C++
Program-Structure of C++ Program- Tokens, Expressions and Control
Structures:Introduction - Tokens- Keywords - Identifiers and Constants - Basic Data Types –
User Defined Data Types - Derived Data Types -Symbolic Constants Problem Solving Using
Computers.
Problem Solving Using Computers
Computers solve complex problems through a structured, multi-step process to ensure accuracy and
efficiency.
Steps Involved in Problem Solving
Problem Definition: Clear statement of the problem and its requirements.
Analysis: Identifying inputs, required outputs, and processing constraints.
Design: Creating a logical plan using algorithms or flowcharts.
Coding: Translating the design into a specific programming language.
Testing & Debugging: Running the program to find and fix errors.
Documentation: Writing user manuals and technical guides for maintenance.
Maintenance: Updating the software to meet chang ing requirements.
ALGORITHM
Algorithm is a set of finite, well-defined steps or instructions designed to solve a problem or
perform a computation. It can also be defined as a procedure for solving a mathematical or
computational problem in a finite number of steps, often involving repetitive or recursive
operations.
Need for Algorithms:
Solve complex problems efficiently and effectively.
Automate processes, making them reliable, faster, and easier.
Enable computers to perform tasks difficult or impossible for humans.
Widely used in mathematics, computer science, engineering, finance, and data analysis.
Characteristics of Algorithms
An algorithm is a set of step-by-step instructions to solve a problem. Every good algorithm must
have these traits:
Finiteness: It must terminate after a limited number of steps.
Definiteness: Each step must be clear and unambiguous.
Input: It must accept zero or more well-defined inputs.
Output: It must produce at least one desired result.
Effectiveness: Every step must be basic enough to be doable.
Standard Flowchart Symbols
Flowcharts use standard geometric shapes to visually map out an algorithm.
Terminal (Oval): Marks the start or end of a program.
Input/Output (Parallelogram): Indicates reading data or printing results.
Process (Rectangle): Represents calculations, data manipulation, or variable assignments.
Decision (Diamond): Shows a conditional test (Yes/No or True/False) that splits the path.
Connectors (Circles): Links different points or pages of a complex chart.
Flow Lines (Arrows): Displays the exact direction of the process flow.
Flowchart Symbols Mapping to C++
C++ Language
Symbol Shape Symbol Name Purpose
Equivalent
Oval / Rounded Marks the beginning and end of the
Terminal main() start / return 0;
Rectangle program logic.
Input / Handles data entry or displaying
Parallelogram cin >> / cout <<
Output results to the console.
Used for declarations (int x;),
Variables, math
Rectangle Process calculations, and expressions (x = a
operations, assignments
+ b;).
if, else if, else, switch Evaluates a condition to branch the
Diamond Decision
cases flow into True/False paths.
Double-Border Predefined Function calls Indicates a call to a separate block
Rectangle Process (myFunction();) of code or user-defined function.
Connects different parts of a
On-Page
Circle Jump points complex flowchart on the same
Connector
page.
Sequence of code Shows the direction and order in
Arrow Line Flowline
execution which instructions execute.
Pseudocode
Pseudocode acts as a human-readable bridge for designing algorithms before writing actual code. It
uses three fundamental building blocks to control program logic: Sequence (execution order),
Selection (decisions), and Iteration (repetition). These constructs form the foundation of structured
and object-oriented programming
1. The Three Fundamental Constructs of Logic
Sequence: The linear, step-by-step execution of instructions from top to bottom. The computer
finishes one instruction completely before moving to the next. [1, 2, 3, 4]
Selection: The decision-making construct. It allows the program to choose different paths of
execution based on a condition (evaluating to True or False). [1, 2, 3, 4, 5]
Iteration: The looping or repetition construct. It tells the program to execute a specific block of
code multiple times until a certain condition is met or a specific count is reached.
.
[Link] Implementation & Examples
Pseudocode & Logic Structures
Sequence
Executes statements sequentially, one after another, in the exact order written. [1, 2]
Example:
text
INPUT length
INPUT width
SET area = length * width
OUTPUT area
Use code with caution.
Selection
Makes decisions by evaluating a condition and branching the execution path (e.g., IF-ELSE).
Example:
text
IF score >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Use code with caution.
Iteration
Repeats a block of code multiple times using loops (e.g., WHILE, FOR). [1, 2, 3]
Example:
text
SET count = 1
WHILE count <= 5
OUTPUT count
SET count = count + 1
ENDWHILE
3. Application in Object-Oriented Programming (OOP)
While sequence, selection, and iteration define the basic logic flow of any program, Object-
Oriented Programming (OOP) combines these elements into self-contained "objects" to manage
complex software. [1, 2, 3, 4]
Objects and Classes: OOP focuses on creating "classes" (blueprints) and "objects" (instances of
those classes). The internal methods of these objects are simply algorithms built using Sequence,
Selection, and Iteration. [1, 2, 3, 4, 5]
Encapsulation: Combining data and functions into a single unit. It hides the internal state from the
outside world. Inside these encapsulated methods, sequence and selection control how internal data
is accessed or modified. [1, 2, 3, 4]
Inheritance and Polymorphism: Object behaviors can be dynamically selected or overridden at
runtime, using selection logic (like switch/case or dynamic binding). [1, 2, 3, 4, 5]
For additional structured programming principles, refer to the detailed resources on Scribd or the
analysis on ResearchGate. [1, 2]
If you want to test your understanding, let me know if you would like to:
See a practical example of how these three constructs are applied to a specific OOP project (like a
banking or shopping system).
Practice converting a pseudocode problem into Object-Oriented Java or C++ code.
Principles of Object-Oriented Programming (OOP)
Basic Concepts of OOP
Objects: Runtime entities containing data and code that manipulates that data.
Classes: User-defined blueprints or data types used to create objects.
Encapsulation: Wrapping data and functions into a single unit to restrict direct access.
Data Hiding: Isolating data from direct access by external code for security.
Abstraction: Displaying only essential features while hiding background details.
Inheritance: Mechanism where a new class acquires properties of an existing class.
Polymorphism: Ability of a function or operator to take multiple forms.
Dynamic Binding: Linking a function call to its executable code at runtime.
Message Passing: Process where objects communicate by sending and receiving data.
Benefits of OOP
Eliminates redundant code through inheritance.
Ensures high data security via encapsulation.
Simplifies complex software maintenance and upgrades.
Allows easy partitioning of work in projects.
Applications of OOP
Real-time systems.
Simulation and modeling software.
Object-oriented database systems.
Hypertext and expert systems.
Beginning with C++
Simple C++ Program
A basic program prints a single line of text to the console screen.
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Structure of a C++ Program
C++ programs follow a rigid structural organization containing distinct sections.
Section Purpose Example
Imports standard libraries for input/output
Include Header Files #include <iostream>
functions.
using namespace
Namespace Declaration Grouping system to prevent naming conflicts.
std;
Main Function The explicit entry point where code execution int main() { ... }
Boundary begins.
Execution Statements Internal instructions that perform program actions. cout << "Hi";
Terminates the main function and sends a status
Return Statement return 0;
code.
Tokens, Expressions, and Control Structures
Tokens are the smallest meaningful units, Expressions are combinations of these tokens evaluated
to produce a value, and Control Structures dictate the sequential flow of your logic.
1. Tokens
Tokens are the basic building blocks that the compiler understands. Every program is simply a
collection of tokens.
Keywords: Reserved words that have predefined meanings in the language (e.g., int, if, while).
Identifiers: User-defined names given to variables, functions, and arrays (e.g., totalSum, userAge).
Constants & Literals: Fixed values that do not change (e.g., 10, 3.14, "Hello").
Operators: Symbols used to perform operations on data (e.g., +, -, ==, &&).
Special Symbols: Punctuation used to format code, like semicolons (;) to end statements, or braces
({}) to group code blocks.
Keywords Identifiers Constants Strings Operators
2. Expressions
An expression is a combination of variables, constants, and operators that the programming
language evaluates to yield a single result.
Arithmetic Expressions: Evaluate to numerical values, e.g., a + b × 2.
Relational Expressions: Evaluate to true or false, e.g., x > y.
Logical Expressions: Evaluate the combination of multiple conditions, e.g., \((a > b) \lor (x > y)\).
3. Control Structures
Control structures dictate the order in which instructions are executed in your code.
Sequence: Code runs line-by-line, in the order it is written.
Selection (Decision Making): Allows the program to execute different blocks of code based on a
condition, e.g., if, if-else, or switch statements.
Iteration (Loops): Repeats a block of code while or until a certain condition is met (e.g., for,
while, and do-while loops).
Introduction to Tokens
Tokens represent the smallest individual element of a program that a compiler recognizes.
Keywords
System-reserved words that carry a fixed, unalterable meaning to the compiler.
Example: int, float, class, if, while, return.
Identifiers
User-defined names assigned to variables, functions, arrays, or classes.
Example: int age; (where age acts as the identifier).
Constants
Fixed values that remain entirely unchanged throughout the program lifespan. [1, 2]
Example: const int MAX_SPEED = 100;
Basic Data Types
Built-in or primitive types that handle standard foundational values.
Example: int (integer), float (decimal), char (character), bool (boolean).
User-Defined Data Types
Custom types created by the programmer to model complex structures.
Example: struct, union, class, enum.
struct Student {
int rollNumber;
float marks;
};
Derived Data Types
Types built directly by extending or combining the basic data types. [1, 2, 3]
Example: Arrays, pointers, references, functions.
int grades[5]; // Array derived from integer type
int* ptr; // Pointer derived from integer type
Symbolic Constants
Names assigned to unique values that never alter during execution, declared via const or #define.
A symbolic constant is a meaningful name or identifier that substitutes for a fixed value or literal in
a program. Instead of hard-coding raw values (often called "magic numbers") directly into code,
developers assign descriptive names to them, which dramatically improves code readability, safety,
and maintainability.
Example:
#define PI 3.14159
// OR
const double TAX_RATE = 0.05;
. They are classified into four primary types: integer, floating-point (or real), character, and
string constants
1. Integer Constants
These are whole numbers consisting of a sequence of digits without any decimal point. They can be
positive, negative, or zero.
Decimal: Base-10 numbers using digits 0–9 (e.g., 10, -25, 0).
Octal: Base-8 numbers preceded by a 0 (e.g., 035).
Hexadecimal: Base-16 numbers preceded by 0x or 0X (e.g., 0x2A).
Starter tutorials
2. Floating-Point (Real) Constants
These are numerical constants that contain a decimal point or an exponential component
. They are used to represent numbers with fractional parts.
Example: 3.14, -0.005, 1.5e2 (which translates to 1.5 × 10²).
3. Character Constants
These represent a single character enclosed within single quotation marks. They usually take up one
byte of memory.
Example: 'A', 'z', '9', '$'.
4. String Constants
These consist of a sequence of characters enclosed within double quotation marks. They are stored
as an array of characters, automatically ending with a null terminator (\0).
YouTube·Ekeeda +4
Example: "Hello World", "1234".