Problem Solving Techniques
Course Code :- CAUCBC106T
Course :- BCA
Semester :- 1
By :- Shikhar Prakash
Unit - 2
Algorithm Development: Definition, Algorithm: a solution to a problem, Input-Output
Statements
Decision Making Statements, Looping Statements, Examples.
Flowcharting: Definition, Input-Output Statements, Decision Making Statements, Looping
Statements, Module representation, Drawing conventions and standards, Example.
Debugging: Bug , errors : syntax ,semantics and runtime, Compilation, Interoperation,
Program debugging.
Algorithm Development
The word Algorithm means ” A set of finite rules or instructions to be followed in calculations
or other problem-solving operations ”
What are the Characteristics of an Algorithm?
• Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs.
It may or may not take input.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded and
it should be well-defined as well. It should produce at least 1 output.
• Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
• Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
• Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be the same, as expected.
Properties of Algorithm
• It should terminate after a finite time.
• It should produce at least one output.
• It should take zero or more input.
• It should be deterministic means giving the same output for the same input case.
• Every step in the algorithm must be effective i.e. every step should do some work.
Types of Algorithm
1. Brute Force
2. Recursive Algorithm
3. Backtracking Algorithm
4. Searching Algorithm
5. Sorting
6. Hashing
7. Divide and Conquer
8. Greedy Algorithm
9. Dynamic Programming etc.
Advantages of Algorithm
• It is easy to understand.
• An algorithm is a step-wise representation of a solution to a given problem.
• In an Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
Disadvantages of Algorithm
• Writing an algorithm takes a long time so it is time-consuming.
• Understanding complex logic through algorithms can be very difficult.
• Branching and Looping statements are difficult to show in Algorithms.
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-requisite:
• The problem that is to be solved by this algorithm i.e. clear problem definition.
• The constraints of the problem must be considered while solving the problem.
• The input to be taken to solve the problem.
• The output is to be expected when the problem is solved.
• The solution to this problem is within the given constraints.
Example: Consider the example to add three numbers and print the sum.
Step 1: Fulfilling the pre-requisites
As discussed above, to write an algorithm, its prerequisites must be fulfilled.
1. Add 3 numbers and print their sum.
2. The numbers must contain only digits and no other characters.
3. The three numbers to be added.
4. The sum of the three numbers taken as the input i.e. a single integer value.
5. The solution consists of adding the 3 numbers. It can be done with the help of the „+‟
operator, or bit-wise, or any other method.
Step 2: Designing the algorithm
Now let‟s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3
respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END
Input Output Statement
Print Output in Python
The print() function allows us to display text, variables, and expressions on the console.
E.g. : print("Hello, World!")
Print Single and Multiple variable in Python
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
name, age, city = "John", 30, "New York"
print(name)
print(age)
print(city)
Python Print Variable using F-Strings
name = "Alice"
age = 30
city = "Wonderland"
# Using F-string to incorporate multiple variables
message = f"Hello, my name is {name}, I am {age} years old, and I live in {city}."
# Printing the formatted message
print(message)
Output :
Hello, my name is Alice, I am 30 years old, and I live in Wonderland.
Using Format()
amount = 150.75
print("Amount: ${:.2f}".format(amount))
Using sep and end parameter
# end Parameter with '@'
print("Python", end='@') Output
print("GeeksforGeeks")
Python@GeeksforGeeks
# Seprating with Comma
print('G', 'F', 'G', sep=„ „) GFG
# for formatting a date 09-12-2016
print('09', '12', '2016', sep='-')
pratik@geeksforgeeks
# another example
print('pratik', 'geeksforgeeks', sep='@')
Taking input in Python
Python input() function is used to take user input. By default, it returns the user input in
form of a string.
Syntax: input(prompt)
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
num = int(input(“Enter a number”))
Output : Enter a number
Decision making statement
• Programming requires decision-making statements because they let programs decide what to
do and run distinct code blocks according to predefined conditions.
• The if, elif and if-else statements are just a few of the decision-making statements available in
Python.
Types of decision-making statements in python
If statements in python
If else statement in python
Nested if statement in Python
if-elif-else Ladder in Python
Ternary statement | Short hand if else statement
1. If statements in python
• The if keyword is followed by an indented block of statements that are executed if
the condition is assessed and found to be true.
• If not, the code skips the if block.
Syntax :
if expression:
statement(s)
Example :
age = 18
if age >= 18:
print("You are an adult.")
2. If else statement in python
• The if statement itself indicates that if a condition is true, a block of statements will be
executed.
• If the condition in the if block evaluates to false, the else statement executes an
alternate block of code.
• This block of alternatives is introduced by the else keyword.
Syntax of If Else Statement in Python :
if expression:
statement(s)
else:
statement(s)
E.g. : num = 11
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
3. Nested if else statement in Python
• Python enables the nesting of decision-making statements, which facilitates the
development of more complex decision logic. A nested if statement is one that has an
if statement within another if statement.
• A hierarchy of conditions can be created by an if or if-else block within another if or if-
else block.
Syntax of Nested If Else Statement in Python
if expression1:
statement(s)
if expression2:
statement(s)
else:
statement(s)
else:
statement(s)
Example of Nested If Else Statement in Python Compiler
num = 3
if num > 0:
if num % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive but odd.")
else:
print("The number is not positive.")
Example:
• score = 85
• passed_exam = True
• if score >= 60:
• if passed_exam:
• print("Congratulations! You passed with a score of", score)
• else:
• print("You scored well but did not pass the exam.")
• else:
• print("You did not pass. Try again.")
4. Python if-elif-else Ladder
• An if-elif-else ladder is an order of if statements connected by elif statements.
• This enables you to check for numerous conditions and run separate code blocks
based on which condition is met.
Syntax of Python if-elif-else Ladder
if condition1: # code block 1
elif condition2:
# code block 2
elif condition3:
# code block 3
else:
# default code block
Example of Python if-elif-else ladder
x = 11
if x == 2:
print("x is equal to 2")
elif x == 3:
print("x is equal to 3")
elif x == 4:
print("x is equal to 4")
else:
print("x is not equal to 2, 3, or 4")
Example :
score = 78
if score >= 90:
print("Grade: A")
elif 80 <= score < 90:
print("Grade: B")
elif 70 <= score < 80:
print("Grade: C")
elif 60 <= score < 70:
print("Grade: D")
else:
print("Grade: F")
Ternary Statement | Short Hand If Else Statement
• A ternary statement, often known as shorthand if-else, is a compact way to express an
if-else condition on a single line. It uses the syntax value_if_true if condition, else
value_if_false. This statement checks the condition and returns one value if it is True
and another if it is False.
Syntax
value_if_true if condition else value_if_false
Example
age = 16
status = "Adult" if age >= 18 else status = "Minor"
print(status)
# Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)
Example : - Find the largest among three
different numbers entered by the user.
Looping Statement
While loop
• A while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the
program is executed.
Python While Loop Syntax:
• while expression:
statement(s)
Example of Python While Loop
• Let‟s see a simple example of a while loop in Python. The given Python code uses
a „while' loop to print “Hello Geek” three times by incrementing a variable
called „count' from 1 to 3.
count = 0
while(count < 3):
print("Hello Geek")
count = count + 1
Output
Hello Geek
Hello Geek
Hello Geek
Using else statement with While Loop in Python
• The else clause is only executed when your while condition becomes false. If you break
out of the loop, or if an exception is raised, it won‟t be executed.
Syntax of While Loop with else statement:
• while condition:
# execute these statements
else:
# execute these statements
Example
• count = 0
• while (count < 3):
print("Hello Geek")
count = count + 1
• else:
• print("In Else Block")
Output
• Hello Geek
• Hello Geek
• Hello Geek
• In Else Block
For Loop in Python
• For loops are used for sequential traversal. For example: traversing a list or string or
array etc.
For Loop Syntax:
• for iterator_var in sequence(start, stop, step):
statements(s)
• It can be used to iterate over a range and iterators.
Example:
• The code uses a Python for loop that iterates over the values from 0 to 3 (not
including 4), as specified by the range(0, n) construct. It will print the values of „i' in
each iteration of the loop.
• n=4
• for i in range(0, n):
• print(i)
• Output
• 0
• 1
• 2
• 3
# Iterating over a String
print("String Iteration")
s = "Geeks"
for i in s:
print(i)
Output:
String Iteration
G
e
e
k
s
for i in range(0, 10, 2):
print(i)
Output :
0
2
4
6
8
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is called nested
loop. Following section shows few examples to illustrate the concept.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Example :
for i in range(0, 10, 2):
print(i)
Output :
0
2
4
6
8
Example :
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
Output :
1
22
333
4444
Debugging
• Debugging is the process of finding and fixing errors or bugs in the source code of any
software.
• It‟s a critical aspect of software development, ensuring quality, performance, and user
satisfaction.
Bug
• A "bug" typically refers to an error, flaw, or unintended behavior in software or hardware
that causes it to produce incorrect or unexpected results.
• In a broader sense, it can also describe any problem or issue that disrupts the normal
functioning of a system.
Error and its types
In programming, "errors" refer to mistakes or issues that prevent a program from functioning as
intended. Errors can generally be categorized into three main types:
1. Syntax Errors: These occur when the code does not conform to the rules of the
programming language, such as missing punctuation, incorrect use of keywords, or improper
structure. These errors are usually caught by the compiler or interpreter before the program
runs.
Example: print("Hello, world!“
2. Runtime Errors: These happen while the program is executing, often due to unexpected
conditions, such as dividing by zero, accessing out-of-bounds array elements, or trying to use a
null reference. Runtime errors cause the program to crash or behave unpredictably.
Example: x = 10
y=0
print(x / y)
3. Logical Errors: These occur when the code runs without crashing but produces incorrect or
unexpected results. Logical errors stem from flaws in the program's logic or algorithms, often
due to misunderstandings of the problem or requirements.
Example:
def add_numbers(a, b):
return a - b # Incorrect operation
result = add_numbers(5, 3)
print(result)
Outputs 2 instead of 8
4. Semantic Errors: These refer to mistakes that make sense in the programming language's
syntax but don't produce the intended result due to a misunderstanding of the problem or the
logic required.
Example :
a+b = c #This is showing misunderstanding of logic
Interoperation
• Interoperation in debugging refers to the ability of different systems, tools, or environments to
work together effectively to identify and resolve issues in software.
• This can involve multiple programming languages, frameworks, or platforms collaborating to
troubleshoot a problem.
• Here are some key aspects of interoperation in debugging:
• Cross-Language Debugging: Tools that support multiple programming languages can help
developers trace bugs across different components of an application. For example, if a front-
end written in JavaScript interacts with a back-end in Python, debugging tools that
understand both can streamline the process.
• Integrated Development Environments (IDEs): Many IDEs offer plugins or built-in features
that allow for the debugging of various languages and frameworks within a single
environment, improving efficiency.
• Remote Debugging: This involves debugging applications running on different machines
or environments.
• Logging and Monitoring Tools: Effective interoperation often relies on robust logging
systems that collect and aggregate logs from different components, enabling developers to
see how different parts of the system interact.
• API Debugging: When services communicate via APIs, debugging tools that can simulate
API calls or analyze network traffic are crucial for identifying issues in data exchange
between systems.
Compilation
• Compilation in debugging refers to the process of converting source code written in a high-
level programming language into machine code, which the computer can execute.
• During this process, various issues can arise, leading to errors that need to be resolved.
• Compile-Time Errors: These are errors that occur during the compilation process, such as
syntax errors, type mismatches, and undeclared variables. They prevent the code from
being successfully compiled. Debugging these errors typically involves checking for typos,
ensuring correct syntax, and validating data types.
• Eg : # Missing colon at the end of if statement
• if 5 > 3
• print("Five is greater than three")
• Compiler Warnings: Warnings are not errors, but they indicate potential issues in the code
that could lead to runtime problems. It's essential to address these warnings to avoid
unexpected behavior later.
• Debug Symbols: When compiling code, developers can include debug symbols, which
provide additional information about the source code, such as variable names and line
numbers. This information can help during debugging sessions, making it easier to trace
back to the source of an issue.
• Optimization Levels: Compilers often have various optimization settings. High
optimization levels can alter how code behaves, sometimes making debugging harder. It's
common to compile with lower optimization levels during development to maintain the
original structure of the code for easier debugging.
• Linker Errors: After compilation, the linker combines different code modules. Linker
errors can occur if there are unresolved references, such as missing functions or libraries.
Debugging these issues typically involves ensuring that all necessary components are
correctly referenced and available.
• Runtime Errors: Once the code compiles successfully, it may still encounter runtime errors.
These errors occur when the program is executed, often due to logic errors, memory issues, or
incorrect assumptions about the program state. Debugging at this stage may involve using
breakpoints, step-through debugging, and inspecting variables.
• # Division by zero during runtime
• num1 = 10
• num2 = 0
• result = num1 / num2
• print(result)
• Logical Error : # The intention is to find the average of two numbers
• num1 = 10
• num2 = 20
• average = num1 + num2 / 2
• print("Average is:", average)
• Integrated Debugging Tools: Many IDEs provide integrated debugging tools that work alongside
the compilation process, allowing developers to catch errors early and debug more effectively
within the same environment.
Process of Program Debugging
Debugging is a crucial skill in programming. Here’s a simple, step-by-step explanation to
help you understand and execute the debugging process effectively:
Step 1: Reproduce the Bug
To start, you need to recreate the conditions that caused the bug. This means making the
error happen again so you can see it firsthand.
Seeing the bug in action helps you understand the problem better and gather important details
for fixing it.
Step 2: Locate the Bug
Next, find where the bug is in your code. This involves looking closely at your code and
checking any error messages or logs.
Developers often use debugging tools to help with this step.
Step 3: Identify the Root Cause
Now, figure out why the bug happened. Examine the logic and flow of your code and see
how different parts interact under the conditions that caused the bug.
This helps you understand what went wrong.
Step 4: Fix the Bug
• Once you know the cause, fix the code. This involves making changes and then testing
the program to ensure the bug is gone.
• Sometimes, you might need to try several times, as initial fixes might not work or could
create new issues.
• Using a version control system helps track changes and undo any action that don’t solve
the problem.
Step 5: Test the Fix
• After fixing the bug, run tests to ensure everything works correctly. These tests include:
• Unit Tests: Check the specific part of the code that was changed.
• Integration Tests: Verify the entire module where the bug was found.
• System Tests: Test the whole system to ensure overall functionality.
• Regression Tests: Make sure the fix didn’t cause any new problems elsewhere in the
application.
Step 6: Document the Process
Finally, record what you did. Write down what caused the bug, how you fixed it, and any
other important details.
This documentation is helpful if similar issues occur in the future.
Difference between Testing and Debugging
Aspects Testing Debugging
Debugging is the process of
Testing is the process to find bugs
Definition correcting the bugs found during
and errors.
testing.
The purpose of testing is to identify
The purpose of debugging is to fix
Purpose defects or errors in the software
those defects or errors.
system
It is the process to identify the failure It is the process to give absolution to
Focus
of implemented code. code failure.
Timing Testing is done before debugging Debugging is done after testing
Debugging involves analyzing the
Testing involves executing the symptoms of a problem and
Approach
software system with test cases identifying the root cause of the
problem
Debugging typically involves using
Tools and Testing can involve using automated
tools and techniques such as logging,
Technique or manual testing tools
tracing, and code inspection.
Pattern Programs
• https://youtu.be/fX64q6sYom0?si=IM0V2c546LbaEDws
• https://youtu.be/npopDLgUXzU?si=vwS-8BK3mahV4Psj