0% found this document useful (0 votes)
11 views36 pages

Problem Solving with Algorithms & Flowcharts

The document outlines problem-solving steps, including defining a problem, designing a solution using flowcharts, and writing pseudocode. It explains algorithms as structured methods for solving problems and discusses various operators in C++. Additionally, it emphasizes the importance of clarity, simplicity, and effectiveness in algorithms and provides examples of pseudocode and C++ programs.

Uploaded by

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

Problem Solving with Algorithms & Flowcharts

The document outlines problem-solving steps, including defining a problem, designing a solution using flowcharts, and writing pseudocode. It explains algorithms as structured methods for solving problems and discusses various operators in C++. Additionally, it emphasizes the importance of clarity, simplicity, and effectiveness in algorithms and provides examples of pseudocode and C++ programs.

Uploaded by

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

Problem

Understand the problem (1st step)


Steps in Problem solving
1. Define the Problem
2. Design the Solution
[Link] the problem
After careful reading, the problem statement should be divided into three separate
components

 Input
What data will be provided to the solution
 Output
What is required from the solution
 Processing
List of actions needed to produce the required output

2. Design the solution

 There are more than one ways to do this


 We will use a graphical approach
 Involves the usage of geometrical shapes
Flowchart (Designing the Solution)

 A flowchart is a graphical representation of an algorithm that shows the flow of logic in a


step-by-step manner.
It uses symbols and arrows to represent the sequence of operations in a program.
 Why Use Flowcharts?
Helps visualize complex processes.
Makes it easier to debug and refine logic.
Language-independent—focuses on logic rather than syntax.
 Key Features of a Flowchart
Uses standard symbols for easy understanding.
Represents logic in a structured way.
Clearly defines input, processing, and output.
Symbol Name Function
⭕ Oval Terminator Start or End
▭ Rectangle Process Task or Activity
◆ Diamond Decision Branch based on Yes/No or conditions
⬒ Parallelogram Input/Output Input to or Output from a process
● Circle Connector Connect flowchart elements across distances
� Wavy doc Document Represents a document generated

We have to find sum of two numbers


How can we solve this problem???

Step 1: define the problem


Problem: Find the sum of two numbers

INPUT OUTPUT PROCESSING


Number1 Sum Add two numbers
Number2

Step 2: design the solution

 Start by drawing a “Start” symbol


 Show a symbol for Input
 Show process symbol(s) for processing
There can be more than 1 such steps depending on the complexity of the problem
 Show a symbol for Output
 Finish by drawing a “Stop “ symbol.
SOME OTHER PROBLEMS

• Find sum of three numbers


• Find Average of two numbers
• Find square of a number
• Find acceleration for a given velocity and time
• Find Velocity form given D1, D2, T1, T2
• Where, velocity = change in distance /
change in time
• Division, multiplication, subtraction of two/three
numbers

Sum of three

numbers
An Important Observaion
In the expression,
sum = sum + num3
‘num3’ is added to the value of ‘sum’ and the new value is than assigned to ‘sum’
In other words, the expression at right of the assignment is evaluated first than the value is
assigned to the variable at left
We will further explore this kind of expressions when we will study a particular computer

language.

Average of two numbers


Square of a number

Acceleration
Velocity

Value of F
Power of computers
Computers can do many complicated tasks at very high speeds and can store
large quantities of data
Some Situations
Extensive Input
Extensive output
Method of solution is too complicated to implement manually
If done manually, it takes an excessive long time to solve
What is Pseudocode?
Pseudocode is a simplified way of writing algorithms using plain, structured
English.
It bridges the gap between human language and programming language,
making it easier for programmers to plan logic before coding.
Why Use Pseudocode?
Focuses on logic, not syntax.
Easy to understand and modify.
Helps in translating ideas into actual code.
Pseudocode - Example
Pseudocode that describes the pay-calculating program:
Get payroll data.
Calculate gross pay.
Display gross pay.
Although the pseudocode above gives a broad view of the program, it
doesn’t reveal all the program’s details.
Write a pseudocode to calculate
The area of a circle -> πr2
(here radius is already given, and its unit is centimeter).
Algorithm
Just like a recipe needs clear step-by-step instructions to ensure consistency, a
computer program also needs a well-defined set of steps to solve a problem. This
structured set of steps is called an algorithm!
What is an Algorithm?
An algorithm ensuring that a task is completed correctly and efficiently is a step-
by-step set of operations designed to solve a specific problem or a class of
problems.
It provides a structured and logical approach to problem-solving,.
Key Characteristics of an Algorithm
Well-Defined Steps – Each step must be clear and unambiguous.
Finite Execution – An algorithm must have a definite number of steps.
Produces Output – It must provide a correct and expected result.
Effective & Efficient – It should solve the problem in an optimal way.

