Home / Computer Science / Class XI / Introduction to Problem Solving
Introduction to Problem Solving — CUET Computer Science hero
Class XI 💻 Computer Science Ch 4 of 19

Introduction to Problem Solving

CUET unit: Introduction to Problem Solving

📌 Snapshot

  • How to turn a problem into an algorithm: pseudocode, flowcharts, dry runs and trace tables, worked out.
  • The four steps of problem solving, five features of a good algorithm and three kinds of flow of control.
  • Dry runs that expose bugs, four ways to test a prime, and how to compare algorithms by time and space.
  • The traps NTA sets on flowchart symbols, loop traces and boundary values, with practice MCQs.

📖 Detailed Notes

Written and reviewed by Rohit Singh, Computer Science & Commerce faculty at UniDrill (MCA, Osmania University · 6 years teaching). Based on NCERT Computer Science Class XI, Chapter 4.

A computer cannot solve a problem. You can.

Booking a train ticket from your phone looks like magic. Behind it is a huge task: many trains, many types of berths, a schedule, and thousands of people booking at the same moment. A computer handles it only because someone first worked out, in exact steps, how to handle it.

That is the main message of this chapter: a computer cannot solve a problem by itself. We must give it precise, step by step instructions. Whether a computer succeeds depends on how correctly we define the problem, design the solution (an algorithm) and implement it (a program). The correctness of the output depends on the correctness of the input, a rule summed up as GIGO, garbage in, garbage out.

The cycle in one line: analyse the problem → develop an algorithm → code → test and debug → maintain.

The steps of problem solving

When a car starts making a strange noise, a mechanic first finds where the noise comes from, makes a plan, and then repairs it. Solving a problem on a computer follows the same logic.

Step Question it answers Output of the step
Analysing the problem What exactly is to be solved? A list of inputs, the outputs and the core functions of the solution
Developing an algorithm How do I solve it, in plain language? A step by step solution, refined until it captures all aspects; the best of several possible algorithms is chosen
Coding How do I tell the computer? A program in a high level language, with its details documented
Testing and debugging Does it work for all inputs? Errors found and fixed, repeated until none remain
Maintenance What after delivery? Fixes, user queries answered, new features added

During testing, a syntax error means no output at all, while a wrong output points to a logical error. Industry follows standard testing methods such as unit (component) testing, integration testing, system testing and acceptance testing. A program must meet the user's needs, respond within the expected time, and give correct output for all possible inputs.

Algorithm: the recipe

An algorithm is a finite sequence of exact steps that leads to the desired result in a finite amount of time, if followed correctly. Like a recipe, it has a definite beginning, a definite end and a finite number of steps. The word comes from the name of the Persian mathematician Al-Khwarizmi (about 850 AD), whose name became "Algorithmi" in Latin.

Worked example: GCD of 45 and 54. The greatest common divisor is the largest number that divides both.

Step What we do Result
1 List the divisors of each number 45: 1, 3, 5, 9, 15, 45. 54: 1, 2, 3, 6, 9, 18, 27, 54
2 Find the largest common value 9

Why do we need an algorithm? A programmer needs a roadmap before writing code, otherwise the program may not work as expected. Search engines, messaging, online banking and taxi booking all rest on algorithms. If the algorithm is correct, the computer runs the program correctly every time. This increases the reliability, accuracy and efficiency of getting solutions. While writing an algorithm you identify three things: the input to be taken, the processing to be done and the output wanted.

Characteristic Meaning
Precision Every step is stated exactly
Uniqueness The result of each step depends only on the input and the previous steps
Finiteness It always stops after a finite number of steps
Input It receives some input
Output It produces some output

Pause and predict: what happens if an algorithm does not stop after a finite number of steps?

Check your answer: It never produces its final output, so it fails the finiteness test and isn't an algorithm at all. A loop whose condition can never become false is the usual cause.

Representing an algorithm: flowchart and pseudocode

An algorithm is written down in one of two ways, and in either case it should show the logic without implementation details and make the flow of control clear.

A flowchart is a diagram of shapes joined by arrows. Each shape is a step and each arrow shows the order.

Name Shape Function
Start/End (terminator) Oval Shows where the flow starts and ends
Process (action) Rectangle One step, action or process
Decision Diamond A yes/no or true/false question; the path splits into two branches
Input/Output (data) Parallelogram Input or output of data
Arrow (connector) Arrow Shows the order of flow between shapes

