0% found this document useful (0 votes)
2 views17 pages

UNIT I Algorithmic Problem Solving

The document provides comprehensive notes on algorithmic problem solving and Python programming, covering fundamentals of computing, including hardware, software, input/output, storage, and processing. It explains various numbering systems, conversion methods between decimal, binary, octal, and hexadecimal, as well as logical and algorithmic thinking. Additionally, it outlines steps in problem-solving, characteristics of algorithms, and provides examples of algorithms for specific tasks.

Uploaded by

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

UNIT I Algorithmic Problem Solving

The document provides comprehensive notes on algorithmic problem solving and Python programming, covering fundamentals of computing, including hardware, software, input/output, storage, and processing. It explains various numbering systems, conversion methods between decimal, binary, octal, and hexadecimal, as well as logical and algorithmic thinking. Additionally, it outlines steps in problem-solving, characteristics of algorithms, and provides examples of algorithms for specific tasks.

Uploaded by

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

UNIT I

Algorithmic Problem Solving


Python Programming – Comprehensive Notes (20-Mark Answers)

Q1. Fundamentals of Computing

Computing is the process of using computer hardware and software to input, store, process, and output
data/information. A computer system is composed of six fundamental components:

1. Hardware
Hardware refers to the physical, tangible components of a computer that can be seen and touched.
• Central Processing Unit (CPU) – Intel Core i9, AMD Ryzen
• Memory (RAM) – 8 GB, 16 GB DDR4 RAM
• Storage – 512 GB SSD, 1 TB Hard Disk
• Motherboard – connects all components together
• GPU – NVIDIA RTX 4090 for graphics processing

2. Software
Software is a set of programs and instructions that tell the hardware what to do. It is intangible.
Type Description Examples
System Software Manages hardware Windows 11, Linux, macOS
resources
Application Software Performs specific user tasks MS Word, Chrome, VLC
Programming Tools Help develop software Python, Java, VS Code, GCC
Utility Software Maintenance & support tasks Antivirus, Disk Cleaner

3. Input
Input is the raw data fed into a computer for processing. Input devices convert real-world data into
digital form.
• Keyboard – entering text and commands
• Mouse – pointing and clicking for navigation
• Scanner – converting paper documents to digital images
• Microphone – voice input for speech recognition
• Webcam – video input for video calls
4. Output
Output is the processed result delivered by the computer to the user or another system.
• Monitor – displays visual information (text, images, video)
• Printer – produces hard copies of documents
• Speakers – produce audio output
• Projector – displays output on large screen

5. Storage
Storage devices hold data permanently or temporarily for future use.
Type Location Example Speed
Primary (RAM) Inside CPU 8 GB DDR4 Very Fast – temporary
Secondary External to CPU SSD, HDD Moderate – permanent
Cache Inside CPU chip L1, L2, L3 Fastest – very small
Cloud Remote servers Google Drive Depends on internet

6. Processing
Processing is the core activity where the CPU transforms raw input data into meaningful output using
arithmetic, logic, and control operations.
• ALU (Arithmetic Logic Unit) – performs +, -, ×, ÷ and AND, OR, NOT
• Control Unit (CU) – fetches, decodes, and executes instructions
• Registers – tiny, ultra-fast temporary storage inside CPU

Complete Data Flow Diagram:


[INPUT] → [PROCESSOR/CPU] → [OUTPUT]
↑ ↓
[STORAGE / MEMORY]

Example:
Input : User types '5 + 3' on keyboard
Process : CPU computes 5 + 3 = 8
Output : Monitor displays 8
Storage : Result may be saved to disk

Q2. Numbering Systems in Computing

Computers internally use binary (base-2) because electronic circuits have two states: ON (1) and OFF
(0). Different numbering systems are used for different purposes.

System Base Digits Used Used For


Binary 2 0, 1 Internal computer
processing
Octal 8 0–7 Compact
representation of
binary
Decimal 10 0–9 Human everyday
arithmetic
Hexadecimal 16 0–9, A–F Memory addresses,
colour codes

