Computer Science (Python) Chapter 4 4 Study Options Available

Introduction to Problem Solving

CHAPTER PDF

Complete curriculum textbook chapter document for reading and offline study.

NOTES

Complete conceptual breakdown, formulas, diagrams, and memory aids.

Class 11 Computer Science | Chapter 4 – Introduction to Problem Solving
Class XI · Computer Science · Chapter 4

Introduction to Problem Solving

Complete study notes covering the full 26-page chapter: problem-solving stages, algorithms, flowcharts, pseudocode, sequence, selection, loops, verification, algorithm efficiency, coding and decomposition — with worked examples, Python syntax and all 18 textbook exercise solutions.
NCERT Computer ScienceReprint 2026–27Pages 61–86 coveredMobile & tablet responsive

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.

Definition — Problem Solving: The process of identifying a problem, developing an algorithm to solve it and implementing that algorithm as a computer program.

The success of a computer-based solution depends on three things:

  1. Defining the problem correctly and precisely.
  2. Designing a suitable solution, called an algorithm.
  3. Implementing the algorithm as a program using a programming language.
Quotation in the textbook: A. Aho and J. Ullman describe computer science as a science of abstraction — creating an appropriate model for a problem and devising mechanisable techniques to solve it. In other words, the programmer identifies the essential features of a problem and develops a systematic solution.

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.

1. Analyse the problem→2. Develop an algorithm→3. Code→4. Test & debug→5. Maintain

The first four stages are the main development activities. Maintenance continues after delivery whenever corrections, user support or improvements are required.

GIGO — Garbage In, Garbage Out: The correctness of a computer's output depends on the correctness and suitability of the input supplied. Incorrect input can lead to incorrect or misleading output even when the program itself is functioning as designed.

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.

ComponentQuestion to askExample: area of a rectangle
InputWhat information must the user provide?Length and breadth.
ProcessWhat calculation or operation is required?Multiply length by breadth.
OutputWhat result should be displayed?Area of the rectangle.
Area = Length × Breadth

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.

Definition — Algorithm: A finite sequence of exact and unambiguous steps which, when followed correctly, solves a problem or accomplishes a required task.

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 451, 3, 5, 9, 15, 45
Divisors of 541, 2, 3, 6, 9, 18, 27, 54
Common divisors1, 3, 9
Greatest common divisor9

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

CharacteristicExplanationExample / meaning
PrecisionEvery step is stated clearly and exactly.“Add A and B” is clearer than “do the calculation”.
Uniqueness / DefinitenessEach step has an unambiguous meaning and its result depends on the input and preceding steps.A step should not have two possible interpretations.
FinitenessThe algorithm must stop after a finite number of steps.A loop must eventually terminate for valid input.
InputIt accepts zero or more clearly defined inputs, as required by the problem.Two numbers for addition.
OutputIt produces at least one desired result.The sum of the two numbers.
Before writing an algorithm, identify: (1) Input from the user, (2) processing or computation, and (3) output required by the user.

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 typePurpose
Unit / Component testingTests an individual function, module or component.
Integration testingChecks whether combined components work correctly together.
System testingTests the complete integrated application.
Acceptance testingChecks 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.