Pseudocode ("not real code") is an informal, human readable description of the instructions in order. It cannot be run by a computer and there is no standard for writing it. Common keywords are INPUT, COMPUTE, PRINT, INCREMENT, DECREMENT, IF/ELSE, WHILE and TRUE/FALSE. Writing pseudocode first protects a programmer from leaving out an important step, and lets non-programmers read the plan and confirm that it gives the desired output.

Worked example: square of a number. Identify the input, process and output first: input a number, process by multiplying it by itself, output the square.

Code
INPUT num
COMPUTE square = num * num
PRINT square

For the sum of two numbers the pseudocode is INPUT num1, INPUT num2, COMPUTE Result = num1 + num2, PRINT Result. For a rectangle:

Code
INPUT length
INPUT breadth
COMPUTE Area = length * breadth
PRINT Area
COMPUTE Perim = 2 * (length + breadth)
PRINT Perim

Flow of control: sequence, selection, repetition

The flow of control is the order in which the steps of an algorithm happen.

Kind Meaning Keyword Example
Sequence Steps run one after another None Square, sum, rectangle above
Selection One path is chosen depending on a condition (true or false) IF, ELSE Voting eligibility, odd or even
Repetition (iteration, loop) Some steps repeat until a condition is met WHILE Average of numbers

Selection. A condition is either true or false, and the program does different things in each case. In actual programs the "otherwise" is the else keyword, giving an if-else block.

Worked example: odd or even.

Code
PRINT "Enter the Number"
INPUT number
IF number MOD 2 == 0 THEN
    PRINT "Number is Even"
ELSE
    PRINT "Number is Odd"

MOD gives the remainder, so an even number has remainder 0 when divided by 2. In the flowchart a diamond asks whether the remainder equals 0, and the two branches lead to two print boxes.

Worked example: child, teenager or adult. Child is below 13, teenager is 13 or more but below 20, and adult is 20 or more.

Code
INPUT Age
IF Age < 13 THEN
    PRINT "Child"
ELSE IF Age < 20 THEN
    PRINT "Teenager"
ELSE
    PRINT "Adult"
Age First test (Age < 13) Second test (Age < 20) Output
12 True Not reached Child
13 False True Teenager
19 False True Teenager
20 False False Adult

The tests run top to bottom and stop at the first true one. That is why the second test does not need to say "at least 13": a person reaching it is already known to be 13 or more.

Common wrong step. Writing the tests in the wrong order, for example testing Age < 20 first. Then a 5-year-old would be called a teenager, because the first test catches everyone below 20.

Worked example: the card game Dragons and Wizards. Rules: a diamond or a club gives Team DRAGONS a point; a heart that is a number gives Team WIZARDS a point; a heart that is not a number gives DRAGONS a point; any other card gives WIZARDS a point. The team with more points wins.

Code
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 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"

Trace five cards through the conditions.

Card drawn Branch taken Dpoint Wpoint
Diamond 7 Diamond or club 1 0
Heart 5 Heart that is a number 1 1
Heart K Heart that is not a number 2 1
Spade 3 Any other card 2 2
Club A Diamond or club 3 2

Dpoint 3 beats Wpoint 2, so the dragons win. The pseudocode as given has a gap that a dry run exposes. If both teams finish with equal points, the last IF is false and it prints that the Wizard team wins, although neither team has won. The algorithm needs a third case for a tie.

Repetition. A loop repeats some statements until a condition is satisfied. A counter variable keeps track of the number of repetitions and is increased after each pass, until it reaches the set number. When the number of repetitions is not known in advance, the WHILE construct is used.

Worked example: average of 5 numbers (known count).

Code
SET count = 0
SET sum = 0
WHILE count < 5
    INPUT num
    sum = sum + num
    count = count + 1
average = sum / 5
PRINT average

Trace table for the inputs 4, 8, 6, 2 and 10.

Pass count before num sum after count after
1 0 4 4 1
2 1 8 12 2
3 2 6 18 3
4 3 2 20 4
5 4 10 30 5

Now count is 5, the condition count < 5 is false and the loop ends. The average is $30 / 5 = 6$.

Worked example: average until the user enters 0 (unknown count).

Code
SET count = 0
SET sum = 0
INPUT num
WHILE num != 0
    sum = sum + num
    count = count + 1
    INPUT num
