Chapter 2Computer Science

Chapter 2

Read official chapter content, important formulas, and quick notes below.

Chapter 2

Chapter Overview

The second chapter of the Computer Science book for Class 11 introduces the fundamental concept of Algorithms and the broader methodology of computer-based Problem Solving. An algorithm is a precise, step-by-step set of unambiguous instructions used to solve a specific problem or perform a computation. It serves as a well-defined computational procedure that takes some value (or set of values) as input and produces a corresponding value (or set of values) as output.

Algorithms represent the foundational backbone of computer science, software engineering, data science, and artificial intelligence. Before writing a single line of code in any programming language (such as Python, C++, or Java), a computer scientist must conceptualize, design, and validate the underlying algorithm. In this chapter, we explore the complete problem-solving lifecycle, the core types and characteristics of algorithms, strategies for algorithm design, and modern representation techniques including detailed flowcharts and standardized pseudocode.


Learning Objectives

By mastering this chapter, students will be able to:

  • Analyze and Understand the concept of algorithms, their theoretical foundations, and their indispensability in computational problem-solving.
  • Deconstruct the Problem-Solving Lifecycle: From initial problem identification and analysis to algorithm design, implementation, testing, and documentation.
  • Categorize Algorithm Control Structures: Differentiate comprehensively between sequential execution, selection (conditional branching), iteration (looping), and recursion.
  • Identify Core Characteristics: Evaluate algorithms against Donald Knuth’s standard criteria—Input, Output, Definiteness, Finiteness, and Effectiveness.
  • Master Representation Techniques: Translate real-world logic into standard ANSI flowcharts and syntactically clean, language-agnostic pseudocode.
  • Perform Trace Table Analysis (Dry Running): Manually execute algorithms step-by-step to track variable states, verify correctness, and debug logical errors.
  • Evaluate Algorithmic Efficiency: Understand the basic concepts of Time Complexity and Space Complexity.

Complete Problem-Solving Lifecycle

Before developing an algorithm, software engineers follow a structured methodology known as the Software Development Problem-Solving Lifecycle.

[Problem Definition] ➔ [Problem Analysis] ➔ [Algorithm Design] ➔ [Coding/Implementation] ➔ [Testing & Debugging] ➔ [Documentation]
  1. Problem Definition: Clearly defining the goal and boundaries of the problem. What needs to be calculated or solved?
  2. Problem Analysis: Deconstructing the problem to identify inputs, required outputs, constraints, edge cases, and relationships between variables.
  3. Algorithm Design: Designing a step-by-step plan using high-level logic (Flowcharts and Pseudocode) independent of any programming language.
  4. Coding / Implementation: Translating the designed algorithm into high-level programming language code (e.g., Python).
  5. Testing and Debugging: Running the code with sample inputs, boundary inputs, and erroneous inputs to identify and fix:
    • Syntax Errors: Violations of language rules.
    • Runtime Errors: Errors causing abrupt program termination during execution (e.g., Division by Zero).
    • Logical Errors: Errors where code runs but produces incorrect outputs due to faulty algorithm design.
  6. Documentation & Maintenance: Writing code comments and user manuals to enable future maintenance and scalability.

Important Concepts