Development cycle: Analyse → Design algorithm → Code → Test → Debug → Deliver → Maintain. In practice, developers may revisit earlier stages when testing reveals a design or requirement problem.

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 nameUsual shapePurpose
Start / End (Terminator)Oval or rounded rectangleIndicates where the flowchart begins or ends.
Process / ActionRectangleRepresents a calculation, assignment or processing step.
DecisionDiamondChecks a condition and branches, usually into Yes/No or True/False paths.
Input / Output (Data)ParallelogramAccepts input or displays output.
Arrow / Flow lineDirected lineShows 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
START
(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:

START→Bulb not glowing→Check switch / power

↓ If power is OFF, turn it ON and test again. If power is ON, check the bulb.

Bulb fused?→ Yes →Replace bulb→Test light

If bulb is not fused, inspect wiring or seek an electrician. End after the fault is resolved safely.

Safety note: This is a logical troubleshooting example. Electrical wiring should be inspected by a qualified person; do not touch exposed wires or electrical components.

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

KeywordMeaning
INPUTAccept a value from the user.
COMPUTEPerform a calculation.
PRINTDisplay a result or message.
INCREMENTIncrease a value, commonly by 1.
DECREMENTDecrease a value, commonly by 1.
IF / ELSEChoose an action according to a condition.
WHILERepeat instructions while a condition is true.
TRUE / FALSELogical 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

Area = length × breadth
Perimeter = 2 × (length + breadth)
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.

Input price→Input quantity→Calculate total→Print total

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.

AgeOutputReason
8Child8 < 13
13Teenager13 is not below 13, but is below 20
19Teenager19 < 20
20Adult20 is not below 20

Logical operators: AND and OR

OperatorMeaningExample
ANDTrue only when both conditions are true.age >= 18 AND citizen = TRUE
ORTrue when at least one condition is true.shape = diamond OR shape = club
NOTReverses 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.

IterationInput numUpdated sumUpdated count
110101
220302
330603
4401004
5501505

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.

QuestionAnswer
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.
Important edge case: If the first value is 0, count remains 0. Do not divide by zero; display a message that no numbers were entered.

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:

  1. Identify incorrect steps or logic.
  2. Find missing details and special cases.
  3. Check that the algorithm handles different categories of input.
  4. Improve the algorithm before coding.

Example: Verify the sum of first N natural numbers

Sum = N × (N + 1) ÷ 2

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.

JourneyNaive additionProblem / correct result
5 h 20 min + 7 h 30 min12 h 50 minCorrect because minutes are below 60.
4 h 50 min + 2 h 20 min6 h 70 minIncorrect 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.

Why test multiple cases? The first test (5 h 20 min + 7 h 30 min) did not reveal the defect. The second test, where minutes exceed 59, revealed the missing carry. Good verification includes ordinary values, boundary values and unusual cases.

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:

MethodDivisors testedEfficiency / trade-off
(i) Test up to n − 1Check every integer from 2 up to n − 1.Simple but performs many calculations.
(ii) Test up to n ÷ 2Check 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 √nCheck 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 listTest 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

BasisLow-level languageHigh-level language
FormMachine language (binary 0s and 1s) or assembly language.Uses statements and structures closer to human-readable language.
UnderstandingDifficult for humans to read and write.Easier to read, write and maintain.
Hardware dependenceMachine code is hardware-specific; assembly is generally processor-family specific.Generally more portable across platforms, subject to compiler/interpreter and library support.
TranslationMachine language is directly executed by hardware; assembly is translated by an assembler.Translated or executed using a compiler or interpreter (or a combination).
ExamplesBinary 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.
Programmer writes source code→Compiler / Interpreter→Execution by computer→Output

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.

Railway Reservation System
Train information
Days, timings, stations, classes and berths
Reservation information
Booking open/closed, availability, waiting list, cancellation and refund
Staff, security and infrastructure
Railway personnel and physical resources
Food service
Catering and onboard services
Billing service
Fare calculation and payment
Other railway details
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.
Key phrase: Divide and conquer — break a complex problem into simpler problems, solve them, and combine their results.

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.

Q1. Write pseudocode that reads two numbers and divides one by another and displays the quotient.

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 IF

Example: 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")
Q2. Two friends decide who gets the last slice of cake by flipping a coin five times. The first person to win three flips wins. Input 1 means Player 1 wins a flip and 2 means Player 2 wins. Design an algorithm to determine who takes the cake.

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 IF

Example: Inputs 1, 2, 1, 1 → Player 1 reaches three wins on the fourth flip and wins. No further flips are needed.

Q3. Write pseudocode to print all multiples of 5 between 10 and 25, including both 10 and 25.
number = 10
WHILE number <= 25
    PRINT number
    number = number + 5
END WHILE

Output: 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.

Q4. Give an example of a loop that is to be executed a certain number of times.

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 WHILE

Other examples include accepting marks for five subjects or printing the multiplication table of a number from 1 to 10.

Q5. You need to collect ₹200. Different relatives may give ₹10, ₹20 or ₹50. Write an algorithm to collect until the total becomes 200.

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 =", total

Example: ₹50 + ₹20 + ₹50 + ₹50 + ₹50 = ₹220. The collection stops when the total first reaches or exceeds ₹200.

Q6. Write pseudocode to print the bill depending on price and quantity. Also print the bill after adding 5% GST.

First calculate the amount before tax, then calculate GST as 5% of that amount, then add it to the total.

Subtotal = Price × Quantity
GST = Subtotal × 5 ÷ 100
Final Bill = Subtotal + GST
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_bill

Example: Price = ₹200, quantity = 3. Subtotal = ₹600; GST = ₹30; final bill = ₹630.

Q7. Write pseudocode to read marks in Computer Science, Mathematics and Physics (each out of 100), calculate aggregate marks and percentage.

Maximum aggregate = 100 + 100 + 100 = 300.

Percentage = (Aggregate ÷ 300) × 100
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%.

Q8. Write an algorithm to find the greatest among two different numbers entered by the user.
INPUT A
INPUT B

IF A > B THEN
    PRINT A, "is greater"
ELSE
    PRINT B, "is greater"
END IF

The question specifies two different numbers, so equality does not need to be handled. Example: A = 17 and B = 12 → 17 is greater.

Q9. Enter a number. If it is between 5 and 15, print GREEN; between 15 and 25, print BLUE; between 25 and 35, print ORANGE; otherwise print ALL COLOURS ARE BEAUTIFUL.

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 IF

Examples: 5 → GREEN; 15 → GREEN; 16 → BLUE; 25 → BLUE; 30 → ORANGE; 40 → ALL COLOURS ARE BEAUTIFUL.

If a teacher or question setter intends different endpoint rules, state them explicitly. The important point is to avoid overlapping conditions or leaving boundary values undefined.
Q10. Write an algorithm that accepts four numbers and finds the largest and smallest.

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 =", smallest

Example: 18, 7, 42, 11 → Largest = 42; Smallest = 7.

Q11. Calculate the monthly water bill: first 100 units at ₹5/unit; next 150 units at ₹10/unit; more than 250 units at ₹20/unit. Add meter charges of ₹75.

Interpret the rates as progressive slabs: each rate applies only to the units in its slab.

Units consumedCalculation of energy charge
0–100All 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_bill

Worked 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.

The solution treats the tariff as a progressive slab system. If the local tariff instead applies one rate to all units once a threshold is crossed, the formula would be different; follow the tariff rule specified by the authority.
Q12. What are conditionals? When are they required in a program?

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
Q13. Match the flowchart symbols with their functions.
Flowchart symbolCorrect function
Arrow / Flow lineFlow of Control
RectangleProcess Step
Oval / TerminatorStart/Stop of the Process
ParallelogramData (Input/Output)
DiamondDecision Making

Remember: rectangle = process; diamond = decision; parallelogram = input/output; oval = start/end; arrow = flow direction.

Q14. Improve the algorithm for going to school or college to include other options.

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
END

Other improvements may include checking the timetable, carrying an ID card, checking weather conditions, allowing extra travel time and following road-safety rules.

Q15. Write pseudocode to calculate the factorial of a number.

For a positive integer n, factorial is the product of all integers from 1 to n. By definition, 0! = 1.

n! = n × (n − 1) × … × 2 × 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 IF

Worked 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)
Q16. Draw a flowchart to check whether a given number is a three-digit Armstrong number.