average = sum / count
PRINT average

Take the inputs 6, 7, 4, 8, 2, 5, 0, 3, 1.

Step num read (end of step) Loop test num != 0 sum after count after
Before loop 6 True 0 0
Pass 1 7 True 6 1
Pass 2 4 True 13 2
Pass 3 8 True 17 3
Pass 4 2 True 25 4
Pass 5 5 True 27 5
Pass 6 0 False, stop 32 6

The sum is 32 and the count is 6, so the average is $32 / 6 \approx 5.33$. The 3 and the 1 after the 0 are never read. The first INPUT before the loop gives the test something to look at, and the second INPUT at the end of each pass reads the next value. Dividing by count (not by a fixed number) is what makes it work for any number of inputs.

Common wrong step. Giving 0 as the very first input. The loop never runs, count stays 0 and the algorithm divides by zero. A dry run with this input shows the gap, so the algorithm needs a check for count == 0.

Checking an algorithm: the dry run

A faulty program can do damage: imagine a money transfer module that credits only half the amount, or debits instead of crediting. Software for hospitals and space missions must work in every situation. So before coding, you check the algorithm by taking sample inputs and going through every step by hand, which is called a dry run. A dry run helps you to identify incorrect steps and to find missing details. You choose inputs carefully, because a program that is not tested on all kinds of input will fail on the one you missed. It is also cheapest to fix a mistake at this stage.

It is just like checking the formula for the sum of the first $N$ natural numbers, $N(N+1)/2$. For $N = 6$ we get $1 + 2 + 3 + 4 + 5 + 6 = 21$ and $6 \times 7 / 2 = 21$.

Worked example: adding two journey times. Time from A to B is hh1 hours and mm1 minutes, and from B to C is hh2 and mm2. The first version adds hours to hours and minutes to minutes.

Input hh_total mm_total Output Correct?
5 h 20 min + 7 h 30 min 12 50 12 h 50 min Yes
4 h 50 min + 2 h 20 min 6 70 6 h 70 min No: should be 7 h 10 min

The second input shows that the algorithm works only when mm_total < 60. The fix is to add one test after the additions.

Code
hh_total = hh1 + hh2
mm_total = mm1 + mm2
IF mm_total >= 60 THEN
    hh_total = hh_total + 1
    mm_total = mm_total - 60
PRINT hh_total, mm_total

The same dry run now gives $6 + 1 = 7$ hours and $70 - 60 = 10$ minutes.

Worked example: boundary values. An algorithm classifies a number as "Single Digit" if Number < 9, "Double Digit" if Number < 99 and "Big" otherwise. Test it on 5, 9, 47, 99, 100 and 200.

Input Output of the algorithm Correct answer Verdict
5 Single Digit Single Digit Right
9 Double Digit Single Digit Wrong
47 Double Digit Double Digit Right
99 Big Double Digit Wrong
100 Big Big Right
200 Big Big Right

The two failures happen exactly on the boundaries 9 and 99, because < leaves out the boundary itself. The fix is Number <= 9 and Number <= 99. Always test the boundary values of every condition, and values just on either side.

Worked example: a range check. An algorithm accepts a number if 0 <= Number AND Number <= 100, meant for positive integers up to 100. It wrongly accepts 0, since 0 is not positive, and it accepts fractions like 50.5, which are not integers. An improved version tests 1 <= Number, Number <= 100 and that the number is a whole number.

Pause and predict: a student tests an algorithm only with the input 25 and finds the output correct. Is the algorithm correct?

Check your answer: Not necessarily. One input proves nothing about the rest. Test ordinary values, boundary values and unusual values such as 0.

Comparing algorithms: time and space

There can be several algorithms for the same problem. Take testing whether a number is prime. Four approaches:

Method Idea Cost
(i) Divide by every divisor from 2 up to just below the number Most calculations; slowest for large numbers
(ii) Test divisors only up to half the number, since a divisor cannot exceed half Fewer than (i)
(iii) Test divisors only up to the square root of the number Even fewer
(iv) Divide only by the primes from a stored list (for example the primes up to 100) Fewest calculations, but the list takes extra memory

Worked example: how many divisions to test 97?

Method Divisors tried Count
(i) 2 to 96 95
(ii) 2 to 48 47
(iii) 2 to 9, since $\sqrt{97} \approx 9.85$ 8
(iv) The 24 primes below 97 24, plus the memory to store them