Q3. Decimal to Binary Conversion

Method: Repeatedly divide the decimal number by 2. Record the remainders from bottom to top.

Example 1: Convert 45 to Binary


Division Quotient Remainder
45 ÷ 2 22 1 ← LSB
22 ÷ 2 11 0
11 ÷ 2 5 1
5÷2 2 1
2÷2 1 0
1÷2 0 1 ← MSB

Result:
45₁₀ = 101101₂
Read remainders from bottom to top: 1 0 1 1 0 1

Example 2: Convert 156 to Binary


156 ÷ 2 = 78 R 0
78 ÷ 2 = 39 R 0
39 ÷ 2 = 19 R 1
19 ÷ 2 = 9 R 1
9 ÷ 2 = 4 R 1
4 ÷ 2 = 2 R 0
2 ÷ 2 = 1 R 0
1 ÷ 2 = 0 R 1 ← MSB

Result (bottom to top): 10011100

Result:
156₁₀ = 10011100₂

Verification (Binary back to Decimal):


10011100 = 1×2⁷ + 0×2⁶ + 0×2⁵ + 1×2⁴ + 1×2³ + 1×2² + 0×2¹ + 0×2⁰
= 128 + 0 + 0 + 16 + 8 + 4 + 0 + 0
= 156 ✓

Q4. Binary to Decimal Conversion

Method: Multiply each bit by 2 raised to its positional power (right to left, starting from 0), then sum all
results.

Example 1: Convert 101101₂ to Decimal


Bit 7 6 5 4 3 2 1 0
Position
Bit – – 1 0 1 1 0 1
Value
Power of – – 2⁵=32 2⁴=16 2³=8 2²=4 2¹=2 2⁰=1
2
Contribu – – 32 0 8 4 0 1
tion

101101₂ = 1×2⁵ + 0×2⁴ + 1×2³ + 1×2² + 0×2¹ + 1×2⁰


= 32 + 0 + 8 + 4 + 0 + 1
= 45

Result:
101101₂ = 45₁₀

Example 2: Convert 11001010₂ to Decimal


11001010 = 1×2⁷ + 1×2⁶ + 0×2⁵ + 0×2⁴ + 1×2³ + 0×2² + 1×2¹ + 0×2⁰
= 128 + 64 + 0 + 0 + 8 + 0 + 2 + 0
= 202

Result:
11001010₂ = 202₁₀

Q5. Decimal to Octal Conversion

Method: Repeatedly divide the decimal number by 8. Record remainders from bottom to top.

Example 1: Convert 255 to Octal


Division Quotient Remainder
255 ÷ 8 31 7 ← LSB
31 ÷ 8 3 7
3÷8 0 3 ← MSB

Result:
255₁₀ = 377₈

Example 2: Convert 1500 to Octal


1500 ÷ 8 = 187 R 4
187 ÷ 8 = 23 R 3
23 ÷ 8 = 2 R 7
2 ÷ 8 = 0 R 2 ← MSB

Result:
1500₁₀ = 2734₈

Binary → Octal Shortcut (group by 3 bits from right):


Binary: 1 0 1 1 0 1
Group: [1] [01] [101] → no, group from RIGHT:
10 11 01
2 3 1 (octal digits)
101101₂ = 55₈

Verify: 5×8¹ + 5×8⁰ = 40 + 5 = 45₁₀ ✓

Q6. Decimal to Hexadecimal Conversion

Method: Repeatedly divide by 16. Remainders 10–15 are written as A–F.


De 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ci
ma
l
He 0 1 2 3 4 5 6 7 8 9 A B C D E F
x

Example 1: Convert 255 to Hexadecimal


Division Quotient Remainder Hex Digit
255 ÷ 16 15 15 F ← LSB
15 ÷ 16 0 15 F ← MSB

Result:
255₁₀ = FF₁₆
Example 2: Convert 2748 to Hexadecimal
2748 ÷ 16 = 171 R 12 → C
171 ÷ 16 = 10 R 11 → B
10 ÷ 16 = 0 R 10 → A

