Overview
This unit introduces students to program coding: how to design, write, test and debug simple computer programs. It covers the basic ideas needed to turn a real-world problem into step-by-step instructions a computer can follow. You will learn what algorithms are, how to draw flowcharts, and how to use variables, data types, input/output, operators, decisions and loops. The unit also explains how to break a program into small reusable parts called functions or procedures, and how lists (arrays) store collections of data. Emphasis is on logical thinking, careful design and clear documentation so that programs run correctly and are easy to understand. These skills prepare students for more advanced coding and help develop problem-solving ability useful across subjects. By the end of the unit you will be able to plan a solution, write a working program in a simple structured style, test it against different cases and fix errors. Learning to code also builds patience and creativity, and gives the tools to create small games, calculators or data tasks that make classroom ideas come alive.
Learning Objectives
- Understand what an algorithm and a flowchart are and be able to create them for small problems.
- Use variables and basic data types correctly to store and manipulate information.
- Write programs that perform input and output operations with the correct order of statements.
- Apply arithmetic and logical operators to build expressions and compute results.
- Use selection statements (if, if-else) to make decisions inside a program.
- Use loop constructs to repeat actions until a condition is met.
- Break problems into functions or procedures and call them with correct parameters.
- Store and access multiple values using arrays (lists) and process them with loops.
- Test, trace and debug programs using simple strategies and produce correct output.
Topics in this chapter
13 topics · tap a topic title to jump straight to it.
What is Programming and Algorithms
What is programming? Programming is the activity of creating a set of instructions a computer can follow to perform tasks. These instructions must be precise, unambiguous and ordered. A program is the written form of these instructions in a language the computer can interpret. Programming teaches you to think logically: break a problem into smaller steps, decide what information is needed, and tell the computer exactly how to use that information.
What is an algorithm? An algorithm is a clear and finite sequence of steps to solve a specific problem. It does not depend on a particular programming language. Instead, it explains the logic of the solution. An algorithm should be correct, clear, and terminate after a finite number of steps. Writing an algorithm first helps catch mistakes before writing code.
Why start with algorithms? Designing an algorithm before coding makes development faster and less error-prone. It is easier to check logic in plain steps or with a flowchart than to correct errors in source code later. Algorithms are also reusable: once you have a method to find the largest of three numbers, you can apply the same logic in many programs.
Characteristics of a good algorithm A good algorithm is:
- Correct: it solves the problem for all valid inputs.
- Efficient: it uses reasonable steps and resources for the task size.
- Simple: steps should be easy to understand and follow.
- Finite: it must finish after a limited number of steps.
How to express an algorithm You can write algorithms in simple numbered steps, in pseudocode that looks like programming statements, or show them as flowcharts. For school problems, choose the method your teacher prefers. Always test an algorithm with sample inputs by doing a dry run on paper: write down the values that change at each step and check that the final result is what you expect.
- Find the largest of three numbers: compare first two, keep the larger, then compare with the third and keep the larger.
- Recipe-like steps to make a cup of tea: boil water, add tea, steep, pour through strainer, add milk/sugar as needed.
- Algorithm to compute average marks: add marks to get sum, divide sum by number of subjects, display result.
- Algorithm: A finite sequence of well-defined instructions to solve a problem
- Program: A set of coded instructions executed by a computer
Flowcharts and Pseudocode
Flowcharts are diagrams that show the flow of control in an algorithm using standard symbols. Standard symbols include an oval for Start/End, a parallelogram for Input/Output, a rectangle for Process or calculation, and a diamond for Decisions that branch into two or more paths. Arrows show the order in which steps happen. A flowchart makes it easy to visualise choices and loops and to spot mistakes such as missing steps or incorrect branching.
Pseudocode is a way to write the logic of a program using plain language mixed with common programming words like READ, WRITE, IF, WHILE, FOR and CALL. It is more detailed than a high-level algorithm written in sentences, but it avoids strict language syntax. Pseudocode should be precise enough for someone to convert it into actual program code without guessing the logic.
When to use each Use a flowchart when you want a clear picture of branching and looping, which helps during class explanation or presentation. Use pseudocode when you are about to write the program because it maps closely to code structure and is faster to write than a detailed flowchart. Both methods support testing: you can walk through them with sample inputs to ensure correct behaviour.
Good practices Keep flowcharts tidy: limit crossing arrows and group related steps. Label decision branches clearly (Yes/No or True/False) and use consistent symbol sizes. For pseudocode, use clear indenting and meaningful names for variables and procedures. Include comments or short notes explaining assumptions such as whether input numbers are positive or whether arrays are 0-based. Teachers often ask for both flowchart and pseudocode for the same problem to show complete understanding.
- Flowchart for deciding whether a number is even: Start -> Input number -> Decision: number mod 2 = 0? -> Yes: Output "Even" -> No: Output "Odd" -> End.
- Pseudocode to find average of three numbers: READ a, b, c; sum = a + b + c; avg = sum / 3; WRITE avg.
- Flowchart symbols: Start/End = Oval, Input/Output = Parallelogram, Process = Rectangle, Decision = Diamond
- Pseudocode style: READ variable, WRITE expression, IF condition THEN ... ELSE ... ENDIF
Variables and Data Types
Variables are named containers that hold data values while a program runs. Imagine each variable as a labelled box where you store a piece of information: a number, a name, or a true/false answer. Variables let a program remember and change values. Use meaningful names such as totalMarks, studentName or counter so that the purpose of each box is clear when reading the code.
Data types describe what kind of value a variable can hold. Common types taught at this level are integers (whole numbers), real or float (numbers with decimal parts), strings (text), and boolean (true or false). Choosing the correct type helps prevent errors: for example, dividing two integers in some languages may give an integer result by truncation, while using real types keeps decimals.
Declaration and assignment Some programming environments require declaring a variable with its type before using it, e.g., INTEGER age. Other environments let you assign a value directly, e.g., age = 12. Assignment uses the equals sign to store a value: marks = 85. You can update a variable with expressions, for example: count = count + 1 increases the stored value by one.
Naming rules and conventions Variable names should start with a letter and may include letters, digits or underscores, depending on language rules in class. Avoid single-letter names except for counters like i or j in loops. Consistent naming style, such as camelCase (totalMarks) or snake_case (total_marks), makes code easier to follow. Add short comments to explain any non-obvious variable purpose.
Common mistakes Using a variable before assigning a value leads to undefined behaviour. Mixing types without conversion (for example adding a number to a string) causes errors in many languages. Be careful with array indices which are also variables: using an out-of-range index causes runtime errors. Always initialize variables where necessary, and document expected ranges or units (for example, marks out of 100).
- Declare and use an integer: marks = 85; output marks + 5 gives 90.
- String example: name = "Riya"; output "Hello " + name shows Hello Riya.
- Boolean example: isOpen = true; if isOpen then WRITE "Shop open" else WRITE "Closed".
- Assignment: variable = expression
- Update pattern: variable = variable + value (e.g., i = i + 1)
- Type rule: integer + integer = integer, integer / integer may produce real
Input and Output Statements
Input allows a program to receive data from a user, a file, or another system. Typical input statements use words like READ or INPUT followed by variable names. A good input prompt explains what is expected, such as "Enter number of students:" so the user provides the correct type and number of values. When writing programs, think about the order of inputs and validate them where necessary.
Output displays results or messages to the user. Output statements use words like WRITE, PRINT or DISPLAY and can combine text with variable values. For clarity, include labels when printing values: instead of printing 72, print "Average = 72". Formatting matters when printing lists or tables; align columns and use clear headings when required.
Type handling and conversion Input is often read as text and may need conversion to numbers. Some teaching languages convert automatically; others require explicit conversion functions. Watch for invalid inputs such as letters where numbers are expected. Include checks and helpful error messages so the program does not crash or produce misleading results.
Input order and default values Ensure that every READ statement appears before the code that uses that value. For optional inputs or menu choices, provide default values or instructions. When reading multiple values, decide whether to read them on one line separated by spaces or on separate lines. For exams, follow the input/output style shown in examples or teacher instructions.
Testing I/O Test with normal inputs, boundary cases such as zero or maximum values, and invalid inputs to see if the program handles them gracefully. Check output formatting and messages so a user unfamiliar with the program can understand the results without extra explanation.
- Read two numbers a and b; compute sum = a + b; WRITE "Sum = " + sum.
- Ask for student's name; READ name; WRITE "Welcome, " + name.
- Read marks and check: READ marks; IF marks >= 35 THEN WRITE "Pass" ELSE WRITE "Fail" ENDIF.
- Input pattern: READ variable
- Output pattern: WRITE expression or PRINT text + variable
Operators and Expressions
Operators are the building blocks for forming expressions that perform calculations or tests. At this level we use three main groups of operators: arithmetic, relational and logical. Arithmetic operators like +, -, *, / and % perform mathematical calculations. Relational operators compare two values and return true or false, using symbols like =, !=, <, >, <= and >=. Logical operators combine boolean results and include AND, OR and NOT.
Expressions are combinations of variables, constants and operators that evaluate to a single value. For example, total = price * quantity + tax is an arithmetic expression. A condition such as age >= 18 is a relational expression that evaluates to true or false. Logical expressions combine such conditions: (age >= 18) AND (hasID = true).
Operator precedence determines the order in which parts of an expression are evaluated. Multiplication and division are done before addition and subtraction; relational checks come after arithmetic; logical operators are evaluated after relational operators. Use parentheses to make the intended order explicit and improve readability. For example, (a + b) * c forces addition before multiplication.
Integer vs real operations Be aware that dividing integers may produce integer results in some languages (discarding the fraction), while using real types preserves decimals. The modulus operator (%) gives the remainder of integer division and is useful for checking even/odd numbers or cycles. Logical operators short-circuit in many languages: an AND stops evaluating if the first part is false because the whole expression cannot be true.
Common mistakes Mixing types without conversion, forgetting parentheses, and misunderstanding operator precedence cause wrong results. When writing complex expressions, break them into smaller steps or use temporary variables for clarity. Always test expressions with values that reveal precedence or type errors.
- Expression: total = price * quantity + tax. Compute multiplication first, then addition.
- Decision with relational operator: IF score >= 40 THEN WRITE "Pass" ELSE WRITE "Fail" ENDIF.
- Logical example: IF age >= 18 AND hasID == true THEN WRITE "Allowed" ELSE WRITE "Not allowed" ENDIF.
- Arithmetic operators: +, -, *, /, %
- Relational operators: =, !=, <, >, <=, >=
- Logical operators: AND, OR, NOT
- Precedence rule: Parentheses (), then *, /, %, then +, -, then relational, then logical
Sequence and Simple Programs
Sequence is the simplest control structure in which statements execute one after another. Most programs begin as a sequence: read inputs, perform calculations, and display outputs. Each step must be in the correct order so that values used in a statement have already been assigned.
Designing small programs Start with a clear problem statement: what inputs are needed and what outputs are expected. Write an algorithm in numbered steps or pseudocode and then map each step to program statements. Keep the program short and focused on one task. Simple programs are ideal for practicing correct use of variables, input/output and expressions.
Structure of a simple program A typical small program contains: a start point, input statements, processing statements, output statements and an end. Use comments to describe the purpose of the program and the meaning of key variables. Test parts of the program independently. For example, test the input routine separately from the calculation routine to find errors quickly.
Examples of simple programs Friendly examples are calculators for two numbers, temperature converters between Celsius and Fahrenheit, area or perimeter calculators for shapes, and small grade calculators that compute total and average marks. These programs use sequence to perform their steps and reinforce basic skills.
Checking and testing Always dry-run the program with sample inputs and list variable values step by step. Test normal cases, boundary values such as zero or negative inputs if allowed, and large values to ensure no overflow or incorrect formatting. Good testing at this stage prevents more complex errors when you add selections and loops later.
- Program to add two numbers: READ a; READ b; sum = a + b; WRITE sum.
- Area of rectangle: READ length; READ breadth; area = length * breadth; WRITE area.
- Temperature converter: READ celsius; fahrenheit = (celsius * 9 / 5) + 32; WRITE fahrenheit.
- Sequence structure: Step1; Step2; Step3; ...
- Area of rectangle: area = length * breadth
- Celsius to Fahrenheit: F = (C * 9 / 5) + 32
Selection: IF and IF-ELSE
Selection statements allow a program to choose different actions depending on conditions. The basic form is IF condition THEN action ENDIF, used when an action should run only if a condition is true. IF-ELSE extends this to provide an alternative action when the condition is false: IF condition THEN action1 ELSE action2 ENDIF. These constructs are essential for decisions like pass/fail, eligibility checks, and menu choices.
Writing clear conditions Conditions use relational and logical operators to compare values and combine subconditions. Make conditions readable by using parentheses and descriptive variable names. For example: IF (age >= 18) AND (hasID = true) THEN ... checks two requirements clearly.
Nested IF and multiple choices Sometimes you need to check several conditions in sequence, such as grading ranges. You can nest IF statements inside others or chain conditions using IF...ELSE IF...ELSE (if your pseudocode style allows it). Keep nesting shallow because deep nesting makes code harder to read. For more than two branches, a CASE or SWITCH structure is cleaner if available.
Common pitfalls Off-by-one errors in ranges (for example using > instead of >=) lead to incorrect branching. Forgetting an ELSE path can leave the program without guidance for some inputs. Also be careful to use correct logical operators: using OR where AND is needed changes the logic.
Testing selection Test each branch with inputs that make the condition true and false, and test boundary values that are exactly on limits. Include tests for unexpected input, such as negative numbers or empty strings, to ensure the program responds sensibly and does not crash.
- IF marks >= 50 THEN WRITE "First Division" ELSE WRITE "Lower Division" ENDIF.
- Check sign of number: IF n > 0 THEN WRITE "Positive" ELSE IF n < 0 THEN WRITE "Negative" ELSE WRITE "Zero" ENDIF ENDIF.
- Validate age: IF age >= 18 THEN WRITE "Adult" ELSE WRITE "Minor" ENDIF.
- IF condition THEN statements ENDIF
- IF condition THEN statements ELSE statements ENDIF
- Nested IF: IF condition1 THEN IF condition2 THEN ... ENDIF ENDIF
Loops: WHILE and FOR
Loops let a program repeat actions multiple times without writing the same code again. They are used when a task must be performed repeatedly, like summing many numbers, processing each item in a list, or responding to user input until a condition is met. Two common loop types are WHILE (repeat while a condition is true) and FOR (repeat a known number of times).
WHILE loops check the condition before running the loop body. They are suited to situations where the number of iterations is not known beforehand. For example, reading numbers until the user enters 0 uses a WHILE loop. Remember to update variables used in the condition inside the loop so it eventually becomes false and the loop terminates; otherwise you risk an infinite loop.
FOR loops are used when you know how many times you want to repeat an action. A FOR loop typically sets a counter to a start value, repeats until the counter reaches an end value, and updates the counter each iteration. Use FOR to iterate over array indices or to perform an action a fixed number of times.
Loop control and nested loops Some languages provide statements like BREAK to exit a loop early or CONTINUE to skip to the next iteration. Nested loops are loops inside loops and are useful for working with two-dimensional data, such as tables. Be cautious with nested loops: they multiply the number of iterations and may slow the program if sizes are large.
Testing loops Test loops with zero iterations, one iteration, and many iterations to check boundaries. Trace the loop by listing the counter and relevant variable values after each pass to ensure the correct behaviour. If a loop is not finishing, inspect how the condition depends on variables and whether they change appropriately within the loop.
- WHILE example: i = 1; sum = 0; WHILE i <= 5 DO sum = sum + i; i = i + 1; ENDWHILE; WRITE sum.
- FOR example: sum = 0; FOR i = 1 TO 5 DO sum = sum + i; ENDFOR; WRITE sum.
- Using loop with array: FOR i = 0 TO n-1 DO total = total + marks[i]; ENDFOR; avg = total / n.
- WHILE condition DO statements ENDWHILE
- FOR variable = start TO end DO statements ENDFOR
- Loop invariant: ensure change leads to termination (e.g., i = i + 1)
Functions and Procedures
Functions and procedures are named blocks of code designed to perform a single, well-defined task. A function usually returns a value to the place where it was called; a procedure performs an action but may not return a value. Using functions and procedures helps divide a program into smaller, manageable parts that are easier to write, test and reuse.
Design and purpose Each function should have a clear purpose and a small footprint: do one thing and do it well. Describe required inputs as parameters and define what the function will return. For example, a function calculateAverage(marks, n) might take an array and its size, and return the average. Writing a function header and a brief comment describing expected inputs and outputs is good practice.
Calling and parameters Call a function by using its name and providing arguments. Parameters are the names used inside the function; arguments are the actual values passed. At this level, focus on passing values (call by value), where the function cannot change the original variable outside its scope. Some languages allow passing by reference, but that is an advanced topic.
Benefits Reusability: write once, use many times. Testing: you can test functions individually with sample inputs. Readability: the main program becomes a set of high-level calls, making the overall logic easier to follow. Maintainability: fix or improve the function and all callers benefit immediately.
Examples and testing Write small functions like square(x) returning x*x, or isEven(n) returning true if n%2=0. Use functions in loops or decision statements. Test functions with typical, boundary and invalid inputs to ensure they behave correctly. Document any assumptions such as non-negative input or non-empty arrays so callers know how to use the function safely.
- Function example: function square(x) return x * x; main: READ n; WRITE square(n).
- Procedure example: procedure greet(name) WRITE "Hello " + name; main: READ name; CALL greet(name).
- Use function in loop: FOR i = 1 TO 5 DO WRITE square(i); ENDFOR.
- Function structure: FUNCTION name(parameters) RETURNS value ... END FUNCTION
- Procedure structure: PROCEDURE name(parameters) ... END PROCEDURE
- Call pattern: result = name(arguments)
Arrays (Lists) and Basic Operations
Arrays or lists are structures that store several values of the same type under one name. Each value is stored in a position or index. Arrays make it easy to represent collections such as marks for a class, a series of temperatures, or a list of names. Using arrays avoids needing many separate variables like mark1, mark2, mark3, which are hard to manage.
Declaration and use Depending on the teaching convention, arrays may start at index 0 or 1. When declaring an array, specify its size if required. For example, declare marks[5] to store five values. To access an element, use the array name with an index: marks[2] refers to the third element if indexing starts at 0. Always ensure index values stay within the valid range to prevent errors.
Common operations Reading values into an array is done with a loop: FOR i = 0 TO n-1 READ arr[i] ENDFOR. Traversing with loops lets you compute totals, find the largest or smallest element, count elements satisfying a condition, or copy values to another array. Sorting arranges elements in order; simple methods like bubble sort compare adjacent elements and swap them repeatedly until the array is ordered.
Searching Linear search checks each element sequentially and stops when the target is found or the end is reached. For small arrays this is simple and sufficient. Record the index of the found element or a sentinel like -1 if not found. For larger arrays, efficient methods exist but are beyond the current class level.
Edge cases and testing Test with arrays of size zero (if allowed), size one, and typical sizes. Watch for off-by-one errors: loops should match the chosen index range. Use clear variable names like n for size and i for index and comment whether your array starts at 0 or 1.
- Store five marks using an array: FOR i = 0 TO 4 READ marks[i] ENDFOR; compute total and average in another loop.
- Find maximum: max = marks[0]; FOR i = 1 TO 4 IF marks[i] > max THEN max = marks[i] ENDIF ENDFOR; WRITE max.
- Linear search: FOR i = 0 TO n-1 IF arr[i] = key THEN WRITE i; EXIT ENDFOR.
- Array indexing: name[index] (index range depends on convention)
- Sum of array: total = Σ arr[i] for i = 0 to n-1
- Average: avg = total / n
Debugging and Tracing Programs
Debugging is the process of locating, understanding and fixing errors in a program. Errors can be syntax errors (mistakes in the code that prevent the program from running), runtime errors (problems that happen while the program runs, such as division by zero), or logical errors (the program runs but produces incorrect results). The goal of debugging is not only to fix the visible symptom but to understand and correct the underlying cause.
Tracing is a useful debugging technique where you follow the program step by step and record the values of variables at each point. You can do this manually on paper or include temporary output statements in the program to print variable values during execution. Tracing helps you see where a value differs from what you expect and narrows down the place to search for the mistake.
Practical debugging steps First, reproduce the error consistently with a test case. Read any error messages carefully because they often indicate the line number or type of problem. Insert prints or use a trace table to capture variable values at important steps. Simplify the code to isolate the part causing the issue, and test each part separately. After fixing, rerun all relevant tests to ensure the change did not introduce new errors.
Common mistakes to look for Off-by-one errors in loops, wrong operator precedence, using the wrong variable name, forgetting to initialize variables, and index out-of-bounds for arrays are frequent sources of bugs. Logical errors such as using <= instead of < can lead to wrong outputs without crashing, so careful testing with edge cases is important.
Good habits Write small programs and test frequently, keep code well commented, and use meaningful variable names to make tracing easier. Maintain a simple log of test cases and their results so you can check that fixes remain correct over time.
- Trace a loop that sums numbers: list variable values of i and sum after each iteration to verify correctness.
- Debug incorrect average: check whether sum is integer and division produces integer result; adjust to use real division.
- Fix off-by-one: if a loop runs one too many times, change boundary from <= to < or adjust start/end indexes.
- Common debugging steps: Reproduce error -> Isolate -> Trace -> Fix -> Test
- Trace table: list statements vs variable values after each statement
Program Design and Documentation
Program design is the planning phase where you think through a problem and decide how the program will work before writing code. Good design begins with a clear problem statement: specify inputs, outputs and any constraints. Then write an algorithm or draw a flowchart and prepare pseudocode. Decide on data structures such as variables or arrays, and identify functions or procedures for repeated tasks. Planning reduces errors and makes coding faster.
Modular design Break a program into modules where each module does one job, for example input handling, processing, or output. Use functions for tasks that recur, and keep each function short and focused. This makes testing easier because you can test each module independently before combining them into the main program.
Documentation Document both inside and outside the code. Header comments should give the program name, purpose, author, date and brief instructions for running it. Inline comments explain tricky parts or the intention behind particular choices. External documentation, such as a short user guide and a list of test cases with expected results, helps teachers and classmates understand and run your program.
Naming and style Use meaningful variable and function names, consistent indentation, and readable formatting. Follow any style rules your teacher gives. Consistent style not only makes your code easier to read, it also earns marks in assessments where clarity is evaluated.
Testing plan Prepare test cases that include normal inputs, boundary cases and invalid inputs. Record expected outputs and compare them to actual outputs. A simple test table shows input, expected output, and actual output, and notes whether the test passed. This demonstrates a careful approach to development and helps in debugging.
- Design steps listed for a student marks program: define inputs (n, marks), algorithm to compute total and average, functions to read marks and calculate average, main program to call functions.
- Documentation header: // Program: AverageCalculator // Author: A. Student // Purpose: Compute average of n numbers
- Test cases table with input, expected output and actual output for three scenarios
- Design cycle: Understand -> Plan (algorithm) -> Design (flowchart/pseudocode) -> Code -> Test -> Document
- Documentation elements: Purpose, Inputs, Outputs, Assumptions, Sample Tests
Project: Putting It All Together
Class project asks you to use the techniques learned in this unit to build a small, complete program. The project should show your ability to analyse a problem, design a solution, write working code and document it. Choose a manageable task such as a student marks manager, a small calculator, a number-guessing game, or a contact list. The goal is to demonstrate clear logic, correct use of variables, selection and looping, arrays where needed, and at least one function or procedure.
Planning the project Begin with a short problem statement describing what the program does and who will use it. List inputs and expected outputs. Draw a flowchart for the main workflow and prepare pseudocode for each module. Decide on function names and what parameters they need. Plan test cases that include typical inputs, boundary values and invalid inputs. A project plan showing tasks and estimated time is useful for group work.
Implementing the project Code module by module, and test each piece before integrating. Use clear variable names and include comments explaining main steps. For user interaction, provide friendly prompts and validation messages. If the project has a menu, ensure each choice calls the correct function and there is a way to return to the menu or exit cleanly.
Documentation and presentation Prepare a short user guide with instructions to run the program, sample input and output, and descriptions of any assumptions. Include the algorithm or flowchart, the pseudocode or code listing, and a table of test cases showing expected and actual outputs. During assessment, be ready to explain design choices and to run the program for the examiner.
Assessment focus Teachers look for correct working logic, readable and well-documented code, appropriate testing, and a clear demonstration of understanding. A small well-tested project with good documentation is better than a large incomplete one. Practice presenting the program and discussing how you tested and debugged it.
- Project idea: Student Marks Manager that reads marks, calculates total and average, finds highest mark and gives pass/fail count.
- Project idea: Simple calculator supporting add, subtract, multiply and divide with a menu using IF or CASE structure.
- Project idea: Number guessing game where the program picks a number and the user guesses with hints (higher/lower) until correct.
- Project checklist: Problem statement, Algorithm, Flowchart/Pseudocode, Code, Test cases, Documentation
- Acceptance criteria: Program runs, passes test cases, has comments and a short user guide
Key Concepts
- Algorithm
- A finite, ordered set of precise steps to solve a problem.
- Flowchart
- A visual diagram using standard symbols to represent steps and decisions in an algorithm.
- Pseudocode
- A plain-language structured description of program steps that resembles code.
- Variable
- A named storage location that holds a value which can change during program execution.
- Data Type
- A category that specifies the kind of data a variable can hold, such as integer or string.
- Input/Output
- Statements that read data into a program and display results to the user.
- Operator
- A symbol that performs arithmetic, comparison or logical operations on values or expressions.
- Expression
- A combination of variables, constants and operators that evaluates to a value.
- Sequence
- A control flow where statements execute one after another in order.
- Selection
- A control structure that chooses between alternative actions using IF or IF-ELSE.
- Loop
- A control structure that repeats statements while a condition holds or for a set number of times.
- Function
- A named block of code that performs a task and usually returns a value.
- Array
- A collection of items of the same type stored under a single name and accessed by index.
- Debugging
- The process of finding, isolating and fixing errors in a program.
- Trace
- A step-by-step record of variable values and statements during program execution to find errors.
- Documentation
- Comments and written notes that explain what the program does, its inputs, outputs and design.
Practice Questions
-
Write an algorithm to find the largest of three numbers. / तीन संख्याओं में सबसे बड़ी संख्या खोजने का एल्गोरिदम लिखिए।
Show answer
Step 1: Start. Step 2: Read A, B, C. Step 3: If A >= B and A >= C then largest = A else if B >= A and B >= C then largest = B else largest = C. Step 4: Write largest. Step 5: End. / चरण 1: प्रारंभ। चरण 2: A, B, C पढ़िए। चरण 3: यदि A >= B और A >= C तो largest = A अन्यथा यदि B >= A और B >= C तो largest = B अन्यथा largest = C। चरण 4: largest लिखिए। चरण 5: समाप्त।
-
Draw a flowchart to check whether a number is even or odd. / किसी संख्या के सम या विषम होने की जाँच करने का फ्लोचार्ट बनाइए।
Show answer
Start -> Input n -> Decision: n % 2 = 0 ? If Yes -> Output 'Even' -> End; If No -> Output 'Odd' -> End. / प्रारंभ -> n इनपुट करें -> निर्णय: n % 2 = 0 ? यदि हाँ -> 'Even' 출력 करें -> समाप्त; यदि नहीं -> 'Odd' 출력 करें -> समाप्त।
-
Give two differences between a variable and an array. / एक वेरिएबल और एक ऐरे के बीच दो अंतर बताइए।
Show answer
1) A variable stores a single value at a time; an array stores many values under one name. 2) A variable is accessed by its name; an array element is accessed by name and index (for example a[0]). / 1) एक वेरिएबल एक समय में एक ही मान रखता है; एक ऐरे एक नाम के अंतर्गत कई मान रखता है। 2) एक वेरिएबल को उसके नाम से पहुँचाते हैं; एक ऐरे तत्व को नाम और सूचकांक से पहुँचाते हैं (जैसे a[0])।
-
Write a program (in pseudocode) to compute the sum of first n natural numbers using a loop. / लूप का उपयोग कर पहले n प्राकृतिक संख्याओं का योग निकालने का प्रोग्राम (प्स्यूडोकोड) लिखिए।
Show answer
READ n; sum = 0; FOR i = 1 TO n DO sum = sum + i ENDFOR; WRITE sum. / n पढ़िए; sum = 0; FOR i = 1 TO n DO sum = sum + i ENDFOR; sum लिखिए।
-
Explain what debugging is and name two techniques used in debugging. / डीबगिंग क्या है समझाइए और डीबगिंग में उपयोग की जाने वाली दो तकनीकों के नाम बताइए।
Show answer
Debugging is finding and fixing errors in a program. Two techniques: (1) Tracing with print statements to show variable values at points in the program; (2) Testing with different test cases including edge values to reproduce and isolate the bug. / डीबगिंग प्रोग्राम में त्रुटियों को ढूँढना और ठीक करना है। दो तकनीकें: (1) प्रिंट स्टेटमेंट से ट्रेस करना ताकि प्रोग्राम के बिंदुओं पर वेरिएबल मान दिखें; (2) अलग-अलग परीक्षण मामलों सहित सीमा मानों के साथ टेस्ट करना ताकि बग को फिर से बनाया और अलग किया जा सके।
-
Write pseudocode for a function maxOfTwo(a,b) that returns the larger of two numbers and show how to call it. / दो संख्याओं में बड़ी संख्या लौटाने वाला maxOfTwo(a,b) फंक्शन का प्स्यूडोकोड लिखिए और इसे कैसे कॉल करेंगे दिखाइए।
Show answer
FUNCTION maxOfTwo(a, b) IF a >= b THEN RETURN a ELSE RETURN b ENDIF END FUNCTION. Call example: READ x, y; max = maxOfTwo(x, y); WRITE max. / FUNCTION maxOfTwo(a, b) IF a >= b THEN RETURN a ELSE RETURN b ENDIF END FUNCTION. कॉल का उदाहरण: x, y पढ़िए; max = maxOfTwo(x, y); max लिखिए।
-
What will be the output of the following pseudocode? READ n; sum = 0; FOR i = 1 TO n DO sum = sum + i ENDFOR; WRITE sum. (If input n = 4) / निम्न pseudocode का आउटपुट क्या होगा? (यदि n = 4 है) READ n; sum = 0; FOR i = 1 TO n DO sum = sum + i ENDFOR; WRITE sum.
Show answer
When n = 4, the loop adds 1+2+3+4 so sum = 10. Output: 10. / जब n = 4 होगा, लूप 1+2+3+4 जोड़ता है इसलिए sum = 10। आउटपुट: 10।
-
Describe how you would test a program that computes the average of marks for 5 subjects. / आप 5 विषयों के अंक का औसत निकालने वाला प्रोग्राम कैसे टेस्ट करेंगे, बताइए।
Show answer
Prepare test cases: normal case (e.g., 80,70,60,50,40), all zeros (0,0,0,0,0), maximum values (100,100,100,100,100), and a mix including boundary values. Check whether average is computed with correct decimal precision and see if program handles invalid inputs (like negative marks) with a message. Record expected and actual outputs. / परीक्षण मामलों की तैयारी कीजिए: सामान्य मामला (जैसे 80,70,60,50,40), सभी शून्य (0,0,0,0,0), अधिकतम मान (100,100,100,100,100), और एक मिश्रण जिसमें सीमा मान शामिल हों। जाँच कीजिए कि औसत को दशमलव सहित सही ढंग से निकाला गया है और प्रोग्राम अवैध आंकड़ों (जैसे निगेटिव अंक) को संदेश के साथ संभालता है या नहीं। अपेक्षित और वास्तविक आउटपुट रिकॉर्ड कीजिए।
-
Give pseudocode to search for a value key in an array arr of size n and return the index or -1 if not found. / एक n आकार के ऐरे arr में key खोजने और यदि न मिले तो -1 लौटाने का प्स्यूडोकोड दीजिए।
Show answer
index = -1; FOR i = 0 TO n-1 DO IF arr[i] = key THEN index = i; EXIT ENDFOR; WRITE index. / index = -1; FOR i = 0 TO n-1 DO IF arr[i] = key THEN index = i; EXIT ENDFOR; index लिखिए।
-
Explain why meaningful variable names and comments are important in a program. / प्रोग्राम में अर्थपूर्ण वेरिएबल नाम और कमेंट्स क्यों महत्वपूर्ण हैं, समझाइए।
Show answer
Meaningful names and comments make code easier to read and understand for others and for yourself later. They explain the purpose of variables and steps, help find errors faster, and make maintenance and marking simpler for teachers. Clear code shows good planning and style. / अर्थपूर्ण नाम और कमेंट्स कोड को दूसरों और भविष्य में खुद के लिए पढ़ना और समझना आसान बनाते हैं। वे वेरिएबल और कदमों के उद्देश्य को समझाते हैं, त्रुटियों को जल्दी ढूँढने में मदद करते हैं, और रखरखाव तथा शिक्षकों के लिए मूल्यांकन सरल बनाते हैं। स्पष्ट कोड अच्छा परिकलन और शैली दर्शाता है।
Related Laws & Principles
Explore allFoundational laws & principles connected to this chapter — tap to open in the Laws Explorer.