All four conclude that 97 is prime, but they differ greatly in the work done. Algorithms are compared on the processing time they need, called time complexity, and the memory they need, called space complexity. Method (iv) buys speed with memory.

Why the square root is enough. If $n = a \times b$ and $a \le b$, then $a \le \sqrt{n}$. So if $n$ has any factor besides 1 and itself, it has one no bigger than $\sqrt{n}$, and you can stop searching there.

Worked example: method (iii) as pseudocode.

Code
INPUT n
SET isPrime = TRUE
SET d = 2
WHILE d * d <= n
    IF n MOD d == 0 THEN
        SET isPrime = FALSE
    d = d + 1
IF isPrime THEN
    PRINT "Prime"
ELSE
    PRINT "Not prime"
n Divisors tried (d) Stops because Output
91 2, 3, 4, 5, 6, 7 (91 MOD 7 = 0 so isPrime becomes FALSE), 8, 9 $10 \times 10 > 91$ Not prime
97 2, 3, 4, 5, 6, 7, 8, 9 $10 \times 10 > 97$ Prime
1 None $2 \times 2 > 1$ at once Prime (wrong)

The dry run on 1 exposes a bug: the loop never runs, so the answer stays TRUE, though 1 is not a prime. The algorithm needs a first test that n is greater than 1.

Beyond the textbook. For the exam: find the GCD by listing divisors, as in the example above. In reality: the Greek mathematician Euclid described a much faster method: replace the pair (a, b) by (b, a MOD b) until the second number is 0, and the first is the GCD. For 54 and 45: 54 MOD 45 = 9, then 45 MOD 9 = 0, so the GCD is 9 in two steps. Why it matters: it shows that different algorithms for the same problem can differ hugely in effort, which is the point of comparing algorithms.

Beyond the textbook. For the exam: algorithms are compared by time complexity and space complexity. In reality: the trade of memory for speed in method (iv) is everywhere in computing. The cache in the computer system chapter is another case: extra fast memory is spent to save waiting time. Why it matters: there is rarely a free lunch, so the best algorithm depends on which resource is scarcer.

Worked example: a water bill. Charges: the first 100 units at ₹5 per unit, the next 150 units at ₹10 per unit, more than 250 units at ₹20 per unit, plus a meter charge of ₹75 a month.

Code
INPUT units
IF units <= 100 THEN
    bill = units * 5
ELSE IF units <= 250 THEN
    bill = 100 * 5 + (units - 100) * 10
ELSE
    bill = 100 * 5 + 150 * 10 + (units - 250) * 20
bill = bill + 75
PRINT bill
Units Slab working Bill before meter Total with ₹75
80 $80 \times 5$ ₹400 ₹475
200 $100 \times 5 + 100 \times 10$ ₹1500 ₹1575
300 $100 \times 5 + 150 \times 10 + 50 \times 20$ ₹3000 ₹3075

Common wrong step. Charging all 300 units at ₹20 (₹6000). The rate applies only to the units above 250, as in a tax slab.

Worked example: factorial and Armstrong number. The factorial of 5 is $5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$. A three digit Armstrong number equals the sum of the cubes of its digits: 371 is one because $3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371$.

Code
INPUT n
SET fact = 1
SET i = 1
WHILE i <= n
    fact = fact * i
    i = i + 1
PRINT fact
Pass i fact after
1 1 1
2 2 2
3 3 6
4 4 24
5 5 120

For the Armstrong test, the loop peels off the last digit with digit = temp MOD 10, adds its cube to a total, and removes it with temp = temp DIV 10 (DIV gives the whole number quotient). For 371 the digits come out as 1, 7, 3 and the total grows 1, 344, 371, which equals the input, so it is an Armstrong number.

Coding

Once the algorithm is final, it is written in a high level programming language by following its syntax, the set of rules, like grammar, that govern spelling, order and punctuation. Machine language of 0s and 1s runs directly on the hardware but is hard for humans. High level languages, such as FORTRAN, C, C++, Java and Python, are close to natural language and easy to read, write and maintain. They are portable: they run on different computers with little or no change, while low level programs run on only one kind of computer. A program in a high level language is source code, and a compiler or an interpreter translates it into machine language.