Read bottom to top: ABC

Result:
2748₁₀ = ABC₁₆

Binary → Hexadecimal Shortcut (group by 4 bits from right):


Binary: 1010 1111 0011
Hex : A F 3
10101111 0011₂ = AF3₁₆

Q7. Logical Thinking vs Algorithmic Thinking

A. Logical Thinking
Logical thinking is the ability to analyse a situation, identify relationships and patterns, and draw valid
conclusions using reason and evidence. It is the foundation of rational problem solving.

Characteristics of Logical Thinking:


• Uses rules of inference (if A then B, A is true → B is true)
• Identifies cause-and-effect relationships
• Eliminates contradictions and ambiguities
• Applies to abstract reasoning and everyday decisions

Real-life Example:
Situation: The light in the room is not working.

Logical reasoning chain:


1. If the light is off → either bulb is fused or power is cut
2. Other appliances work → power is available
3. Therefore → the bulb is fused
4. Conclusion → Replace the bulb

B. Algorithmic Thinking
Algorithmic thinking is the ability to solve a problem by defining a clear, precise, step-by-step sequence
of instructions that can be executed by a human or computer to produce the desired result.

Characteristics of Algorithmic Thinking:


• Breaks a problem into finite, ordered steps
• Each step must be unambiguous and executable
• Has a clear start, defined input, and guaranteed output
• Can be translated into a program

Real-life Example – Making Tea:


Algorithm: Make a Cup of Tea
Step 1: Boil water in a kettle
Step 2: Place a tea bag in the cup
Step 3: Pour hot water into the cup
Step 4: Wait 3 minutes
Step 5: Remove the tea bag
Step 6: Add sugar and milk as required
Step 7: Stir and serve

Feature Logical Thinking Algorithmic Thinking


Focus Reasoning and inference Step-by-step execution
Goal Reach a logical conclusion Solve a problem systematically
Structure Not necessarily sequential Always sequential
Executability By human reasoning By human or computer
Precision May be informal Must be unambiguous
Example Deducing who committed a Sorting a list of names
crime

Q8. Steps in Problem Solving

Problem solving in computing is a structured process that transforms a problem statement into a
working solution. It involves three major phases:

Step 1: Defining the Problem


The first and most critical step is to clearly understand and define what the problem is asking. A poorly
defined problem leads to a wrong solution.

Activities in this step:


• Read and re-read the problem statement carefully
• Identify the inputs (what data is given)
• Identify the outputs (what result is needed)
• Identify constraints and special conditions
• Ask clarifying questions to remove ambiguity

Example – Define the problem: 'Find the average of N numbers'


Aspect Details
Input Number N, and N individual numbers
Output Average (sum divided by N)
Constraints N must be > 0 (no division by zero)
Process Sum all numbers, divide by N

Step 2: Devising the Solution


Once the problem is defined, we design the strategy and algorithm to solve it. This step translates the
problem definition into a logical solution plan.

Activities:
• Identify the most efficient approach (brute force, divide & conquer, etc.)
• Write pseudocode or draw a flowchart
• Choose appropriate data structures
• Consider edge cases and boundary conditions
• Evaluate time and space complexity

Example – Devise solution for average:


Pseudocode:
START
READ N
SET sum = 0
FOR i = 1 TO N:
READ number
sum = sum + number
END FOR
average = sum / N
PRINT average
STOP

Step 3: Decomposition
Decomposition is the process of breaking a large, complex problem into smaller, manageable sub-
problems. Each sub-problem is solved independently and the solutions are combined.

Benefits of Decomposition:
• Makes complex problems easier to understand
• Sub-problems can be solved in parallel
• Promotes code reuse through functions/modules
• Easier to test and debug individual parts

Example – Decompose 'Student Report Card System':


Main Problem: Generate Student Report Card

Sub-problems:
1. Input sub-system → Read student name, ID, marks for each subject
2. Calculation sub-sys → Compute total, average, grade for each student
3. Comparison sub-sys → Find class topper and rank students
4. Output sub-system → Format and print the report card