An algorithm to change a numeric exam result to a letter grade


Input One number
if the number is between 70 and 100 then
Set the grade to “A”
if the number is between 50 and 69 then
Set the grade to “B”
if the number is between 40 and 59 then
Set the grade to “C”
Return Grade
End
Pseudocode VS algorithm
Pseudocode VS algorithm

Expressions
An expression is a combination of variables, constants, operators, and
functions that produce a value.
Example: int x = 5 + 3; (Expression: 5 + 3 evaluates to 8)
An expression includes operators and operands.
Example: 5 + 3; (here 5 and 3 are operands and + is an operator)

Arithmetic Operators
Perform mathematical operations.
Operators:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
Operator Precedence:
*, /, % have higher precedence than + and -, and operations are evaluated from left to right.
Example: 6 + 2 * 3 / 6
→ 6 + (6 / 6)
→6+1
→7

Assignment Operators
Used to assign values to variables.
Operators:
= (Assignment)
+= (Add and Assign)
-= (Subtract and Assign)
*= (Multiply and Assign)
/= (Divide and Assign)
%= (Modulus and Assign)

Comparison Operators
Used to compare two values.
Operators:
== (Equal)
!= (Not Equal)
> (Greater)
< (Lesser)
>= (Greater or Equal)
<= (Lesser or Equal)
Logical Operators

Week 2(Algorithm,Pseudocode,Flowcharts)
What is an Algorithm?
 Step-by-step instructions to solve a problem
 Must be clear, finite, and effective
Why Algorithms?

 Help us think before coding


 Avoid errors in program design
 Provide a structured problem-solving approach
Characteristics of Good Algorithms
• Clarity and simplicity
• Finite steps
• Well-defined inputs and outputs
• Effectiveness
Algorithm to Find Largest of Two Numbers
1. Start
2. Input A and B
3. If A > B, print A is largest
4. Else, print B is largest
5. End
From Algorithm to Code
Steps:
1. Algorithm (words)
2. Pseudocode (structured steps)
3. Flowchart (diagram)
4. Program (C++ code)
What is Pseudocode?
 A way of writing algorithms in structured plain English
 Not actual code
 Easy to convert to programming language
 Pseudocode is a bridge
between English and
programming

Rules of Pseudocode
Use simple English
• One instruction per line
• Use keywords like INPUT, OUTPUT, CALCULATE
• Indent for clarity
Pseudocode - Example

• Pseudocode that describes the pay-calculating program:


1. Get payroll data.
2. Calculate gross pay.
3. Display gross pay.
• Although the pseudocode above gives a broad view of the program, it doesn’t reveal all
the program’s details.
Example Pseudocode: Average of 3 Numbers
1. INPUT A, B, C
2. CALCULATE Avg = (A + B + C) / 3
3. OUTPUT Avg
4. END
What is a Flowchart?
• Visual representation of algorithm
• Uses standard symbols
• Easier to understand for beginners

Flowchart Symbols
Flowchart Example: Average of 3 Numbers

The Last step: CODE/PROGRAM


In C++, "code" or a "program" refers to a set of instructions written in the C++ programming
language that a computer can understand and execute to perform a specific task.
SYNTAX
C++ syntax refers to the set of rules that define how a C++ program is written and
structured.
Fundamental elements of C++ syntax
Header Files:
These files, included using #include, provide access to predefined functionalities and
libraries. For example, #include <iostream> is used for input/output operations.

Namespaces:
Namespaces organize code into logical groups to prevent naming conflicts. The using
namespace std; statement allows direct use of elements from the standard namespace
without prefixing them with std::.

Main Function:
Every C++ program must have a main() function, which serves as the entry point for
program execution.
int main()
{
}

C++ Program: Average of 3 Numbers


#include <iostream>
using namespace std;
int main(){
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
float avg = (a+b+c)/3.0;
cout << "Average = " << avg;
return 0;
}
Program Output Example
Input:
10 20 30

Output:
Average = 20

Common Mistakes
Forgetting Start/End symbols in flowcharts
Not initializing variables in pseudocode
Skipping calculation steps