Choosing a language depends on the platform (operating system), on whether the application is for desktop, mobile or web, and on whether it is for an embedded system such as a digital watch, MP3 player, traffic signal or medical equipment, where specialised tools or assembly language may be needed.

Decomposition: divide and conquer

If a problem is too complex to solve directly, decompose it, that is, break it into smaller sub-problems that are easier to solve, and then combine the solutions in a logical way. The railway reservation system breaks into parts.

Sub-problem What it holds
Train information Days, timings, stations, classes and berths
Reservation information Booking open or closed, available or waiting list, cancellation and refund
Staff and infrastructure Information about staff, security and railway infrastructure
Food service and billing service Separate services that plug into the system

Each sub-problem can be studied in detail, solved independently, and handed to a team that is expert in it. Once solved, the parts must be tested for correctness and integrated into the complete solution. Decomposition is used for problems in mathematics and science, event management in a school, weather forecasting and delivery management.

Exam traps

The trap Why it's tempting The truth
"Pseudocode can be executed by the computer." It looks like code It is for humans; it cannot be run directly and has no standard
"A diamond shape is a process step." Boxes feel like steps A diamond is a decision; a rectangle is a process
"The parallelogram marks the start." It is the first shape drawn in many charts The parallelogram is input or output; start and end use the terminator
"An algorithm may go on forever." Programs like games keep running An algorithm must stop after a finite number of steps
"Wrong output means a syntax error." Both are errors A syntax error stops the program; a wrong output points to a logical error
"There is only one algorithm for a problem." One answer is neat There can be many; choose by time and space
"A dry run is done after the program is finished." We test programs A dry run checks the algorithm before coding
"Method (iv) of the prime test uses less memory." It does fewer divisions It does fewer divisions but needs memory to store the prime list

60-second revision

Topic Lock this in
Steps Analyse → algorithm → code → test and debug → maintain
Algorithm Finite, precise steps with input and output; definite start and end
Features Precision, uniqueness, finiteness, input, output
Flowchart Oval start/end; rectangle process; diamond decision; parallelogram input/output; arrows
Pseudocode Informal, human readable, not executable, no standard
Flow of control Sequence, selection (IF/ELSE), repetition (WHILE)
Dry run Run the steps by hand with inputs to find incorrect or missing steps
Boundary values Test the edges of each condition, such as 9 and 99
Comparison Time complexity (processing time), space complexity (memory)
Decomposition Break a complex problem into sub-problems, solve each, combine
GIGO Output is only as good as the input

Pseudocode patterns sheet

Pattern Skeleton Use
Average of known count $k$ $\text{average} = \text{sum} / k$ Loop with a counter
Average of unknown count $\text{average} = \text{sum} / \text{count}$ Loop that stops at a special value; guard against count 0
Even test number MOD 2 == 0 Odd or even
Last digit n MOD 10 Digit extraction
Drop last digit n DIV 10 Digit extraction
Counter loop WHILE count < k with count = count + 1 Repeat k times
Slab billing Charge each slab separately, then add Bills and tax slabs

Where this chapter connects

  • Previous: Emerging Trends shows the problems that today's algorithms are written to solve.
  • Next: Getting Started with Python is where these algorithms are turned into real programs.
  • Control flow in Python: Flow of Control turns sequence, selection and repetition into if statements and loops.
  • Class XII link: Searching and Sorting compare several algorithms for one task, exactly like the prime test above.

🎯 Practice MCQs

First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed

Q1. Which of the following gives the correct order of the steps of problem solving using a computer?

▸ Show answer & explanation

Answer: B

You must understand the problem first, then design the algorithm, then code it, and finally test and debug. The other orders put coding before the design is ready.

Q2. Which of the following is NOT a characteristic of a good algorithm?

▸ Show answer & explanation

Answer: C

An algorithm must stop after a finite number of steps. Precision, finiteness, receiving input and producing output are all characteristics of a good algorithm.

Q3. In a flowchart, which symbol is used for a yes or no question that splits the flow into two branches?

▸ Show answer & explanation

Answer: C

The diamond is the decision symbol. The rectangle is a process step, the parallelogram is input or output, and the oval marks the start or end.

🔒 12 more practice MCQs

Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.

Already registered? Just log in and they'll all appear here.

📊 Previous-Year Questions

Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.

View solved CUET PYQ papers →

Ready to drill Computer Science?

Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.

Get UniDrill Pro