Each sub-problem becomes a separate function in the program.

Q9. Algorithm – Definition and Characteristics

Definition
An algorithm is a finite, ordered set of unambiguous and executable instructions that solves a given
problem in a finite amount of time. It takes input, processes it through a series of steps, and produces a
definite output.

Origin: The word 'algorithm' comes from the name of the 9th-century mathematician Muhammad ibn
Musa al-Khwarizmi.

Characteristics of a Good Algorithm

# Characteristic Explanation
1 Finiteness Must terminate after a finite number of steps – no infinite loops
2 Definiteness Every step must be precisely and unambiguously defined
3 Input Has zero or more well-defined inputs
4 Output Produces at least one meaningful output
5 Effectiveness Every step must be basic and executable in finite time
6 Correctness Produces the correct output for all valid inputs
7 Generality Works for all instances of the problem, not just specific cases

Example – Algorithm to Find Sum of N Natural Numbers


Algorithm: SUM_NATURAL
Input : A positive integer N
Output : Sum of 1 + 2 + ... + N

Step 1: START
Step 2: READ N
Step 3: SET sum = 0, i = 1
Step 4: WHILE i <= N DO
Step 5: sum = sum + i
Step 6: i = i + 1
Step 7: END WHILE
Step 8: PRINT sum
Step 9: STOP

Trace for N = 4:
i=1: sum=1 i=2: sum=3 i=3: sum=6 i=4: sum=10
Output: 10

Q10. Largest of Three Numbers – Algorithm and Flowchart

Algorithm
Algorithm: LARGEST_THREE
Input : Three numbers A, B, C
Output : The largest among A, B, C

Step 1: START
Step 2: READ A, B, C
Step 3: IF A >= B AND A >= C THEN
Step 4: PRINT 'Largest is A =', A
Step 5: ELSE IF B >= A AND B >= C THEN
Step 6: PRINT 'Largest is B =', B
Step 7: ELSE
Step 8: PRINT 'Largest is C =', C
Step 9: END IF
Step 10: STOP

Trace for A=12, B=45, C=30:


A>=B? 12>=45? No
B>=A AND B>=C? 45>=12 AND 45>=30? Yes
Output: Largest is B = 45

Flowchart
┌─────────┐
│ START │
└────┬────┘

┌────▼────────────────┐
│ READ A, B, C │
└────┬────────────────┘

┌─────────▼──────────────┐
│ Is A >= B AND A >= C? │
└──────┬──────────┬──────┘
YES│ │NO
┌───────▼──┐ ┌───▼─────────────────────┐
│ Print A │ │ Is B >= A AND B >= C ? │
└───────┬──┘ └───┬─────────────┬───────┘
│ YES│ │NO
│ ┌──────▼──┐ ┌────▼────┐
│ │ Print B │ │ Print C │
│ └──────┬──┘ └────┬────┘
│ │ │
└────┬────┘─────────────┘

┌────▼────┐
│ STOP │
└─────────┘
Q11. Prime Number Check – Algorithm and Flowchart

Definition
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
Examples: 2, 3, 5, 7, 11, 13...

Algorithm
Algorithm: CHECK_PRIME
Input : A positive integer N
Output : Whether N is PRIME or NOT PRIME

Step 1: START
Step 2: READ N
Step 3: IF N <= 1 THEN
Step 4: PRINT 'Not Prime'
Step 5: GOTO Step 12
Step 6: END IF
Step 7: SET i = 2
Step 8: WHILE i <= sqrt(N) DO
Step 9: IF N MOD i == 0 THEN
Step 10: PRINT 'Not Prime'
Step 11: GOTO Step 12
Step 12: END IF
Step 13: i = i + 1
Step 14: END WHILE
Step 15: PRINT 'Prime'
Step 16: STOP

Trace for N = 13:


i=2: 13%2=1 (not 0), i=3: 13%3=1 (not 0), sqrt(13)≈3.6
Loop ends. Output: Prime ✓