Summary
• Algorithms are step-by-step methods
• Pseudocode is structured plain English
• Flowcharts are visual representations
• C++ programs implement algorithms

Class Activity
Write pseudocode and flowchart for finding the sum of 5 and 8.

Lab Tasks
1. Write pseudocode, flowchart and C++ code to Check if a number is even or odd.
(Hint: Use modulus operator % in C++)
2. Write an algorithm to calculate the sum of two numbers entered by the user. Write the
pseudocode and draw the flowchart.
Implement in C++ using cin and cout.

Operators & Expressions in C++(week 4)


Comments in C++
Comments are notes inside code that explain what the program does.
- Ignored by compiler (not executed)
- Help programmers understand the logic
- Useful for documentation and debugging
Types:
1. Single-line: // comment
2. Multi-line: /* comment */
Example Program
#include <iostream>
using namespace std;
int main()
{
int a = 5; // This is a single-line comment

/* Multi-line comment example


This adds 10 to a */

a = a + 10;
cout << a; // Output: 15
return 0;
}

What are Operators?


Operators are special symbols that tell the computer to perform certain operations on
variables and values.
For example: + for addition, * for multiplication.
Why Operators are Important?

Operators are the building blocks of programs.


They allow us to perform:
calculations,
make decisions, and
write logical code easily.

Types of Operators in C++


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment/Decrement Operators
6. Conditional Operator
7. Other Special Operators

1. Arithmetic Operators
Used for mathematical calculations:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Program: Arithmetic Operators

#include <iostream>
using namespace std;
int main()
{
int a=10, b=3;
cout << "Addition: " << a+b << endl;
cout << "Subtraction: " << a-b << endl;
cout << "Multiplication: " << a*b << endl;
cout << "Division: " << a/b << endl;
cout << "Modulus: " << a%b << endl;
return 0;
}

2. Relational Operators
Used to compare two values:
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater or Equal
<= Less or Equal
Program: Relational Operators
#include <iostream>
using namespace std;
int main()
{
int a=5, b=8;
cout << (a>b) << endl;
cout << (a<b) << endl;
cout << (a==b) << endl;
cout << (a!=b) << endl;
return 0;
}
Output

[Link] Operators

Used to combine conditions:


&& AND (true if both true)
|| OR (true if any true)
! NOT (reverses condition)

Logical Operators

X y x && y x || y !x !y
true (1) true (1) true (1) true (1) false (0) false (0)
true (1) false (0) false (0) true (1) false (0) true (1)
false (0) true (1) false (0) true (1) true (1) false (0)
false (0) false (0) false (0) false (0) true (1) true (0)

Program: Logical Operators


#include <iostream>
using namespace std;
int main()
{
bool x=true, y=false;
cout << (x && y) << endl;
cout << (x || y) << endl;
cout << (!x) << endl;
return 0;
}
4. Assignment Operators
Used to assign values:
= Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign

Output

Program: Assignment Operators


#include <iostream>
using namespace std;
int main()
{
int a=10;
a+=5; // same as a = a + 5
cout << a << endl;
return 0;
}

5. Increment & Decrement Operators


++ Increment by 1
-- Decrement by 1
Pre-increment (++a) increases before use
Post-increment (a++) increases after use
Program: Increment/Decrement
#include <iostream>
using namespace std;
int main()
{
int a=5;
cout << ++a << endl;
cout << a++ << endl;
cout << a << endl;
return 0;
}
Expressions in C++
An expression combines variables, values, and operators to produce a
result.
Example: (a+b)*c

Unary Operators
Unary operators work on a single operand:
- Negative
+ Positive
! Logical NOT
Program: Unary Operators
#include <iostream>
using namespace std;
int main()
{
int a = 5;
bool x = true;
cout << "Original value of a: " << a << endl;
cout << "Using unary minus (-a): " << -a << endl;
cout << "Using unary plus (+a): " << +a << endl;
cout << "Value of x: " << x << endl;
cout << "Using logical NOT (!x): " << !x << endl;
return 0;
}
6. Conditional (Ternary) Operator
It evaluates a condition and returns one value if the condition is true,
and another value if the condition is false.
It is called “ternary” because it uses three operands:
The condition
The result if the condition is true
The result if the condition is false
Syntax:
condition ? value_if_true : value_if_false

Program: Conditional Operator