Characteristics of Algorithms (Donald Knuth's Criteria)

For a set of instructions to qualify as an algorithm, it must satisfy five crucial criteria established by computer scientist Donald Knuth, alongside general processing efficiency:

  • Input: An algorithm must have zero or more well-defined inputs provided externally before execution begins.
  • Output: An algorithm must produce at least one well-defined output, representing the quantitative result or state change requested.
  • Definiteness (Unambiguity): Every step of the algorithm must be clear, precise, and unambiguous. There should be no room for dynamic interpretation. For instance, "Add 3 or 4 to x" is ambiguous, whereas "Add 3 to x" is definite.
  • Finiteness: An algorithm must terminate after a finite number of steps for all valid input test cases. An infinite loop or endless process is not a valid algorithm.
  • Effectiveness: Every instruction must be sufficiently basic that it can, in principle, be carried out using pencil and paper in a finite amount of time.
  • Processing: The processing represents the execution engine—the systematic, logical, arithmetic, and control-flow steps executed by the machine or processor to transform inputs into outputs.

Classification & Types of Algorithms

Algorithms are categorized based on their underlying control structure and logical progression:

1. Sequential Algorithm

A sequential algorithm follows a strictly linear execution flow. Instructions are executed in a top-to-bottom order, one after another, without skipping any steps or repeating execution.

  • Characteristics: Deterministic flow, no decision-making diamonds, no loop constructs.
  • Example Case Study: Computing the Simple Interest and Total Amount given Principal (PP), Rate (RR), and Time (TT). Simple Interest (SI)=P×R×T100\text{Simple Interest (SI)} = \frac{P \times R \times T}{100}

2. Selection Algorithm (Conditional Execution)

A selection algorithm (also called conditional or decision-making algorithm) dynamically selects a specific path of execution from two or more alternatives based on whether a given Boolean condition evaluates to TRUE or FALSE.

  • Key Structures: IF...THEN, IF...THEN...ELSE, NESTED IF.
  • Example Case Study: Determining whether a student has Passed or Failed based on marks, or finding the maximum among three numbers.

3. Iteration Algorithm (Looping)

An iteration algorithm repeats a designated block of instructions multiple times until a predefined terminating condition is met.

  • Key Structures:
    • Pre-tested Loop (Entry-controlled): The condition is tested before executing the loop body (e.g., WHILE, FOR).
    • Post-tested Loop (Exit-controlled): The condition is tested after executing the loop body at least once (e.g., REPEAT...UNTIL or DO...WHILE).
  • Example Case Study: Summing the first NN natural numbers or calculating the factorial of a given integer N!N!.

4. Recursion Algorithm

A recursion algorithm solves a complex problem by reducing it into smaller, manageable sub-problems of the exact same type. In programming, a recursive function calls itself directly or indirectly until it reaches a terminal condition known as the Base Case.

  • Key Components:
    • Base Case: The simplest scenario that can be solved directly without further recursive calls, preventing infinite stack overflow.
    • Recursive Step: The logic that reduces the current problem size (NN) toward the base case (N1N-1 or N/2N/2).
  • Example Case Study: Computing Factorial (N!=N×(N1)!N! = N \times (N-1)!) or calculating Fibonacci sequence values (F(n)=F(n1)+F(n2)F(n) = F(n-1) + F(n-2)).

5. Searching and Sorting Algorithms (Extended Knowledge)

  • Linear Search: Checks every element sequentially until the target is found. Time Complexity: O(n)O(n).
  • Binary Search: Efficiently searches a sorted array by repeatedly dividing the search interval in half. Time Complexity: O(logn)O(\log n).
  • Bubble Sort: Compares adjacent elements and swaps them if they are in the wrong order, performing multiple passes. Time Complexity: O(n2)O(n^2).

Representing Algorithms

Algorithms can be formally expressed using graphical diagrams (Flowcharts), high-level structured English (Pseudocode), or decision tables.


Flowcharts

A flowchart is a standardized graphical representation of an algorithm. It uses geometrically distinct symbols connected by directional arrows (flowlines) to visually map out processing logic, inputs/outputs, and decision branches.

Standard ANSI Flowchart Symbols

Symbol NameGeometric ShapePurpose / Function
TerminalOval / CapsuleIndicates the Start or End/Stop point of the flowchart.
Input / OutputParallelogramDenotes data entry (READ/INPUT) or data display (PRINT/DISPLAY).
ProcessingRectangleRepresents arithmetic operations, variable assignments, and computations.
DecisionDiamondRepresents a logical condition/question resulting in binary (True/False, Yes/No) paths.
FlowlinesDirected Arrows (,,,\rightarrow, \leftarrow, \uparrow, \downarrow)Shows the direction of control execution flow.
ConnectorSmall CircleConnects disparate flow sections across complex diagrams or multiple pages.

Pseudocode

Pseudocode (derived from pseudo meaning "false" and code meaning "programming instructions") is an informal, high-level, human-readable description of an algorithm. It mimics the structural conventions of code (indentation, control structures) while utilizing natural language phrases.

Conventions for Writing Good Pseudocode:

  1. Capitalize primary control structural keywords (START, END, READ, PRINT, IF, ELSE, WHILE, FOR, REPEAT).
  2. Use clear variable names (e.g., totalAmount, studentAge).
  3. Use structural indentation to highlight nested statements within loops and conditionals.
  4. Keep logic completely independent of any specific language syntax (do not use language-specific library functions).

Comparative Matrix: Flowcharts vs Pseudocode vs Source Code

FeatureFlowchartPseudocodeSource Code (Python/C++)
FormatVisual / Graphical DiagramTextual (Structured English)Syntactic Programming Code
Ease of UnderstandingHighly intuitive for beginnersHighly readable for developersRequires compiler/syntax knowledge
Modification CostDifficult to modify (requires redrawing)Easy to modify and editEasy to edit and recompile
Machine ExecutionCannot be executed directlyCannot be executed directlyCompiled/Interpreted into machine code
StandardizationANSI/ISO Standard SymbolsIndentation & Keyword standardsStrict language grammatical syntax

Key Definitions

  • Algorithm: A finite, step-by-step set of unambiguous, well-defined computational instructions designed to transform inputs into specified outputs.
  • Input: External data items supplied to the algorithm prior to execution to initiate computational processing.
  • Output: The quantitative or qualitative result returned by the algorithm after execution finishes.
  • Processing: The operational steps (mathematical operations, data movements, and logical evaluation) performed on inputs.
  • Flowchart: A diagrammatic, visual representation of an algorithm using standardized geometric shapes and flow arrows.
  • Pseudocode: A language-agnostic, structured textual description of an algorithm written in readable English.
  • Dry Run (Trace Table): A manual validation procedure where a programmer tracks variable values on paper through loop cycles and logic steps to verify correctness.
  • Time Complexity: A metric quantifying the amount of computational time an algorithm takes as a function of the input size (NN).
  • Space Complexity: A metric quantifying the total memory space required by an algorithm during execution.

Important Terms

TermMeaning
AlgorithmA set of instructions that is used to solve a problem or perform a task.
InputThe data that is used to execute the algorithm.
OutputThe result produced by the algorithm.
ProcessingThe set of steps that are executed by the algorithm to produce the output.
FlowchartA graphical representation of an algorithm that uses symbols and arrows to represent the steps and decisions in the algorithm.
PseudocodeA high-level representation of an algorithm that uses natural language to describe the steps and decisions in the algorithm.
IterationThe repetitive execution of a block of code until a condition evaluates to false.
RecursionA technique where an algorithm solves a problem by invoking smaller instances of itself.
DefinitenessThe characteristic ensuring every algorithmic instruction is unambiguous and precise.
FinitenessThe property ensuring an algorithm stops after a countable number of execution steps.
Trace TableA tabular technique used to test and manually step through algorithm logic with sample data.

Diagrams & Detailed Descriptions

Diagram 1: Sequential Algorithm — Calculating the Area of a Rectangle

     ( Start )
         |
    [ Read Length, ]
    [   Breadth    ]
         |
    [ Area = Length ]
    [    * Breadth  ]
         |
    [ Print Area ]
         |
      ( Stop )
  • Description:
    1. Start: Represented by an Oval terminal symbol.
    2. Input: A Parallelogram symbol containing Read Length, Breadth.
    3. Processing: A Rectangle symbol containing the computation Area = Length * Breadth.
    4. Output: A Parallelogram symbol containing Print Area.
    5. Stop: An Oval terminal symbol indicating completion.

Diagram 2: Selection Algorithm — Determining the Largest of Three Numbers

                    ( Start )
                        |
               [ Input A, B, C ]
                        |
               < Is A > B ? >
                /          \
            (YES)          (NO)
             /                \
     < Is A > C ? >      < Is B > C ? >
      /          \        /          \
   (YES)        (NO)   (YES)        (NO)
    /              \     /              \
[Print A]     [Print C] [Print B]    [Print C]
    \              /     \              /
     -------------> ( Stop ) <----------
  • Description: The algorithm inputs three numbers A,B,CA, B, C. A diamond decision node compares A>BA > B.
    • If True, a secondary decision checks A>CA > C. If True, AA is printed; if False, CC is printed.
    • If False (BAB \ge A), a secondary decision checks B>CB > C. If True, BB is printed; if False, CC is printed. All paths converge to the Stop terminal.

Real-Life Applications & Deep-Dive Case Studies

Case Study 1: Web Search Engine Indexing & PageRank (Google)

  • Domain: Computer Networks & Web Processing
  • Application: When a user searches for a query on Google, billions of web pages exist. Delivering accurate results within milliseconds requires advanced algorithms.
  • Algorithmic Mechanics:
    1. Web Crawling: Iterative recursive algorithms parse links across the web to build a search graph.
    2. PageRank Algorithm: Assigns numerical weights to web pages based on incoming hyperlink quality and quantity (represented as linear algebra matrix operations).
    3. Sorting & Search: Sorting algorithms organize matching documents by relevance score and render top results instantly.

Case Study 2: GPS Navigation Systems (Dijkstra’s Algorithm)

  • Domain: Transportation and Logistics (Google Maps, Uber)
  • Application: Finding the absolute fastest driving route between two geographical location coordinates while factoring in distance, traffic jams, and road blockages.
  • Algorithmic Mechanics:
    1. Map nodes are modeled as a weighted graph G=(V,E)G = (V, E), where vertices (VV) are intersections and edges (EE) are road segments weighted by real-time traversal time.
    2. Dijkstra's Shortest Path Algorithm iteratively evaluates neighboring nodes, relaxing distance estimations until the shortest total dynamic weight path from Origin to Destination is computed.

Case Study 3: E-Commerce Recommendation Engines (Amazon / Netflix)

  • Domain: Machine Learning & Data Analytics
  • Application: Recommending personalized products or movies based on historical viewing and purchasing trends.
  • Algorithmic Mechanics:
    1. Uses Collaborative Filtering Algorithms to compute vector similarity (e.g., Cosine Similarity) between dynamic user preference vectors.
    2. Sorts candidates by calculated similarity score and outputs the top NN items to the user interface.

Step-by-Step Problem-Solving Strategies & Trace Tables

Problem 1: Euclid’s Algorithm for Finding the Greatest Common Divisor (GCD) of Two Integers

Objective: Compute the largest positive integer that divides two integers AA and BB without leaving a remainder.

Pseudocode Representation:

START
    READ A, B
    WHILE B != 0 DO
        Remainder = A MOD B
        A = B
        B = Remainder
    END WHILE
    PRINT "GCD is", A
END

Step-by-Step Trace Table Analysis:

Let Test Input values be A=48A = 48, B=18B = 18.

Iteration StepCondition (B != 0)A MOD BNew Value of ANew Value of BAction / State Notes
Initial4818Input loaded
Pass 118 != 0 (TRUE)48 MOD 18 = 121812Variables shifted
Pass 212 != 0 (TRUE)18 MOD 12 = 6126Variables shifted
Pass 36 != 0 (TRUE)12 MOD 6 = 060Variables shifted
Pass 40 != 0 (FALSE)60Loop Terminates

Final Output: GCD is 6 (Correct: 48=6×848 = 6 \times 8, 18=6×318 = 6 \times 3).


Step-by-Step Algorithm Analysis: Binary Search

Problem: Find target element X=23X = 23 in sorted array Arr = [2, 5, 8, 12, 16, 23, 38, 56, 72].

  1. Initialize: Low index L=0L = 0, High index H=8H = 8.
  2. Pass 1:
    • Mid=(0+8)/2=4\text{Mid} = \lfloor (0 + 8) / 2 \rfloor = 4.
    • Arr[4]=16\text{Arr}[4] = 16.
    • Compare Target(23)>16    Set L=Mid+1=5\text{Target} (23) > 16 \implies \text{Set } L = \text{Mid} + 1 = 5.
  3. Pass 2:
    • Mid=(5+8)/2=6\text{Mid} = \lfloor (5 + 8) / 2 \rfloor = 6.
    • Arr[6]=38\text{Arr}[6] = 38.
    • Compare Target(23)<38    Set H=Mid1=5\text{Target} (23) < 38 \implies \text{Set } H = \text{Mid} - 1 = 5.
  4. Pass 3:
    • Mid=(5+5)/2=5\text{Mid} = \lfloor (5 + 5) / 2 \rfloor = 5.
    • Arr[5]=23\text{Arr}[5] = 23.
    • Match Found! Return Index 55.

Key Points to Remember

  • Algorithms are precise, language-agnostic step-by-step processing instructions designed to solve specific computational problems.
  • Donald Knuth established 5 mandatory characteristics for algorithms: Input, Output, Definiteness, Finiteness, and Effectiveness.
  • Control structures in algorithms include Sequential, Selection (branching/conditional), Iteration (loops), and Recursion.
  • Flowcharts represent computational logic graphically using standardized ANSI visual symbols.
  • Pseudocode uses natural structured statements and strict indentation to represent programmatic logic without language-specific syntax errors.
  • Trace tables allow programmers to manually dry-run algorithms to verify logical accuracy and track variable state shifts.

Common Mistakes & Troubleshooting

  • Confusing Algorithms with Source Code: Algorithms are high-level conceptual plans; source code is language-specific implementation.
  • Creating Infinite Loops (Violating Finiteness): Forgetting to update loop control variables leads to non-terminating loops.
  • Ambiguous Statements (Violating Definiteness): Using non-specific phrases like "Multiply xx by a small number" instead of exact numeric operations.
  • Incorrect Flowchart Symbols: Drawing action steps in decision diamonds or using incorrect flow arrow orientations.
  • Off-by-One Errors: Using incorrect relational operator conditions (e.g., < instead of <=) in loops and array bounds.

Quick Revision

  • Algorithm Definition: A finite, logical step-by-step process that takes input and yields a deterministic output.
  • 5 Core Properties: Input, Output, Definiteness, Finiteness, Effectiveness.
  • Flowchart Key Shapes: Oval (Start/Stop), Parallelogram (I/O), Rectangle (Process), Diamond (Decision), Arrows (Flow).
  • Pseudocode Key Features: Readable, structured, indented, language-independent logic.
  • Errors Identified During Testing:
    • Syntax Errors: Violation of programming language rules.
    • Logical Errors: Algorithmic flaw resulting in wrong outputs despite crash-free execution.
    • Runtime Errors: Errors during execution (e.g., division by zero).

Higher-Order Thinking Skills (HOTS) Questions & Solutions

Question 1

Dry run the following pseudocode and determine the exact output generated when N=5N = 5. What mathematical sequence does this algorithm generate?

START
    READ N
    SET A = 0, B = 1
    PRINT A, B
    SET Count = 2
    WHILE Count < N DO
        C = A + B
        PRINT C
        A = B
        B = C
        Count = Count + 1
    END WHILE
END

Solution:

  • Trace Table:
StepCountCount < N (N=5)C = A + BABPrinted Output
Init2010, 1
Pass 122 < 5 (TRUE)0+1=10 + 1 = 1111
Pass 233 < 5 (TRUE)1+1=21 + 1 = 2122
Pass 344 < 5 (TRUE)1+2=31 + 2 = 3233
Pass 455 < 5 (FALSE)Loop ends
  • Final Printed Output: 0, 1, 1, 2, 3
  • Mathematical Sequence: The algorithm generates the first NN terms of the Fibonacci Sequence.

Question 2

Rewrite the following sequential algorithmic process into an efficient Selection-based Pseudocode to avoid unnecessary zero division errors:

"Divide input X by input Y and output the result."

Solution:

START
    READ X, Y
    IF Y != 0 THEN
        Result = X / Y
        PRINT "Division Result:", Result
    ELSE
        PRINT "Error: Division by Zero is mathematically undefined."
    END IF
END

Question 3

Analyze the pseudocode below and explain why it fails to qualify as a valid algorithm according to Knuth's properties.

START
    SET X = 10
    WHILE X > 0 DO
        PRINT X
        X = X + 1
    END WHILE
END

Solution: This sequence violates the Finiteness property. The variable X starts at 10 and increases by 1 in each iteration (11, 12, 13...). The condition X > 0 remains permanently TRUE, creating an infinite loop that never terminates.


Previous Year Questions (PYQs) with Solutions

PYQ 1 (Short Answer)

Define an algorithm. What are the key advantages of writing pseudocode before writing actual computer code?

Answer: An algorithm is a well-defined, finite set of clear step-by-step instructions that takes inputs and produces predictable outputs.

Advantages of Pseudocode:

  1. Language Independence: Allows developers to focus purely on logical design without syntax overhead.
  2. Ease of Debugging: Enables quick logical verification and tracing on paper before coding.
  3. Enhanced Maintainability: Serves as documentation for developers using different target programming languages.

PYQ 2 (Flowchart Design)

Draw a flowchart logic sequence to calculate the sum of the first NN natural numbers (1+2+3++N1 + 2 + 3 + \dots + N).

Answer Description:

  1. Terminal Oval: START
  2. Input Parallelogram: READ N
  3. Processing Rectangle: SET Sum = 0, SET Count = 1
  4. Decision Diamond: Is Count <= N ?
    • YES Path:
      • Process Rectangle: Sum = Sum + Count
      • Process Rectangle: Count = Count + 1
      • Connect arrow back to Decision Diamond entry.
    • NO Path:
      • Output Parallelogram: PRINT Sum
      • Terminal Oval: STOP

PYQ 3 (Algorithm Analysis)

Differentiate between Syntax Errors, Runtime Errors, and Logical Errors with suitable examples.

Answer:

  • Syntax Error: Violations of language-specific grammar rules (e.g., missing parentheses or misspelled keywords like prnt("Hello")). Caught during compilation or parsing.
  • Runtime Error: Causes unexpected program termination during execution (e.g., attempting to divide a number by zero or accessing an out-of-bounds array index).
  • Logical Error: The program executes to completion without crashing but yields incorrect results because the underlying algorithm is flawed (e.g., computing Area = Length + Breadth instead of Length * Breadth).

NCERT Textbook Questions & Detailed Answers

Question 1

What is an algorithm? Why is it necessary to write an algorithm before writing a program?

Answer: An algorithm is a well-defined, step-by-step, finite sequence of unambiguous instructions designed to solve a given problem or accomplish a specific task.

It is necessary to write an algorithm before coding because:

  1. Logical Clarity: It separates problem-solving logic from language-specific syntax errors.
  2. Efficiency Analysis: It helps developers evaluate and optimize the time and memory efficiency of their logic before writing code.
  3. Language-Agnostic Design: A single well-designed algorithm can be easily converted into any programming language (Python, C++, Java).
  4. Faster Debugging: It is easier to identify and correct conceptual or structural errors on paper than within thousands of lines of code.

Question 2

Explain the basic characteristics that every algorithm must possess.

Answer: An algorithm must satisfy Donald Knuth's fundamental characteristics:

  1. Input: Must accept zero or more inputs supplied prior to processing.
  2. Output: Must produce at least one output corresponding to the intended solution.
  3. Definiteness (Unambiguity): Every step must be unambiguous, exact, and clearly defined.
  4. Finiteness: Must terminate after a countable number of execution steps for any valid input.
  5. Effectiveness: Each instruction must be simple enough to be executed manually with pencil and paper in finite time.

Question 3

Write an algorithm and pseudocode to find the factorial of a given number NN.

Answer:

Algorithmic Steps:

  1. Start the process.
  2. Accept a non-negative integer input NN.
  3. Check if N<0N < 0. If true, output an error message indicating factorial is undefined for negative numbers and stop.
  4. Initialize two variables: Fact = 1 and Counter = 1.
  5. Repeat the following steps while Counter <= N:
    • Multiply Fact by Counter (Fact = Fact * Counter).
    • Increment Counter by 1 (Counter = Counter + 1).
  6. Print the resulting value stored in Fact.
  7. Stop.

Pseudocode:

START
    READ N
    IF N < 0 THEN
        PRINT "Factorial is undefined for negative numbers."
    ELSE
        SET Fact = 1
        SET Counter = 1
        WHILE Counter <= N DO
            Fact = Fact * Counter
            Counter = Counter + 1
        END WHILE
        PRINT "Factorial of", N, "is", Fact
    END IF
END

Question 4

Differentiate between a flowchart and pseudocode. List the standard symbols used in flowcharts.

Answer:

Differences:

  • A Flowchart uses graphical symbols and directional arrows to visualize processing paths, making it ideal for visual learners and simple logic flows.
  • Pseudocode uses structured, natural-language text formatted like code, making it better suited for complex software development and modular algorithms.

Standard Flowchart Symbols:

  1. Oval: Indicates Start or Stop.
  2. Parallelogram: Used for Input and Output operations.
  3. Rectangle: Represents Processing, calculation, and variable assignments.
  4. Diamond: Represents conditional Decision branches (True/False).
  5. Arrows: Represent Flowlines indicating execution direction.
  6. Circle: Connects disparate sections across complex diagrams.

Question 5

Write an algorithm and draft pseudocode to check whether a user-entered integer is Prime or Not Prime.

Answer:

Algorithmic Logic:

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We test divisibility from 22 up to N/2\lfloor N / 2 \rfloor.

Pseudocode:

START
    READ N
    SET IsPrime = TRUE
    
    IF N <= 1 THEN
        IsPrime = FALSE
    ELSE
        SET Divisor = 2
        WHILE Divisor <= (N / 2) DO
            IF (N MOD Divisor) == 0 THEN
                IsPrime = FALSE
                BREAK LOOP
            END IF
            Divisor = Divisor + 1
        END WHILE
    END IF
    
    IF IsPrime == TRUE THEN
        PRINT N, "is a Prime Number."
    ELSE
        PRINT N, "is NOT a Prime Number."
    END IF
END

Chapter Summary

The second chapter of the Computer Science book for Class 11 introduces the core concept of Algorithms and modern problem-solving methodologies. An algorithm is a precise, unambiguous set of instructions used to perform computational tasks by transforming inputs into outputs. Algorithms form the backbone of computer science, programming, data analysis, and artificial intelligence.

In this chapter, we explored:

  • The Problem-Solving Lifecycle (Definition, Analysis, Algorithm Design, Coding, Testing & Debugging, Documentation).
  • Key Algorithm Control Structures (Sequential, Selection/Conditional, Iteration/Looping, and Recursion).
  • Core Algorithmic Properties (Knuth's criteria: Input, Output, Definiteness, Finiteness, Effectiveness).
  • Representation Tools: Visual Flowcharts with ANSI geometric symbols and language-agnostic Pseudocode.
  • Manual verification strategies using Trace Tables (Dry Running).
  • Real-life applications including search engine indexing, GPS pathfinding, and e-commerce recommendation systems.

Pro Tip for this Chapter

Ensure you practice the in-text questions provided in the official NCERT PDF. If you find any topic difficult, review the formulas and concepts highlighted above. For advanced doubts, join our classroom coaching in Begusarai.