Trace for N = 12:


i=2: 12%2=0 → Output: Not Prime ✓

Flowchart
┌─────────┐
│ START │
└────┬────┘

┌────▼──────────┐
│ READ N │
└────┬──────────┘

┌────────▼───────┐
│ Is N <= 1? │
└──┬──────────┬──┘
YES│ │NO
┌───────▼──┐ ┌────▼──────────────┐
│Not Prime │ │ SET i = 2 │
└───────┬──┘ └────┬──────────────┘
│ │
│ ┌──────▼───────────────┐
│ │ Is i <= sqrt(N) ? │
│ └──┬──────────────┬────┘
│ YES│ │NO
│ ┌────▼──────────┐ ┌▼──────┐
│ │Is N % i == 0? │ │ PRIME │
│ └──┬────────┬───┘ └───┬───┘
│ YES│ │NO │
│ ┌──▼──────┐ │i=i+1 │
│ │Not Prime│ └──────┐ │
│ └──┬──────┘ │ │
└────┘ │ │
└────┘

┌────▼────┐
│ STOP │
└─────────┘

Q12. Algorithmic Constructs: Pseudocode, Flowchart, Programming Language

A. Pseudocode
Pseudocode is an informal, high-level description of an algorithm using a mixture of natural language
and simplified programming-like syntax. It is NOT actual code – it cannot be compiled or run.

Characteristics:
• Language-independent – not tied to any programming language
• Easy to read and understand by non-programmers
• Uses keywords: BEGIN, END, READ, PRINT, IF, WHILE, FOR
• No strict syntax rules – uses indentation for structure

Example – Find sum of even numbers up to N:


BEGIN
READ N
SET sum = 0
FOR i = 1 TO N DO
IF i MOD 2 == 0 THEN
sum = sum + i
END IF
END FOR
PRINT 'Sum of even numbers =', sum
END

B. Flowchart
A flowchart is a graphical/pictorial representation of an algorithm using standard symbols and arrows to
show the flow of logic.
Symbol Shape Meaning
Oval / Rounded Rect ( START / STOP ) Terminal – Begin or End
Parallelogram / INPUT / OUTPUT / Input or Output operation
Rectangle [ PROCESS ] Processing / Computation
Diamond < DECISION > Decision (Yes/No branch)
Arrow → Flow of control
Circle () Connector between parts

Advantages of Flowcharts:
• Provides a visual overview of the entire program
• Easier to identify logic errors before coding
• Useful for explaining programs to non-technical stakeholders
• Serves as documentation for maintenance

C. Programming Language
A programming language is a formal, machine-readable language used to implement algorithms. Unlike
pseudocode, code in a programming language must follow strict syntax rules and can be
compiled/interpreted and executed.

Type Examples Characteristic


Low-level Assembly, Machine code Closer to hardware, harder to
write
High-level Python, Java, C++ Closer to English, easier to write
Scripting Python, JavaScript Interpreted, rapid development
Compiled C, C++, Rust Translated to machine code
before run

Feature Pseudocode Flowchart Programming


Language
Form Text-based Diagram-based Text-based (formal)
Syntax Informal Standard symbols Strict
Executable No No Yes
Tool Paper/Word Paper/Draw tool Compiler/Interpreter
Best for Planning logic Visualising flow Actual implementation

Q13. Factorial – Pseudocode and Flowchart


Definition
The factorial of a non-negative integer N, written as N!, is the product of all positive integers from 1 to
N.
n! = n × (n-1) × (n-2) × ... × 2 × 1
0! = 1 (by definition)

Examples:
5! = 5 × 4 × 3 × 2 × 1 = 120
6! = 720
0! = 1

Pseudocode
BEGIN FACTORIAL

READ N

IF N < 0 THEN
PRINT 'Factorial undefined for negative numbers'
STOP
END IF

SET factorial = 1
SET i = 1

WHILE i <= N DO
factorial = factorial × i
i = i + 1
END WHILE