A three-digit Armstrong number is a three-digit integer equal to the sum of the cubes of its digits.

ABC = A³ + B³ + C³

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 IF
START→INPUT n→Is 100 ≤ n ≤ 999?

NO → Display invalid input → END

YES→Extract hundreds, tens, units→Calculate sum of cubes→Is sum = n?

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")
Q17. Verify and correct the algorithm that classifies numbers as Single Digit, Double Digit or Big.

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.

InputOriginal outputCorrect output
5Single DigitSingle Digit
9Double DigitSingle Digit
47Double DigitDouble Digit
99BigDouble Digit
100BigBig
200BigBig

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 IF

The corrected ranges include 0–9, 10–99 and 100 or more. Negative values are explicitly handled rather than silently misclassified.

Q18. The algorithm should accept only positive integers up to 100. Identify failure values and improve it.

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 IF

Valid 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 LCM

Example: 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

TermRemember
Problem solvingIdentify problem → algorithm → program implementation.
GIGOGarbage In, Garbage Out.
AlgorithmFinite, precise sequence of steps to solve a problem.
FlowchartGraphical representation of an algorithm.
PseudocodeHuman-readable, non-executable description of algorithm steps.
SequenceStatements execute one after another.
SelectionChoose a path using a condition.
RepetitionRepeat instructions using a loop.
Dry runManually execute an algorithm with selected inputs.
Time complexityGrowth in processing work with input size.
Space complexityMemory required by an algorithm.
Source codeProgram written in a programming language.
DecompositionBreak 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.
Chapter completion checklist: You should be able to analyse a problem using IPO, write an algorithm, draw or interpret a flowchart, prepare pseudocode, use sequence/selection/repetition, dry-run an algorithm, compare time and space complexity, explain coding and decomposition, and solve all 18 textbook exercise questions.

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.

Class XI Computer Science · Chapter 4: Introduction to Problem Solving · Responsive Study Notes

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.