#include <iostream>
using namespace std;
int main()
{
int a=7;
cout << ((a>5)?"Greater":"Smaller");
return 0;
}
7. Operator Precedence
Determines which operator is evaluated first.
* has higher precedence than +.
Example:
2+3*4 = 14, not 20.
In Math's Order of Operations: BODMAS / PEMDAS
Brackets
Orders (powers, roots)
Division / Multiplication (left to right)
Addition / Subtraction (left to right)
Associativity of Operators
Definition: When two operators have the same precedence,
associativity decides the order of evaluation.
Example (Left to Right):
int a = 10, b = 5, c = 2;
int result = a - b - c; // (10 - 5) - 2 = 3
cout << result; // Output: 3
Operators like -, /, %, + follow Left to Right associativity.
Summary
- Operators are symbols used to perform operations.
- Types: Arithmetic, Relational, Logical, Assignment,
Increment/Decrement, Unary, Conditional.
- Expressions combine operators and operands to produce values.
- Precedence and Associativity decide the order of evaluation.
Lab Assignment
Write a C++ program to create a simple calculator that performs
addition, subtraction, multiplication, and division based on user input.
Add comments in program.
Write a C++ program to check whether a given number is positive,
negative, or zero. Add comments in program.
Variables and DataTypes
What is Variable?
In C++, a variable is a named storage location in the computer's
memory used to hold data. It acts as a container for a specific type of
value, which can be accessed and modified throughout the program's
execution.

Key characteristics of a C++ variable


1. Named Memory Location:
Variables are essentially labels or identifiers given to specific memory
addresses where data is [Link] allows you to refer to and
manipulate the datawithout needing to know the exact memory
address.

Data Type: Every variable in C++ must have a specified data type (e.g.,
int, float, char, bool, string). The data type determines the kind of
values the variable can store, the amount of memory it occupies, and
the operations that can be performed on it.
Value: A variable holds a value of its declared data type. This value can
be assigned during declaration (initialization) or later in the program.
Modifiable:
The value stored in a variable can be changed or updated during the
program's runtime, allowing for dynamic data manipulation.
Example
int age = 30; // Declares an integer variable named 'age' and initializes it
with the value

30float price = 19.99; // Declares a floating-point variable named


'price' and initializes
char initial = 'J'; // Declares a character variable named 'initial'

C++ VARIABLES
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different
keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or
-123
double - stores floating point numbers, with decimals, such as 19.99 or
-19.99
char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded
by double quotes
bool - stores values with two states: true or false
C++ Data Types
a variable in C++ must be a specified data type:

C++ Identifiers
All C++ variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).

Boolean Types
A boolean data type is declared with the bool keyword and can only
take the values true or false.
When the value is returned, true = 1 and false = 0.
C++ Character Data Types

The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':

C++ String Data Types


The string type is used to store a sequence of characters (text). This is
not a built-in type, but it behaves like one in its most basic usage. String
values must be surrounded by double quotes

Constants
When you do not want others (or yourself) to change existing variable
values, use the const keyword (this will declare the variable as
"constant", which means unchangeable and read-only)
C++ codes (Try it yourself)

Print Text
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values
and print text.
Just remember to surround the text with double quotes (""):
Example
cout << "Hello World!";
New Lines
To insert a new line in your output, you can use the \n character:
For Example:
C++ CODE
Write a C++ code to find area of circle.
Solution
#include <iostream>
using namespace std;
int main()
{
float r, area;
cout << "\n Enter Radius:";
cin >> r;
area = 3.14* r* r;
cout << "\n The Area of the circle is" << area;
}

Write C++ Code to Find Simple Interest


What is 'Simple Interest'?
Simple interest is a quick method of calculating the interest charge on a
loan. Simple interest is determined by multiplying the daily interest rate
by the principal by the number of days that elapse between payments.
Formula

where P is the principal amount, T is time & R is the rate of interest.


// C++ program to find simple interest
// for given principal amount, time
// and rate of interest.
#include<iostream>
using namespace std;

// Driver code
int main()
{
// We can change values here for
// different inputs
float P = 1, R = 1, T = 1;

// Calculate simple interest


float SI = (P * T * R) / 100;
// Print the resultant value of SI
cout << "Simple Interest = " << SI;

return 0;
}
Control Structures in C++ (week 5)
Introduction
Control structures manage the flow of execution in a program.
They determine which statements execute under certain conditions.
Types of Control Structures
1. Sequential Structures
- Executes statements line by line.
- No decisions or repetition.
2. Selection / Decision Structures
- Executes code conditionally based on a true/false condition.
- Includes if, if-else, else-if ladder, and switch (explained later).

