CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Introduction to Problem Solving
4.1 Introduction
Computers are used in everyday activities because they can perform tasks quickly and accurately. For example, online railway reservation systems make it possible to search trains, check availability and book tickets from different locations.
A railway reservation system is a complex application. It must manage train details, train types, berth and compartment information, schedules, simultaneous bookings by many users, cancellations, payments and other related information.
Computerisation means using computers and software to automate routine human tasks efficiently. However, a computer cannot independently understand an unclear problem and invent the correct solution. It must receive precise, logical, step-by-step instructions from a programmer.
The success of a computer-based solution depends on three things:
- Defining the problem correctly and precisely.
- Designing a suitable solution, called an algorithm.
- Implementing the algorithm as a program using a programming language.
4.2 Steps for Problem Solving
Solving a problem usually requires multiple stages. The textbook compares this with a vehicle making an unusual noise: identify the source, analyse the issue, plan the repair, carry out the repair and check that the problem has been resolved.
The first four stages are the main development activities. Maintenance continues after delivery whenever corrections, user support or improvements are required.
4.2.1 Analysing the Problem
Before writing an algorithm or program, understand exactly what needs to be solved. A misunderstanding at this stage may result in software that does not meet the user's requirement.
Read the problem statement carefully and identify its principal components and required functionality. The most useful starting framework is IPO: Input – Process – Output.
| Component | Question to ask | Example: area of a rectangle |
|---|---|---|
| Input | What information must the user provide? | Length and breadth. |
| Process | What calculation or operation is required? | Multiply length by breadth. |
| Output | What result should be displayed? | Area of the rectangle. |
Why is analysis important? It clarifies the input data, expected output, processing rules, special cases and constraints before implementation begins.
4.2.2 Developing an Algorithm and 4.3 Algorithm
After analysing the problem, design a solution before writing program code. This solution can first be described in natural language as a sequence of steps. Such a step-by-step solution is an algorithm.
An algorithm has a definite beginning, a definite end and a finite number of steps. It should produce the desired result when the steps are followed correctly.
Example: Finding the GCD of 45 and 54
GCD (Greatest Common Divisor) is the largest positive integer that divides both numbers without leaving a remainder.
| Divisors of 45 | 1, 3, 5, 9, 15, 45 |
|---|---|
| Divisors of 54 | 1, 2, 3, 6, 9, 18, 27, 54 |
| Common divisors | 1, 3, 9 |
| Greatest common divisor | 9 |
Therefore, GCD(45, 54) = 9.
Algorithm to find the GCD using repeated remainder (Euclidean method)
Step 1: INPUT A, B
Step 2: WHILE B is not equal to 0
R = A MOD B
A = B
B = R
Step 3: PRINT A as the GCD
Dry run: (A, B) = (45, 54) → (54, 45) → (45, 9) → (9, 0). The answer is 9.
4.3.1 Why do we need an algorithm?
- It acts as a roadmap before coding begins.
- It helps the programmer understand the logic and order of instructions.
- It makes it easier to detect missing or incorrect steps before implementation.
- It supports reliability, accuracy and efficiency.
- It separates the problem-solving logic from the syntax of a particular programming language.
Algorithms are used behind search engines, messaging applications, document search, taxi booking, online banking and computer games.
Characteristics of a good algorithm
| Characteristic | Explanation | Example / meaning |
|---|---|---|
| Precision | Every step is stated clearly and exactly. | “Add A and B” is clearer than “do the calculation”. |
| Uniqueness / Definiteness | Each step has an unambiguous meaning and its result depends on the input and preceding steps. | A step should not have two possible interpretations. |
| Finiteness | The algorithm must stop after a finite number of steps. | A loop must eventually terminate for valid input. |
| Input | It accepts zero or more clearly defined inputs, as required by the problem. | Two numbers for addition. |
| Output | It produces at least one desired result. | The sum of the two numbers. |
4.2.3 Coding, 4.2.4 Testing and Debugging, and Maintenance
4.2.3 Coding
Once the algorithm is finalised, translate it into instructions written in a programming language understood by the development tools. High-level languages such as Python, C, C++ and Java can be used. Record important coding decisions and document the program so that it can be understood and modified later.
4.2.4 Testing and Debugging
Testing checks whether the program meets user requirements, produces correct results for different valid inputs and responds within an acceptable time.
- Syntax errors: violations of the programming language's grammar. They commonly prevent a program from running successfully.
- Logical errors: the program runs but produces an incorrect result because the logic or formula is wrong.
- Debugging: finding, analysing and correcting errors or defects.
| Testing type | Purpose |
|---|---|
| Unit / Component testing | Tests an individual function, module or component. |
| Integration testing | Checks whether combined components work correctly together. |
| System testing | Tests the complete integrated application. |
| Acceptance testing | Checks whether the application meets user or business requirements. |
Testing and debugging are repeated until important defects are resolved and the software behaves as expected.
Maintenance
After the software has been developed, tested and delivered, maintenance may still be required. It includes fixing problems reported by users, answering queries and adding or modifying features when requirements change.
4.4 Representation of Algorithms
After identifying the logical steps, programmers must write them in a clear form that shows the input, processing, output and control flow. The chapter introduces two common methods:
Flowchart
A graphical or visual representation using standard symbols connected by arrows.
Pseudocode
A structured, human-readable description of the instructions in a programming-like format.
Both methods should show the logic of the solution without tying it to implementation details of a particular programming language. They should also make the flow of control clear.
4.4.1 Flowchart — Visual Representation of Algorithms
A flowchart is a diagrammatic representation of an algorithm. It consists of standard shapes connected by arrows. Each shape represents an operation or step; arrows indicate the order in which the steps are followed.
Standard flowchart symbols (Table 4.1)
| Symbol name | Usual shape | Purpose |
|---|---|---|
| Start / End (Terminator) | Oval or rounded rectangle | Indicates where the flowchart begins or ends. |
| Process / Action | Rectangle | Represents a calculation, assignment or processing step. |
| Decision | Diamond | Checks a condition and branches, usually into Yes/No or True/False paths. |
| Input / Output (Data) | Parallelogram | Accepts input or displays output. |
| Arrow / Flow line | Directed line | Shows the direction and order of execution. |
Example 4.1: Flow of an algorithm to find the square of a number
IPO analysis: Input = number; Process = multiply number by itself; Output = square.
START
INPUT num
square = num * num
PRINT square
END
(Terminator)→INPUT num
(Input)→square = num × num
(Process)→PRINT square
(Output)→END
Example 4.2: Non-functioning light bulb
The textbook's flowchart on printed page 67 models troubleshooting a bulb using decisions. A clear text equivalent is:
↓ If power is OFF, turn it ON and test again. If power is ON, check the bulb.
If bulb is not fused, inspect wiring or seek an electrician. End after the fault is resolved safely.
4.4.2 Pseudocode
Pseudocode is a non-formal, human-readable way of representing an algorithm. It describes the instructions a computer should follow in a particular order, but it is not directly executable by a computer.
The word “pseudo” means “not real”; pseudocode resembles code but does not follow the complete syntax rules of a particular programming language. There is no single compulsory standard for writing it.
Frequently used pseudocode keywords
| Keyword | Meaning |
|---|---|
| INPUT | Accept a value from the user. |
| COMPUTE | Perform a calculation. |
| Display a result or message. | |
| INCREMENT | Increase a value, commonly by 1. |
| DECREMENT | Decrease a value, commonly by 1. |
| IF / ELSE | Choose an action according to a condition. |
| WHILE | Repeat instructions while a condition is true. |
| TRUE / FALSE | Logical values representing whether a condition holds. |
Example 4.3: Sum of two numbers
INPUT num1
INPUT num2
COMPUTE result = num1 + num2
PRINT result
For example, if num1 = 12 and num2 = 8, result = 12 + 8 = 20.
Example 4.4: Area and perimeter of a rectangle
INPUT length
INPUT breadth
COMPUTE Area = length * breadth
PRINT Area
COMPUTE Perim = 2 * (length + breadth)
PRINT Perim
Worked example: length = 8 cm, breadth = 5 cm. Area = 8 × 5 = 40 cm². Perimeter = 2 × (8 + 5) = 26 cm.
Benefits of pseudocode
- It helps plan the basic functionality before writing high-level language code.
- It reduces the chance of forgetting an important step.
- It is easier for non-programmers to read and review than a full program.
- It allows the logic to be discussed without depending on one programming language.
4.5 Flow of Control
Flow of control describes the order in which the steps or statements of an algorithm are executed. The chapter introduces three basic control structures:
Sequence
Execute instructions one after another.
Selection
Choose a path according to a condition.
Repetition
Repeat a set of instructions using a loop.
4.5.1 Sequence
In a sequence, statements execute one after another in the order in which they are written. There is no branching or repetition in the basic sequence.
Example: Calculate total price
INPUT price
INPUT quantity
total = price * quantity
PRINT total
If price = ₹25 and quantity = 4, total = ₹25 × 4 = ₹100. The input statements execute first, then the calculation, and finally the output statement.
4.5.2 Selection — Decision Making / Conditionals
Sometimes an algorithm must perform different actions depending on the outcome of a condition. This is called selection or decision making. A condition evaluates to one of two logical values: True or False.
Examples include choosing a route based on traffic, checking voting eligibility based on age, or grouping a student according to age and preference.
Basic IF structure
IF condition THEN
instructions to execute when condition is TRUE
END IF
IF–ELSE structure
IF condition THEN
instructions when condition is TRUE
ELSE
instructions when condition is FALSE
END IF
Python syntax equivalent
if condition:
statement_if_true
else:
statement_if_false
In Python, indentation defines the block of statements belonging to the if or else clause.
Example 4.5: Check whether a number is even or odd
A number is even if it is exactly divisible by 2. The remainder operator is called MOD in pseudocode and % in Python.
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Number is Even"
ELSE
PRINT "Number is Odd"
END IF
# Python equivalent
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Number is Even")
else:
print("Number is Odd")
Example: 18 MOD 2 = 0, so 18 is even. 13 MOD 2 = 1, so 13 is odd.
Example 4.6: Multiple conditions — Child, Teenager or Adult
- Child: age less than 13.
- Teenager: age at least 13 but less than 20.
- Adult: age 20 or more.
INPUT Age
IF Age < 13 THEN
PRINT "Child"
ELSE IF Age < 20 THEN
PRINT "Teenager"
ELSE
PRINT "Adult"
END IF
# Python equivalent
age = int(input("Enter age: "))
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
Notice that the second condition only needs to check age < 20, because if execution reaches it, the first condition has already established that age is 13 or more.
| Age | Output | Reason |
|---|---|---|
| 8 | Child | 8 < 13 |
| 13 | Teenager | 13 is not below 13, but is below 20 |
| 19 | Teenager | 19 < 20 |
| 20 | Adult | 20 is not below 20 |
Logical operators: AND and OR
| Operator | Meaning | Example |
|---|---|---|
| AND | True only when both conditions are true. | age >= 18 AND citizen = TRUE |
| OR | True when at least one condition is true. | shape = diamond OR shape = club |
| NOT | Reverses a logical value. | NOT is_valid |
Example 4.7: Dragons and Wizards card game
Two teams score points according to the card drawn:
- Diamond or club: Dragons score.
- Heart with a number: Wizards score.
- Heart that is not a number card (for example, a face card): Dragons score.
- Any other card: Wizards score.
- The team with the higher score wins.
INPUT shape
INPUT value
SET Dpoint = 0, Wpoint = 0
IF shape is diamond OR shape is club THEN
INCREMENT Dpoint
ELSE IF shape is heart AND value is a number THEN
INCREMENT Wpoint
ELSE IF shape is heart AND value is not a number THEN
INCREMENT Dpoint
ELSE
INCREMENT Wpoint
END IF
IF Dpoint > Wpoint THEN
PRINT "Dragon team is the winner"
ELSE
PRINT "Wizard team is the winner"
END IF
The textbook example illustrates how multiple conditions are combined with AND and OR. When playing multiple rounds, the scores must be retained and incremented for each card.
4.5.3 Repetition — Iteration / Loops
When a set of statements must execute repeatedly, the algorithm uses repetition, also called iteration or a loop. A loop repeats instructions while a specified condition is satisfied.
Examples: clap five times, walk ten steps, withdraw ten cards, or keep accepting values until the user enters a stop value.
WHILE loop structure
WHILE condition is TRUE
repeat these instructions
END WHILE
# Python syntax
while condition:
statements_to_repeat
A loop needs a condition that can eventually become false. If the condition never becomes false, an infinite loop may occur.
Example 4.8: Accept five numbers and calculate their average
Because the number of inputs is known (five), use a counter. Initialise count and sum to zero, then repeat input and addition five times.
Step 1: SET count = 0, sum = 0
Step 2: WHILE count < 5
INPUT num
sum = sum + num
count = count + 1
Step 3: average = sum / 5
Step 4: PRINT average
Worked example: Inputs are 10, 20, 30, 40 and 50.
| Iteration | Input num | Updated sum | Updated count |
|---|---|---|---|
| 1 | 10 | 10 | 1 |
| 2 | 20 | 30 | 2 |
| 3 | 30 | 60 | 3 |
| 4 | 40 | 100 | 4 |
| 5 | 50 | 150 | 5 |
Average = 150 ÷ 5 = 30.
Python implementation
count = 0
total = 0
while count < 5:
num = float(input("Enter a number: "))
total = total + num
count = count + 1
average = total / 5
print("Average =", average)
Example 4.9: Accept numbers until the user enters 0
Here the number of values is not known in advance. The value 0 is a sentinel value — a special value that signals the end of input. It is not included in the sum or count.
SET count = 0, sum = 0
INPUT num
WHILE num is not equal to 0
sum = sum + num
count = count + 1
INPUT num
END WHILE
IF count > 0 THEN
average = sum / count
PRINT average
ELSE
PRINT "No numbers were entered"
END IF
Why is INPUT used twice? The first INPUT obtains the initial value before the loop begins. The second INPUT obtains the next value at the end of each iteration; otherwise the loop would keep checking the same value forever.
Activity 4.4 – Worked answers
Given inputs: 6, 7, 4, 8, 2, 5, 0, 3, 1. The algorithm stops as soon as it reads 0. Values after 0 are not processed.
| Question | Answer |
|---|---|
| 1. What is the sum? | 6 + 7 + 4 + 8 + 2 + 5 = 32. |
| 2. What is count? | 6, because six non-zero numbers were processed. |
| 3. Why input num twice? | To read the first value before the loop and then read a new value in each iteration. |
| 4. Why divide sum by count? | Average = total of accepted values ÷ number of accepted values. |
| 5. Another approach? | Use a list to collect all non-zero values, then calculate its sum divided by its length. A loop with a sentinel remains suitable when the count is unknown. |
4.6 Verifying Algorithms
Verification checks whether an algorithm works correctly for the required inputs and produces the expected output. It is especially important in banking, medicine, space systems and other applications where an incorrect result can have serious consequences.
Dry run
A dry run is the manual execution of an algorithm using selected input values. The programmer follows each step and records how variables change, then checks whether the final result is correct.
Dry runs help to:
- Identify incorrect steps or logic.
- Find missing details and special cases.
- Check that the algorithm handles different categories of input.
- Improve the algorithm before coding.
Example: Verify the sum of first N natural numbers
For N = 6, direct addition gives 1 + 2 + 3 + 4 + 5 + 6 = 21. Using the formula: 6 × 7 ÷ 2 = 21. Both results agree.
Textbook example: Add two journey times
Suppose a journey has two parts, T1 and T2. Each time is represented as hours and minutes. A first attempt adds hours and minutes separately.
| Journey | Naive addition | Problem / correct result |
|---|---|---|
| 5 h 20 min + 7 h 30 min | 12 h 50 min | Correct because minutes are below 60. |
| 4 h 50 min + 2 h 20 min | 6 h 70 min | Incorrect representation. Correct result is 7 h 10 min. |
The second test case exposes a missing carry operation. If total minutes are at least 60, add one to the hours and subtract 60 from the minutes.
INPUT hh1, mm1
INPUT hh2, mm2
hh_total = hh1 + hh2
mm_total = mm1 + mm2
IF mm_total >= 60 THEN
hh_total = hh_total + 1
mm_total = mm_total - 60
END IF
PRINT hh_total, "hours", mm_total, "minutes"
Dry run: hh_total = 4 + 2 = 6; mm_total = 50 + 20 = 70. Since 70 ≥ 60, hours = 6 + 1 = 7 and minutes = 70 − 60 = 10. Result = 7 hours 10 minutes.
Activity 4.5 – Rectangle measurements in feet and inches
Convert each measurement to inches, calculate area and perimeter, then report the units correctly. Let length = L feet and Lin inches; breadth = B feet and Bin inches.
length_inches = L * 12 + Lin
breadth_inches = B * 12 + Bin
area_square_inches = length_inches * breadth_inches
perimeter_inches = 2 * (length_inches + breadth_inches)
For example, if length = 5 ft 6 in and breadth = 3 ft 0 in: length = 66 in, breadth = 36 in; area = 2,376 in²; perimeter = 2 × (66 + 36) = 204 in. Convert to square feet or feet/inches if the question requires those units.
4.7 Comparison of Algorithms
A problem may have multiple correct algorithms. The best choice depends on how much processing time and memory each algorithm requires.
Example: Checking whether a number is prime
A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.
The textbook discusses four approaches:
| Method | Divisors tested | Efficiency / trade-off |
|---|---|---|
| (i) Test up to n − 1 | Check every integer from 2 up to n − 1. | Simple but performs many calculations. |
| (ii) Test up to n ÷ 2 | Check divisors only up to half the number. | More efficient than method (i); no divisor greater than n/2 can divide n except n itself. |
| (iii) Test up to √n | Check divisors from 2 through the square root of n. | More efficient: if n has a factor greater than √n, it must have a corresponding factor smaller than √n. |
| (iv) Use a stored prime list | Test divisibility using previously stored prime numbers. | Can reduce calculations, but requires storing and maintaining the prime list. |
Why is checking up to the square root enough?
If a number n = a × b and both a and b were greater than √n, their product would be greater than n. Therefore, at least one factor must be less than or equal to √n. If no divisor is found up to √n, no larger divisor pair exists.
Time complexity and space complexity
Time Complexity
Describes how the amount of processing work or running time grows as the input size increases.
Space Complexity
Describes how much memory an algorithm needs as the input size increases.
Algorithm selection involves balancing both. A method that uses less time may require extra memory; a method that uses less memory may take more processing time.
Illustrative efficient prime-checking pseudocode
INPUT n
IF n <= 1 THEN
PRINT "Not prime"
ELSE
divisor = 2
is_prime = TRUE
WHILE divisor * divisor <= n
IF n MOD divisor == 0 THEN
is_prime = FALSE
BREAK
END IF
divisor = divisor + 1
END WHILE
IF is_prime THEN
PRINT "Prime"
ELSE
PRINT "Not prime"
END IF
END IF
The use of a square-root boundary is the key efficiency improvement described in the chapter. The BREAK statement is an implementation convenience in this illustrative pseudocode.
4.8 Coding
After an algorithm has been finalised, it is translated into a high-level programming language. The programmer writes an ordered set of instructions by following the language's syntax.
Syntax
Syntax is the set of rules or grammar that governs how statements in a programming language must be written. It includes spelling of keywords, order of elements, punctuation, brackets and indentation rules.
# Correct Python syntax
number = int(input("Enter a number: "))
square = number * number
print(square)
# Incorrect Python syntax example
if number > 0
print("Positive")
The incorrect example is missing the colon (:) after the condition. Python reports a syntax error.
Low-level language and high-level language
| Basis | Low-level language | High-level language |
|---|---|---|
| Form | Machine language (binary 0s and 1s) or assembly language. | Uses statements and structures closer to human-readable language. |
| Understanding | Difficult for humans to read and write. | Easier to read, write and maintain. |
| Hardware dependence | Machine code is hardware-specific; assembly is generally processor-family specific. | Generally more portable across platforms, subject to compiler/interpreter and library support. |
| Translation | Machine language is directly executed by hardware; assembly is translated by an assembler. | Translated or executed using a compiler or interpreter (or a combination). |
| Examples | Binary machine instructions, assembly language. | FORTRAN, C, C++, Java, Python. |
Machine language consists of binary instructions understood by the computer hardware, but is difficult for humans to work with. High-level languages are designed to make program development and maintenance easier.
Source code, compiler and interpreter
- Source code: a program written by a programmer in a high-level language.
- Compiler: translates source code into target code (commonly machine code or another lower-level form) before execution.
- Interpreter: executes a program by interpreting its instructions, often during runtime.
Choosing a programming language
The suitable language depends on the target platform, operating system, hardware, application type, available tools and project requirements.
- Desktop applications: developed for desktop operating systems and hardware.
- Mobile applications: developed for mobile operating systems and device capabilities.
- Web applications: accessed through web browsers on different devices and may use cloud resources.
- Embedded systems: programs for devices such as digital watches, MP3 players, traffic signals, vehicles, medical equipment and smart devices. Specialised tools or assembly language may sometimes be used.
4.9 Decomposition
A complex problem may not have an obvious direct solution. Decomposition means breaking a large problem into smaller, simpler sub-problems, solving each part and combining the results into a complete solution.
The textbook uses a railway reservation system as its main example. Instead of designing the entire system as one enormous task, divide it into components.
Days, timings, stations, classes and berths
Booking open/closed, availability, waiting list, cancellation and refund
Railway personnel and physical resources
Catering and onboard services
Fare calculation and payment
Additional supporting information
Benefits of decomposition
- Smaller problems are easier to understand and solve.
- Each sub-problem can be analysed in detail.
- Different people or teams can work independently on different components.
- Specialist teams can be assigned tasks that match their expertise.
- Testing individual components is easier before integration.
After each sub-problem is solved, test it for correctness and integrate the components logically to create the complete solution.
Other examples
- School event management: registration, venue, timetable, food, finance and communication.
- Weather forecasting: data collection, data cleaning, modelling, prediction and reporting.
- Delivery management: order management, warehouse, route planning, delivery tracking and billing.
- Scientific or mathematical problems: divide a large calculation into smaller operations.
Chapter Summary
- Problem solving identifies a problem, designs an algorithm and implements it as a program.
- The main stages are analysis, algorithm development, coding, testing/debugging and maintenance.
- GIGO means the quality of output depends on the quality of input.
- An algorithm is a finite, precise sequence of steps with a definite beginning and end.
- A good algorithm has precision, uniqueness/definiteness, finiteness, input and output.
- Algorithms can be represented using flowcharts or pseudocode.
- Flowcharts use terminator, process, decision, input/output and arrow symbols.
- Flow of control includes sequence, selection and repetition.
- Dry runs help verify algorithms using different input values.
- Algorithms are compared using time complexity and space complexity.
- High-level source code must be translated or interpreted for computer execution.
- Decomposition divides a complex problem into smaller sub-problems.
Textbook Exercise – All 18 Questions with Detailed Solutions
Solutions below explain the logic and include pseudocode. Where useful, Python equivalents are added to connect the algorithm to programming. For questions with boundary ambiguities, the assumptions are stated explicitly.
We must check that the divisor is not zero because division by zero is undefined.
INPUT numerator
INPUT denominator
IF denominator != 0 THEN
quotient = numerator / denominator
PRINT quotient
ELSE
PRINT "Division by zero is not allowed"
END IFExample: numerator = 20 and denominator = 4. Quotient = 20 ÷ 4 = 5.
# Python
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
if b != 0:
print("Quotient =", a / b)
else:
print("Division by zero is not allowed")Maintain separate scores. After each flip, increase the relevant score. Stop as soon as either player reaches three wins or after five flips.
SET score1 = 0, score2 = 0
SET flips = 0
WHILE flips < 5 AND score1 < 3 AND score2 < 3
INPUT winner
IF winner == 1 THEN
score1 = score1 + 1
ELSE IF winner == 2 THEN
score2 = score2 + 1
ELSE
PRINT "Enter only 1 or 2"
CONTINUE
END IF
flips = flips + 1
END WHILE
IF score1 >= 3 THEN
PRINT "Player 1 wins the cake"
ELSE IF score2 >= 3 THEN
PRINT "Player 2 wins the cake"
ELSE
PRINT "No player reached three wins"
END IFExample: Inputs 1, 2, 1, 1 → Player 1 reaches three wins on the fourth flip and wins. No further flips are needed.
number = 10
WHILE number <= 25
PRINT number
number = number + 5
END WHILEOutput: 10, 15, 20, 25.
# Python
for number in range(10, 26, 5):
print(number)range(10, 26, 5) begins at 10, increases by 5 and stops before 26, so 25 is included.
Example: Display “Welcome” ten times. The number of repetitions is known in advance.
SET count = 1
WHILE count <= 10
PRINT "Welcome"
count = count + 1
END WHILEOther examples include accepting marks for five subjects or printing the multiplication table of a number from 1 to 10.
Use a running total and continue accepting contributions until the total is at least ₹200. The last contribution may make the total exceed ₹200.
SET total = 0
WHILE total < 200
INPUT amount
IF amount == 10 OR amount == 20 OR amount == 50 THEN
total = total + amount
PRINT "Current collection =", total
ELSE
PRINT "Accept only 10, 20 or 50"
END IF
END WHILE
PRINT "Target reached. Total =", totalExample: ₹50 + ₹20 + ₹50 + ₹50 + ₹50 = ₹220. The collection stops when the total first reaches or exceeds ₹200.
First calculate the amount before tax, then calculate GST as 5% of that amount, then add it to the total.
INPUT price
INPUT quantity
subtotal = price * quantity
gst = subtotal * 5 / 100
final_bill = subtotal + gst
PRINT "Subtotal =", subtotal
PRINT "GST (5%) =", gst
PRINT "Final bill =", final_billExample: Price = ₹200, quantity = 3. Subtotal = ₹600; GST = ₹30; final bill = ₹630.
Maximum aggregate = 100 + 100 + 100 = 300.
INPUT CS
INPUT Maths
INPUT Physics
aggregate = CS + Maths + Physics
percentage = (aggregate / 300) * 100
PRINT "Aggregate =", aggregate, "out of 300"
PRINT "Percentage =", percentage, "%"Example: CS = 85, Maths = 90, Physics = 75. Aggregate = 250/300. Percentage = 250 ÷ 300 × 100 = 83.33%.
INPUT A
INPUT B
IF A > B THEN
PRINT A, "is greater"
ELSE
PRINT B, "is greater"
END IFThe question specifies two different numbers, so equality does not need to be handled. Example: A = 17 and B = 12 → 17 is greater.
The printed intervals share boundary values 15 and 25. To avoid assigning one boundary to two colours, use non-overlapping ranges: 5 to 15 inclusive, greater than 15 to 25 inclusive, and greater than 25 to 35 inclusive.
INPUT number
IF number >= 5 AND number <= 15 THEN
PRINT "GREEN"
ELSE IF number > 15 AND number <= 25 THEN
PRINT "BLUE"
ELSE IF number > 25 AND number <= 35 THEN
PRINT "ORANGE"
ELSE
PRINT "ALL COLOURS ARE BEAUTIFUL"
END IFExamples: 5 → GREEN; 15 → GREEN; 16 → BLUE; 25 → BLUE; 30 → ORANGE; 40 → ALL COLOURS ARE BEAUTIFUL.
Initially assume the first number is both the largest and smallest. Compare each remaining number and update the values when needed.
INPUT A, B, C, D
largest = A
smallest = A
IF B > largest THEN
largest = B
END IF
IF C > largest THEN
largest = C
END IF
IF D > largest THEN
largest = D
END IF
IF B < smallest THEN
smallest = B
END IF
IF C < smallest THEN
smallest = C
END IF
IF D < smallest THEN
smallest = D
END IF
PRINT "Largest =", largest
PRINT "Smallest =", smallestExample: 18, 7, 42, 11 → Largest = 42; Smallest = 7.
Interpret the rates as progressive slabs: each rate applies only to the units in its slab.
| Units consumed | Calculation of energy charge |
|---|---|
| 0–100 | All units × ₹5 |
| 101–250 | ₹500 + (units − 100) × ₹10 |
| Above 250 | ₹500 + ₹1,500 + (units − 250) × ₹20 |
INPUT units
IF units <= 100 THEN
charge = units * 5
ELSE IF units <= 250 THEN
charge = 100 * 5 + (units - 100) * 10
ELSE
charge = 100 * 5 + 150 * 10
+ (units - 250) * 20
END IF
total_bill = charge + 75
PRINT "Water bill =", total_billWorked example: 300 units
- First 100 units: 100 × 5 = ₹500.
- Next 150 units: 150 × 10 = ₹1,500.
- Remaining 50 units: 50 × 20 = ₹1,000.
- Energy charge = ₹500 + ₹1,500 + ₹1,000 = ₹3,000.
- Meter charge = ₹75.
Total bill = ₹3,075.
Conditionals are statements that allow an algorithm or program to make decisions. They evaluate a condition as True or False and execute the appropriate set of instructions.
They are required when a program must choose between alternatives, for example checking whether a number is even or odd, deciding whether a student has passed, checking voting eligibility or assigning a category based on age.
IF condition THEN
action_when_true
ELSE
action_when_false
END IF| Flowchart symbol | Correct function |
|---|---|
| Arrow / Flow line | Flow of Control |
| Rectangle | Process Step |
| Oval / Terminator | Start/Stop of the Process |
| Parallelogram | Data (Input/Output) |
| Diamond | Decision Making |
Remember: rectangle = process; diamond = decision; parallelogram = input/output; oval = start/end; arrow = flow direction.
The original algorithm assumes that everyone travels by bus. A better algorithm includes a decision based on the available mode of transport.
START
Wake up
Get ready
Take lunch box and school bag
IF walking is the chosen mode THEN
Walk to school
ELSE IF bicycle is the chosen mode THEN
Take bicycle and ride safely
ELSE IF bus is the chosen mode THEN
Go to bus stop
Wait for bus
Board the correct bus
Get off at the school stop
ELSE IF car is the chosen mode THEN
Travel by car
ELSE
PRINT "Choose a valid mode of transport"
END IF
Reach school / college
ENDOther improvements may include checking the timetable, carrying an ID card, checking weather conditions, allowing extra travel time and following road-safety rules.
For a positive integer n, factorial is the product of all integers from 1 to n. By definition, 0! = 1.
INPUT n
IF n < 0 THEN
PRINT "Factorial is not defined for negative integers"
ELSE
factorial = 1
count = 1
WHILE count <= n
factorial = factorial * count
count = count + 1
END WHILE
PRINT factorial
END IFWorked example: n = 5. Start factorial = 1. Multiply by 1 → 1; by 2 → 2; by 3 → 6; by 4 → 24; by 5 → 120. Therefore 5! = 120. For n = 0, the loop does not execute and the result remains 1.
# Python
n = int(input("Enter a non-negative integer: "))
if n < 0:
print("Factorial is not defined")
else:
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial =", fact)A three-digit Armstrong number is a three-digit integer equal to the sum of the cubes of its digits.
Example: 371 = 3³ + 7³ + 1³ = 27 + 343 + 1 = 371. Therefore, 371 is an Armstrong number.
To extract digits: the hundreds digit is n // 100; tens digit is (n // 10) % 10; units digit is n % 10.
INPUT n
IF n < 100 OR n > 999 THEN
PRINT "Enter a three-digit positive integer"
ELSE
hundreds = n // 100
tens = (n // 10) MOD 10
units = n MOD 10
total = hundreds^3 + tens^3 + units^3
IF total == n THEN
PRINT "Armstrong number"
ELSE
PRINT "Not an Armstrong number"
END IF
END IFNO → Display invalid input → END
YES → Print Armstrong number. NO → Print Not Armstrong. Both paths → END.
Python implementation:
n = int(input("Enter a three-digit number: "))
if 100 <= n <= 999:
a = n // 100
b = (n // 10) % 10
c = n % 10
total = a**3 + b**3 + c**3
if total == n:
print("Armstrong number")
else:
print("Not an Armstrong number")
else:
print("Invalid input: enter a three-digit number")Given algorithm:
INPUT Number
IF Number < 9
PRINT "Single Digit"
ELSE IF Number < 99
PRINT "Double Digit"
ELSE
PRINT "Big"The original comparisons are incorrect at boundary values. For example, 9 is classified as double digit even though it is a single-digit number; 99 is classified as big even though it is a two-digit number.
| Input | Original output | Correct output |
|---|---|---|
| 5 | Single Digit | Single Digit |
| 9 | Double Digit | Single Digit |
| 47 | Double Digit | Double Digit |
| 99 | Big | Double Digit |
| 100 | Big | Big |
| 200 | Big | Big |
Corrected algorithm for non-negative integers:
INPUT Number
IF Number >= 0 AND Number <= 9 THEN
PRINT "Single Digit"
ELSE IF Number >= 10 AND Number <= 99 THEN
PRINT "Double Digit"
ELSE IF Number >= 100 THEN
PRINT "Big"
ELSE
PRINT "Negative number not covered"
END IFThe corrected ranges include 0–9, 10–99 and 100 or more. Negative values are explicitly handled rather than silently misclassified.
Given algorithm:
INPUT Number
IF (0 <= Number) AND (Number <= 100)
ACCEPT
ELSE
REJECT(a) On what values will it fail?
It accepts 0 even though the question requires positive integers. It also accepts decimal values such as 25.5 because the condition does not check whether the input is an integer. Therefore, it does not fully enforce the stated requirement.
(b) Improved algorithm:
INPUT Number
IF Number is an integer AND Number >= 1 AND Number <= 100 THEN
ACCEPT
ELSE
REJECT
END IFValid examples: 1, 25, 99, 100. Invalid examples: 0, −5, 101, 25.5.
Python equivalent:
value = input("Enter a positive integer from 1 to 100: ")
try:
number = int(value)
if 1 <= number <= 100:
print("ACCEPT")
else:
print("REJECT")
except ValueError:
print("REJECT: input must be an integer")Textbook Activities and Think-and-Reflect – Suggested Responses
Activity 4.1: What sequence of steps will you follow to compute the LCM of two numbers?
LCM (Least Common Multiple) is the smallest positive integer divisible by both numbers. One approach is to start from the larger number and increase until a number is divisible by both.
INPUT A, B
candidate = maximum(A, B)
WHILE candidate MOD A != 0 OR candidate MOD B != 0
candidate = candidate + 1
END WHILE
PRINT candidate as LCMExample: A = 12, B = 18. The smallest common multiple is 36.
Think and Reflect (page 67): What happens if an algorithm does not stop after a finite number of steps?
It may enter an infinite loop, keep consuming processing time and possibly other resources, and never produce the required final output. A well-designed algorithm should have a termination condition.
Activity 4.2: Draw a flowchart representing the attainment of your career goal.
Suggested stages: Start → identify career goal → research required qualifications → prepare a study plan → complete learning and practice → check progress → if requirements are met, apply for opportunities; otherwise improve skills and repeat the plan → End/continue professional development.
Activity 4.3: Write pseudocode for creating a hockey match scoreboard.
SET TeamA = 0, TeamB = 0
WHILE match is not over
INPUT scoring_team
IF scoring_team == "A" THEN
TeamA = TeamA + 1
ELSE IF scoring_team == "B" THEN
TeamB = TeamB + 1
END IF
PRINT TeamA, TeamB
END WHILE
IF TeamA > TeamB THEN
PRINT "Team A wins"
ELSE IF TeamB > TeamA THEN
PRINT "Team B wins"
ELSE
PRINT "Match tied"
END IF
Think and Reflect (page 70): List daily activities involving decision making.
Choosing clothes according to weather, selecting a route based on traffic, deciding whether to carry an umbrella, checking whether a student has enough marks to pass and deciding whether to recharge a travel card are everyday examples.
Think and Reflect (page 75): List activities involving repetition.
Brushing teeth with repeated strokes, walking several steps, counting objects, practising a musical scale, entering multiple student marks and repeating exercise movements are examples of iteration.
Think and Reflect (page 77): Why is algorithm verification important?
It helps find incorrect logic, missing steps and boundary-case failures before the algorithm is converted into a program. This reduces the cost of fixing mistakes and helps protect users from incorrect results.
Activity 4.5: Convert feet and inches to area and perimeter.
Convert both dimensions into inches first. One foot = 12 inches. Then calculate area = length × breadth and perimeter = 2 × (length + breadth). The worked example is provided in Section 4.6 above.
Quick Revision – Important Terms, Syntax and Exam Checklist
Important definitions
| Term | Remember |
|---|---|
| Problem solving | Identify problem → algorithm → program implementation. |
| GIGO | Garbage In, Garbage Out. |
| Algorithm | Finite, precise sequence of steps to solve a problem. |
| Flowchart | Graphical representation of an algorithm. |
| Pseudocode | Human-readable, non-executable description of algorithm steps. |
| Sequence | Statements execute one after another. |
| Selection | Choose a path using a condition. |
| Repetition | Repeat instructions using a loop. |
| Dry run | Manually execute an algorithm with selected inputs. |
| Time complexity | Growth in processing work with input size. |
| Space complexity | Memory required by an algorithm. |
| Source code | Program written in a programming language. |
| Decomposition | Break a complex problem into smaller sub-problems. |
Syntax patterns to remember
# Input and output in Python
x = input("Enter value: ")
print(x)
# Calculation
result = a + b
# Selection
if condition:
statement1
else:
statement2
# Multiple selection
if condition1:
statement1
elif condition2:
statement2
else:
statement3
# Repetition
count = 0
while count < 5:
# repeated statements
count += 1
# Modulus and integer division
remainder = number % 2
quotient = number // 10
Common examination mistakes
- Starting to code before clearly identifying input, process and output.
- Writing an algorithm with vague or ambiguous steps.
- Forgetting to update a loop counter or read a new value inside a sentinel-controlled loop.
- Dividing by zero when no values have been entered.
- Ignoring boundary values such as 9, 15, 25, 99 or 100.
- Confusing syntax errors with logical errors.
- Comparing algorithms only by speed and ignoring memory requirements.
- Forgetting that 0! = 1 and that factorial is not defined for negative integers.
- Failing to test special cases and invalid input.
Prepared from the supplied 26-page NCERT Class XI Computer Science PDF, Chapter 4 – “Introduction to Problem Solving”, printed textbook pages 61–86 (Reprint 2026–27). The chapter’s diagrams and tables have been explained in text form, including flowchart symbols, the light-bulb troubleshooting flow, control structures, average calculation, time addition, railway reservation decomposition and the complete exercise set.
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
IMPORTANT QUESTION
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.