PRINT 'Factorial of', N, '=', factorial

END FACTORIAL

Dry Run for N = 5:


i=1: fact=1 i=2: fact=2 i=3: fact=6
i=4: fact=24 i=5: fact=120 → STOP
Output: Factorial of 5 = 120

Flowchart
┌──────────┐
│ START │
└────┬─────┘

┌────▼─────────┐
│ READ N │
└────┬─────────┘

┌───────▼──────┐
│ Is N < 0? │
└──┬───────┬───┘
YES│ │NO
┌──────▼───┐ ┌▼──────────────────┐
│ Error │ │ SET fact=1, i=1 │
│ Print │ └──────┬────────────┘
└──────┬───┘ │
│ ┌───────▼───────────┐
│ │ Is i <= N ? │
│ └──┬────────────┬───┘
│ YES│ │NO
│ ┌──────▼──────┐ ┌──▼──────────────────┐
│ │fact = fact×i│ │ PRINT fact │
│ │i = i + 1 │ └──────────────────────┘
│ └──────┬──────┘ │
│ └──────────┐ │
│ ↑ │
│ (loop back) │
└────────────────────────── ┘

┌────▼────┐
│ STOP │
└─────────┘

Python Implementation
n = int(input('Enter a number: '))
if n < 0:
print('Factorial undefined for negative numbers')
else:
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f'{n}! = {factorial}')

Result:
Enter a number: 6
6! = 720

Q14. Concept of Program State

Definition
The program state (or computational state) is the complete snapshot of all the values stored in
variables, memory, and data structures at any particular moment during the execution of a program. As
the program executes each statement, the state changes.

Formal Definition: State = { (variable₁, value₁), (variable₂, value₂), ..., (variableₙ, valueₙ) } at a
specific point in execution

Why Program State Matters


• Understanding state helps trace program execution and find bugs
• Debugging tools (like pdb) let you inspect state at any line
• Functions can change state through parameters and return values
• Global vs local state affects variable scope and program behaviour

Detailed Example – Tracing Program State


Consider the following program to find the sum and average of a list of numbers:

total = 0 # Line 1
count = 0 # Line 2
numbers = [10, 25, 15, 30, 20] # Line 3

for num in numbers: # Line 4


total = total + num # Line 5
count = count + 1 # Line 6

average = total / count # Line 7


print(total, count, average) # Line 8

State Trace Table:


After Line total count num average State
Description
1 0 – – – total initialised
2 0 0 – – count
initialised
3 0 0 – – numbers list
created
Loop i=1 10 1 10 – First number
processed
Loop i=2 35 2 25 – Second
number added
Loop i=3 50 3 15 – Third number
added
Loop i=4 80 4 30 – Fourth number
added
Loop i=5 100 5 20 – Fifth number
added
7 100 5 20 20.0 average
computed
8 100 5 20 20.0 Output: 100 5
20.0

State Changes Due to Assignment


# Initial state
x = 5 # State: { x=5 }
y = 10 # State: { x=5, y=10 }
z = x + y # State: { x=5, y=10, z=15 }
x = z * 2 # State: { x=30, y=10, z=15 } ← x changed!
del y # State: { x=30, z=15 } ← y removed!
print(x, z) # Output: 30 15

State in Conditional and Loop Contexts


n = 10 # State: {n=10, --}
result = 0 # State: {n=10, result=0}

while n > 0: # Condition checked each iteration


result += n # State changes each iteration
n -= 1

# State progression:
# n=10, result=10 → n=9, result=19 → n=8, result=27
# ... → n=1, result=55 → n=0: loop exits

print(result) # 55 (sum of 1 to 10)

Concept Explanation
Initial State State of variables before program begins execution
Current State Snapshot of all variable values at a specific program line
State Transition How one statement changes the state (assignment, loop, call)
Final State State of variables after the program completes
Invalid State A state where variables hold unexpected/wrong values (a bug)

★ End of UNIT I – Algorithmic Problem Solving ★

You might also like