3. Iteration / Looping Structures


- Repeats a block of code while a condition holds true.
- Used for repeating tasks.
4. Jump Statements
- Transfers program control to another part of the code.
- Examples: break, continue, goto, return.
Why Control Structures?
Let the program choose different actions based on conditions.
They allow programs to make logical decisions and execute code
selectively.
Reduces redundancy and improves program performance.
It make programs dynamic, intelligent, and efficient.
Decision-Making in C++
Decision-making uses following statements to control logic flow like:
if
if-else
Nested if
Else-if
switch

If Statement – Syntax
if (condition)
{
// statements
}
Executes code only if the condition is true. skipping otherwise.

If Example program
#include <iostream>
using namespace std;
int main()
{
int num = 10;
if (num > 0)
{
cout << "Positive number";
}
}
Used for two-way decisions: when one condition leads to two
possible outcomes.
if (condition)
{
// code if true
}
else
{
// code if false
}

Even/Odd Example
Braces {} are optional if there is only
#include <iostream>
using namespace std; one statement inside theblock.
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
If remainder after division by 2 is 0,
if (num % 2 == 0)
cout << "Even number";
else
cout << "Odd number";
}

Nested If
A nested if is an if statement placed inside another if statement.
It allows checking a secondary condition only if the primary condition
is true.
Nested If Example
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
if (a > 0)
{
if (b > a)
cout << "b is greater";
}
}
Else-If Ladder
Used for checking multiple conditions sequentially.
Executes the first true block and skips the rest.
Useful when more than two possible outcomes exist.
Else-If Syntax
if (condition1)
statement 1;
else if (condition2)
statement 2;
else
statement N;

Else-if Grading Example

#include <iostream>
using namespace std;
int main()
{
int marks; Checks multiple ranges; executes
cout << "Enter marks: ";
cin >> marks;
only one matching condition.
if (marks >= 90)
cout << "Grade A";
else if (marks >= 80)
cout << "Grade B";

else if (marks >= 70)


cout << "Grade C";
else
cout << "Fail";
}

Positive/Negative Example
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num; Program classifies input number as
positive, negative, or zero.
if (num > 0)
cout << "Positive";

else if (num < 0)


cout << "Negative";

else
cout << "Zero";
}
Switch Statement in C++
Execute one block of code from multiple alternatives based on a
variable.
Ideal when a variable needs to be compared with several constant
values.
Switch-Syntax
switch(variable)
{ Each case ends with break.
case value1: default executes if no case matches.
// statements Works with integral (int,char,) or enum types.
break; .
case value2:
// statements
break;
default:
// statements if no case matches
}
Switch Example

#include <iostream>
using namespace std;
int main()
{
- day is compared with each case.
int day = 3;
- day=3 prints Wednesday.
switch(day)
- break exits after matching case.
{ - default handles unmatched values.
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Other day";
}
}
Common Mistakes
1. Using '=' instead of '=='
if (num = 5) { // ❌ assigns 5 instead of comparing
cout << "Five";
}
2. Missing braces for multiple statements.
if (num > 0)
cout << "Positive";
cout << "Number"; // executes regardless of if
3. Not covering all cases
In else-if ladder or switch, failing to include all possibilities can cause
unexpected results.
Solution: Always include a final else or default to handle unmatched
cases.

Best Practices
1. Indent properly.
2. Keep conditions readable.
3. Test all logical paths.
4. Use Braces Even for Single Statements to Prevents errors when
adding new statements later.
5. Comment Your Logic to understand the purpose of conditions.

Real-Life Uses
Validate username and password in login systems.
Assign grades based on student marks.
Check account balance before withdrawal in banking apps.
Apply discounts based on purchase amount in online shopping.
Control traffic signals using sensor inputs.
Decide game actions based on player input or game state.
Automate devices like lights or thermostats based on conditions.
Summary
if → executes a block for a single condition.
if-else → chooses between two possible outcomes.
else-if ladder → checks multiple conditions sequentially.
switch → selects a block to execute based on the value of a variable.

Lab Assignment
Write a C++ program to check whether a given number is divisible by
both 5 and 11.
Write a C++ program to check whether a given year is a leap year or
not.

You might also like