Se connecterS'abonner

Chapitre 26

Algorithms and programming

Lecture : 21 minQuiz de 12 questions

# Algorithms and programming ## Objectifs et prérequis This chapter aims to develop students’ ability to design, analyze, and implement algorithms using fundamental programming constructs. By the end of this chapter, students will be able to: - Understand and apply selection and loop control structures in algorithm design. - Construct and interpret flowcharts to represent algorithms visually. - Perform dry runs to trace algorithm execution and verify correctness. - Write, test, and refine code in a high-level language (pseudocode or Python-like syntax) across three progressive writing tasks. - Integrate all concepts in a comprehensive activity that simulates real-world problem-solving. Prerequisites: - Familiarity with basic ICT concepts (input, output, storage, processing). - Understanding of variables, data types (integer, string, boolean), and basic operators. - Ability to read and write simple pseudocode. - Logical reasoning skills developed in Lower Sixth ICT. --- ## I. Selection Control Structure ### Context Selection control structures allow a program to make decisions based on conditions. They are essential for creating dynamic responses in software, such as validating user input, grading systems, or determining eligibility for services. In Cameroonian contexts, selection structures are used in mobile money transaction verification (e.g., checking if PIN is correct), healthcare triage systems (e.g., fever > 38°C triggers alert), and agricultural advisory apps (e.g., if rainfall < 50mm, recommend irrigation). ### Definitions > A selection control structure (or conditional statement) executes one block of code if a condition is true, and another (or none) if false. > The most common forms are: `if`, `if-else`, and `if-elif-else` (or nested if). > Conditions are Boolean expressions that evaluate to `True` or `False`. ### Key Concepts - **Condition**: A logical expression using comparison operators (`==`, `!=`, `>`, `<`, `>=`, `<=`) and logical operators (`AND`, `OR`, `NOT`). - **Branching**: The program flow splits into two or more paths based on condition evaluation. - **Nesting**: Placing one selection structure inside another to handle multiple criteria. - **Short-circuit evaluation**: In `AND`/`OR`, evaluation stops as soon as the result is determined. ### Examples (Cameroonian/African Context) 1. **Voter Eligibility Check**: ```pseudocode IF age >= 18 THEN OUTPUT "Eligible to vote" ELSE OUTPUT "Not eligible to vote" ENDIF ``` Used in civic education apps during elections in Yaoundé or Douala. 2. **Malaria Symptom Checker (Health App)**: ```pseudocode IF temperature > 38.5 AND headache = TRUE THEN OUTPUT "Suspect malaria – seek test" ELSE IF temperature > 37.5 THEN OUTPUT "Monitor symptoms" ELSE OUTPUT "No fever detected" ENDIF ``` Reflects WHO guidelines adapted for community health workers in the North Region. 3. **Crop Yield Advisor (Agriculture App)**: ```pseudocode IF soil_pH < 5.5 THEN OUTPUT "Apply lime to reduce acidity" ELSE IF soil_pH > 7.5 THEN OUTPUT "Apply sulfur to reduce alkalinity" ELSE OUTPUT "Soil pH is optimal" ENDIF ``` Based on IRAD recommendations for cocoa farms in the Southwest. ### Vocabulary to Retain - Condition - Boolean expression - Branching - Nesting - Short-circuit evaluation ### Exam-Style Question with Plan **Question**: A mobile banking app in Cameroon allows users to transfer money only if: (1) the account balance is sufficient, (2) the recipient’s number is registered, and (3) the transaction amount is between 100 and 500,000 XAF. Write pseudocode using selection structures to validate a transfer request. Output appropriate messages for each failure case and a success message if all conditions are met. **Plan**: 1. Define variables: `balance`, `recipientRegistered` (boolean), `amount`. 2. Use nested `if` statements to check each condition in sequence. 3. First check: `IF amount < 100 OR amount > 500000` → invalid amount. 4. Second check: `ELSE IF balance < amount` → insufficient funds. 5. Third check: `ELSE IF recipientRegistered = FALSE` → unregistered recipient. 6. Final `ELSE` → success: transfer approved. 7. Include `OUTPUT` statements for each case. 8. Verify logic with test cases (e.g., amount=50, balance=1000, recipientRegistered=TRUE). --- ## II. Loop Control Structure ### Context Loop control structures enable repetition of a block of code until a condition is met. They are vital for processing lists, performing calculations, simulating processes, and handling user interactions. In African ICT applications, loops power systems like USSD menus (repeating until user exits), sensor data logging (e.g., weather stations in Garoua), and inventory management in markets (e.g., counting stock items in Bamenda markets). ### Definitions > A loop control structure repeats a set of instructions as long as a specified condition remains true. > The two main types are: `while` loops (pre-test) and `for` loops (counter-controlled). > Infinite loops occur when the exit condition is never met; they must be avoided or intentionally used with break statements. ### Key Concepts - **Initialization**: Setting up the loop control variable before the loop starts. - **Condition**: The Boolean expression tested before each iteration (in `while`) or after (in `do-while`, though less common in pseudocode). - **Update**: Modifying the loop variable to eventually falsify the condition (e.g., `counter = counter + 1`). - **Off-by-one error**: A common mistake where the loop runs one time too many or too few (e.g., using `<= n` instead of `< n` for n iterations). - **Break and continue**: `break` exits the loop immediately; `continue` skips to the next iteration. ### Examples (Cameroonian/African Context) 1. **USSD Menu Navigation (Mobile Money)**: ```pseudocode OUTPUT "Welcome to MTN Mobile Money" INPUT choice WHILE choice != 0 DO IF choice = 1 THEN OUTPUT "Check balance" ELSE IF choice = 2 THEN OUTPUT "Send money" ENDIF OUTPUT "Enter choice (0 to exit):" INPUT choice ENDWHILE OUTPUT "Thank you for using MTN Mobile Money" ``` Reflects real USSD flow in Cameroon; loop continues until user selects 0. 2. **Rainfall Data Logger (Weather Station in Maroua)**: ```pseudocode SET day = 1 SET totalRainfall = 0 WHILE day <= 30 DO INPUT rainfallToday SET totalRainfall = totalRainfall + rainfallToday SET day = day + 1 ENDWHILE OUTPUT "Total rainfall for the month: ", totalRainfall, " mm" ``` Used by MINADER to monitor seasonal patterns in the Far North. 3. **Stock Inventory Check (Market in Buea)**: ```pseudocode SET itemIndex = 0 SET lowStockCount = 0 WHILE itemIndex < LENGTH(stockList) DO IF stockList[itemIndex] < 10 THEN SET lowStockCount = lowStockCount + 1 ENDIF SET itemIndex = itemIndex + 1 ENDWHILE OUTPUT "Number of items with low stock: ", lowStockCount ``` Helps traders identify items needing restocking before market day. ### Vocabulary to Retain - Initialization - Condition - Update - Off-by-one error - Break - Continue ### Exam-Style Question with Plan **Question**: A teacher in Bamenda wants to input scores for 20 students and calculate the average. However, if a score is negative, it should be ignored (treated as invalid). Write pseudocode using a loop to input 20 scores, skip negative values, and compute the average of valid scores. If no valid scores are entered, output “No valid scores”. **Plan**: 1. Initialize: `countValid = 0`, `sumScores = 0`, `i = 1`. 2. Use a `while` loop: `WHILE i <= 20 DO`. 3. Inside loop: `INPUT score`. 4. Check: `IF score >= 0 THEN` → add to sum and increment count. 5. Else: do nothing (skip invalid score). 6. Update: `SET i = i + 1`. 7. After loop: `IF countValid = 0 THEN` → output “No valid scores”. 8. Else: `OUTPUT sumScores / countValid`. 9. Test with edge cases: all negative, all zero, mixed values. --- ## III. Drawing Flowcharts ### Context Flowcharts are graphical representations of algorithms using standardized symbols. They aid in planning, debugging, and communicating logic before coding. In Cameroonian technical education, flowcharts are used in national exams (GCE A-Level ICT) and in industry for documenting systems like e-health platforms or agricultural advisory tools. They bridge the gap between abstract logic and implementation. ### Definitions > A flowchart is a diagram that uses geometric shapes connected by arrows to represent the sequence of steps and decisions in an algorithm. > Standard symbols: > - Oval: Start/End > - Rectangle: Process (action or calculation) > - Diamond: Decision (selection) > - Parallelogram: Input/Output > - Arrow: Flow of control ### Key Concepts - **Sequence**: Steps executed in order (rectangles in a line). - **Selection**: Diamond symbol with two outgoing arrows (True/False). - **Iteration**: Loop shown by arrows returning to an earlier step (often a decision diamond). - **Clarity**: Avoid crossing lines; use consistent spacing and labeling. - **Modularity**: Complex algorithms can be broken into subcharts (though not required at this level). ### Examples (Cameroonian/African Context) 1. **Flowchart for Voter Eligibility (Selection)**: - Start → Input age → Decision: age >= 18? - Yes → Output “Eligible” → End - No → Output “Not eligible” → End 2. **Flowchart for Monthly Rainfall Sum (Loop)**: - Start → Set day=1, total=0 → Decision: day <= 30? - Yes → Input rainfall → total = total + rainfall → day = day + 1 → back to decision - No → Output total → End 3. **Flowchart for ATM Withdrawal (Selection + Loop)**: - Start → Input PIN → Decision: PIN correct? - Yes → Input amount → Decision: amount <= balance AND amount <= daily limit? - Yes → Dispense cash → Update balance → End - No → Output “Insufficient funds or limit exceeded” → End - No → Output “Invalid PIN” → End *(Note: No loop here; but if allowing retry, a loop would wrap PIN input)* ### Vocabulary to Retain - Start/End symbol - Process symbol - Decision symbol - Input/Output symbol - Flow line (arrow) ### Exam-Style Question with Plan **Question**: Draw a flowchart for a program that calculates the factorial of a positive integer n (n! = n × (n-1) × ... × 1). The program should first validate that n is positive; if not, it outputs an error. Use a loop to compute the factorial. **Plan**: 1. Start symbol. 2. Input n (parallelogram). 3. Decision diamond: n > 0? - No → Output “Error: n must be positive” (parallelogram) → End (oval). - Yes → Proceed. 4. Initialize: factorial = 1, i = 1 (two rectangles or one combined). 5. Decision diamond: i <= n? - No → Output factorial (parallelogram) → End. - Yes → Process: factorial = factorial × i (rectangle). 6. Process: i = i + 1 (rectangle). 7. Arrow from i = i + 1 back to decision diamond (i <= n?). 8. Ensure all symbols are correctly shaped and labeled; arrows show clear flow. 9. Neat layout: start at top, end at bottom; decisions split left/right (True/Right, False/Left is common convention). --- ## IV. Dry Running ### Context Dry running (or trace table) is a manual technique to verify an algorithm’s logic by simulating its execution step-by-step with sample data. It helps identify logic errors before coding. In Cameroonian classrooms, dry running is emphasized in practical exams where students must predict output without executing code. It builds computational thinking and is used in debugging real systems like election result tabulators or vaccine distribution trackers. ### Definitions > Dry running is the manual execution of an algorithm or code segment using a trace table to record the values of variables at each step. > A trace table includes columns for each variable and a row for each line executed or iteration. ### Key Concepts - **Trace Table**: A grid with variable names as columns and step numbers as rows. - **Step-by-step Execution**: Follow the algorithm line by line, updating variable values as instructed. - **Focus on Changes**: Only record when a variable’s value changes; otherwise, carry forward the previous value. - **Identifying Errors**: Off-by-one, incorrect condition, wrong initialization, or infinite loop become visible in the table. - **Test Data Selection**: Use typical, edge, and invalid cases (e.g., zero, negative, boundary values). ### Examples (Cameroonian/African Context) 1. **Dry Run: Voter Eligibility (n=17)** | Step | age | Output | |------|-----|----------------------| | 1 | 17 | (input) | | 2 | 17 | age >= 18? → False | | 3 | 17 | Output “Not eligible”| | 4 | 17 | End | 2. **Dry Run: Sum of First 5 Integers (Loop)** ```pseudocode SET sum = 0 SET i = 1 WHILE i <= 5 DO SET sum = sum + i SET i = i + 1 ENDWHILE OUTPUT sum ``` | Step | i | sum | Condition (i<=5) | Action | |------|---|-----|------------------|----------------------------| | 1 | 1 | 0 | True | sum=0+1=1; i=1+1=2 | | 2 | 2 | 1 | True | sum=1+2=3; i=2+1=3 | | 3 | 3 | 3 | True | sum=3+3=6; i=3+1=4 | | 4 | 4 | 6 | True | sum=6+4=10; i=4+1=5 | | 5 | 5 | 10 | True | sum=10+5=15; i=5+1=6 | | 6 | 6 | 15 | False | Exit loop; Output 15 | 3. **Dry Run: Invalid PIN Attempt (with retry limit)** ```pseudocode SET attempts = 0 SET maxAttempts = 3 INPUT pin WHILE pin != 1234 AND attempts < maxAttempts DO SET attempts = attempts + 1 INPUT pin ENDWHILE IF pin = 1234 THEN OUTPUT "Access granted" ELSE OUTPUT "Account locked" ENDIF ``` Test case: pin=1111 (wrong), then 2222, then 1234. | Step | attempts | pin | Condition (pin!=1234 AND attempts<3) | Action | |------|----------|------|--------------------------------------|----------------------------| | 1 | 0 | 1111 | True (1111!=1234 AND 0<3) | attempts=1; input pin=2222 | | 2 | 1 | 2222 | True (2222!=1234 AND 1<3) | attempts=2; input pin=1234 | | 3 | 2 | 1234 | False (1234!=1234 is False) | Exit loop | | 4 | 2 | 1234 | — | pin=1234 → True → Output “Access granted” | ### Vocabulary to Retain - Trace table - Step-by-step execution - Variable tracking - Off-by-one error - Boundary test ### Exam-Style Question with Plan **Question**: Dry run the following algorithm for input values: n = 4. ```pseudocode SET factorial = 1 SET i = 1 WHILE i <= n DO SET factorial = factorial * i SET i = i + 1 ENDWHILE OUTPUT factorial ``` Show the trace table and final output. **Plan**: 1. List variables: `factorial`, `i`, `n` (constant at 4). 2. Initialize: `factorial=1`, `i=1`, `n=4`. 3. Create trace table with columns: Step, i, factorial, Condition (i<=n), Action. 4. Step 1: i=1, factorial=1 → 1<=4 True → factorial=1*1=1; i=1+1=2. 5. Step 2: i=2, factorial=1 → 2<=4 True → factorial=1*2=2; i=2+1=3. 6. Step 3: i=3, factorial=2 → 3<=4 True → factorial=2*3=6; i=3+1=4. 7. Step 4: i=4, factorial=6 → 4<=4 True → factorial=6*4=24; i=4+1=5. 8. Step 5: i=5, factorial=24 → 5<=4 False → Exit loop. 9. Output factorial = 24. 10. Verify: 4! = 24 → correct. --- ## V. Writing Code 1 ### Context Writing Code 1 introduces students to translating algorithms and flowcharts into structured pseudocode or a high-level language (e.g., Python-like syntax). The focus is on correct syntax, use of variables, and basic input/output. This lesson builds directly on selection and loop structures, requiring students to write complete, executable logic for simple problems. In Cameroonian schools, this is often assessed via pen-and-paper coding tasks in exams, where clarity and correctness are prioritized over execution. ### Definitions > Writing code is the process of expressing an algorithm in a formal, unambiguous language that can be interpreted or compiled. > At this level, pseudocode follows conventions: keywords in uppercase (SET, INPUT, OUTPUT, IF, THEN, ELSE, ENDIF, WHILE, DO, ENDWHILE), variables in lowercase, and clear indentation. ### Key Concepts - **Syntax Rules**: - `SET variable = value` for assignment. - `INPUT variable` to read user input. - `OUTPUT "text" or variable` to display. - `IF condition THEN ... ELSE ... ENDIF` for selection. - `WHILE condition DO ... ENDWHILE` for loops. - **Indentation**: Used to show nesting (not strictly enforced in pseudocode but improves readability). - **Data Types**: Implicit; numbers and strings are distinguished by context (quotes for strings). - **No semicolons or braces**: Unlike Python or C, pseudocode uses keywords to delimit blocks. ### Examples (Cameroonian/African Context) 1. **Program to Check if a Number is Even or Odd**: ```pseudocode INPUT number IF number MOD 2 = 0 THEN OUTPUT "Even" ELSE OUTPUT "Odd" ENDIF ``` Used in basic numeracy apps for primary education in rural areas. 2. **Program to Calculate Total Cost of Market Purchase**: ```pseudocode INPUT pricePerItem INPUT quantity SET total = pricePerItem * quantity IF total > 5000 THEN SET discount = total * 0.1 SET total = total - discount OUTPUT "Discount applied. Final price: ", total ELSE OUTPUT "No discount. Total: ", total ENDIF ``` Reflects bulk discount practices in markets like Mokolo (Maroua) or Mfoundi (Yaoundé). 3. **Program to Count Vowels in a Word**: ```pseudocode INPUT word SET count = 0 SET i = 1 WHILE i <= LENGTH(word) DO SET char = EXTRACT(word, i, 1) // Assume EXTRACT function gets character at position i IF char = "a" OR char = "e" OR char = "i" OR char = "o" OR char = "u" THEN SET count = count + 1 ENDIF SET i = i + 1 ENDWHILE OUTPUT "Number of vowels: ", count ``` Supports literacy apps for Anglophone Cameroonian students learning English spelling. ### Vocabulary to Retain - SET - INPUT - OUTPUT - MOD (modulo) - EXTRACT (substring function) ### Exam-Style Question with Plan **Question**: Write pseudocode for a program that asks the user for their age and outputs whether they are a minor (under 18), adult (18–64), or senior (65 or over). Use selection control structure. **Plan**: 1. Start with `INPUT age`. 2. Use `IF-ELSEIF-ELSE` structure: - First condition: `IF age < 18 THEN` → output “Minor”. - Second condition: `ELSEIF age < 65 THEN` → note: since first condition failed, age >=18; so age <65 means 18–64 → output “Adult”. - Final `ELSE` → age >=65 → output “Senior”. 3. Ensure each branch ends with `ENDIF` (or implicit in structure; some pseudocode uses `ENDIF` only at end). 4. Use clear, concise output messages. 5. Test with values: 10 (minor), 25 (adult), 70 (senior), 18 (adult), 64 (adult), 65 (senior). 6. Avoid common mistake: using `IF age <= 18` for minor (would incorrectly include 18 as minor). --- ## VI. Writing Code 2 ### Context Writing Code 2 advances to problems requiring loops, often combined with selection. Students must initialize variables correctly, update loop counters, and accumulate results (e.g., sums, counts). This level emphasizes algorithmic thinking: breaking down a task into repetitive steps and managing state across iterations. It prepares students for more complex applications like data processing or game logic. ### Definitions > Writing Code 2 involves constructing algorithms that use loops to process sequences of data, perform repeated calculations, or handle iterative user input, often with conditional logic inside the loop. > Key skills: proper initialization, loop condition, update, and accumulation. ### Key Concepts - **Accumulator**: A variable that gradually builds a result (e.g., `sum = sum + value`). - **Counter**: A variable that tracks iterations (e.g., `i = i + 1`). - **Sentinel Value**: A special input value that signals the end of data entry (e.g., -1 to stop). - **Loop Body**: The set of statements repeated in each iteration. - **Initialization vs. Update**: Initialization happens once before the loop; update happens at the end of each iteration. ### Examples (Cameroonian/African Context) 1. **Program to Find the Maximum of 10 Numbers**: ```pseudocode SET max = 0 // Assume non-negative numbers; for generality, use first input INPUT firstNumber SET max = firstNumber SET count = 1 WHILE count < 10 DO INPUT nextNumber IF nextNumber > max THEN SET max = nextNumber ENDIF SET count = count + 1 ENDWHILE OUTPUT "Maximum number is: ", max ``` Used in school score analysis tools to find top student in a class. 2. **Program to Calculate Total Sales with Sentinel**: ```pseudocode SET totalSales = 0 INPUT price WHILE price != -1 DO SET totalSales = totalSales + price INPUT price ENDWHILE OUTPUT "Total sales: ", totalSales, " XAF" ``` Reflects informal market tracking where vendors enter prices until done (sentinel -1). 3. **Program to Count How Many Numbers Are Divisible by 3**: ```pseudocode SET count = 0 SET i = 1 WHILE i <= 20 DO INPUT num IF num MOD 3 = 0 THEN SET count = count + 1 ENDIF SET i = i + 1 ENDWHILE OUTPUT "Numbers divisible by 3: ", count ``` Useful in data validation scripts for agricultural surveys (e.g., checking plot IDs). ### Vocabulary to Retain - Accumulator - Counter - Sentinel value - Loop body - Initialization ### Exam-Style Question with Plan **Question**: Write pseudocode for a program that reads 15 integers from the user and outputs how many are positive, how many are negative, and how many are zero. Use a loop. **Plan**: 1. Initialize three counters: `positive = 0`, `negative = 0`, `zero = 0`. 2. Initialize loop counter: `i = 1`. 3. Use `WHILE i <= 15 DO`. 4. Inside loop: - `INPUT num` - `IF num > 0 THEN` → `SET positive = positive + 1` - `ELSEIF num < 0 THEN` → `SET negative = negative + 1` - `ELSE` → `SET zero = zero + 1` 5. Update loop counter: `SET i = i + 1` 6. After loop: - `OUTPUT "Positive: ", positive` - `OUTPUT "Negative: ", negative` - `OUTPUT "Zero: ", zero` 7. Test with sample: [5, -3, 0, 10, -1, 0, 7, -8, 0, 4, -2, 0, 9, -6, 0] → expected: positive=5, negative=4, zero=6. 8. Avoid mistake: forgetting to initialize counters (would start at garbage value). --- ## VII. Writing Code 3 ### Context Writing Code 3 integrates selection, loops, and more complex data handling. Students tackle problems that require nested loops, multiple accumulators, or processing of structured data (e.g., tables, lists). This level mirrors real-world tasks like generating reports, simulating systems, or processing survey results. It prepares students for project-based assessments and higher education computing courses. ### Definitions > Writing Code 3 involves solving multi-step problems that require combining loops, selection, and data manipulation techniques such as nested loops, multiple accumulators, or processing of arrays/lists (conceptually, even if not explicitly named). > Emphasis is on algorithm design, not just syntax translation. ### Key Concepts - **Nested Loops**: A loop inside another loop; used for processing grids (e.g., rows and columns). - **Multiple Accumulators**: Tracking more than one result (e.g., total and average, or counts by category). - **Inner Loop Initialization**: Resetting inner loop variables for each outer iteration. - **Loop Invariants**: A condition that remains true before and after each iteration (useful for reasoning). - **Break Early**: Using conditional exit to stop loops when a condition is met (e.g., finding first match). ### Examples (Cameroonian/African Context) 1. **Program to Generate a Multiplication Table (1–12)**: ```pseudocode SET i = 1 WHILE i <= 12 DO SET j = 1 WHILE j <= 12 DO SET product = i * j OUTPUT i, " x ", j, " = ", product SET j = j + 1 ENDWHILE OUTPUT "---" // Separator between rows SET i = i + 1 ENDWHILE ``` Used in e-learning apps for primary math education in Cameroonian schools. 2. **Program to Count Pass/Fail in a Class of 30 Students (with threshold 50)**: ```pseudocode SET passCount = 0 SET failCount = 0 SET i = 1 WHILE i <= 30 DO INPUT score IF score >= 50 THEN SET passCount = passCount + 1 ELSE SET failCount = failCount + 1 ENDIF SET i = i + 1 ENDWHILE OUTPUT "Pass: ", passCount OUTPUT "Fail: ", failCount ``` Reflects continuous assessment processing in schools like Saker Baptist College or Cameroon Protestant College. 3. **Program to Find the First Number Divisible by Both 5 and 7 in a List of 20**: ```pseudocode SET i = 1 SET found = FALSE WHILE i <= 20 AND NOT found DO INPUT num IF num MOD 5 = 0 AND num MOD 7 = 0 THEN SET found = TRUE OUTPUT "First number divisible by 5 and 7: ", num ENDIF SET i = i + 1 ENDWHILE IF NOT found THEN OUTPUT "No such number found" ENDIF ``` Use in scheduling algorithms (e.g., finding common maintenance cycles for equipment). ### Vocabulary to Retain - Nested loops - Multiple accumulators - Loop invariant - Break early (via flag or condition) - Flag variable ### Exam-Style Question with Plan **Question**: Write pseudocode for a program that simulates a simple quiz. It asks 5 true/false questions (correct answers: T, F, T, T, F). For each question, it inputs the user’s answer (T or F), checks if correct, and keeps a score. After all questions, it outputs the score and a comment: “Excellent” (5), “Good” (3–4), “Needs improvement” (0–2). **Plan**: 1. Initialize: `score = 0`, `question = 1`. 2. Use `WHILE question <= 5 DO`. 3. Inside loop: - `INPUT answer` (expect T or F) - Use nested `IF` to check correctness based on question number: - `IF question = 1 THEN` → correct if `answer = "T"` - `ELSEIF question = 2 THEN` → correct if `answer = "F"` - `ELSEIF question = 3 THEN` → correct if `answer = "T"` - `ELSEIF question = 4 THEN` → correct if `answer = "T"` - `ELSEIF question = 5 THEN` → correct if `answer = "F"` - If correct: `SET score = score + 1` - Update: `SET question = question + 1` 4. After loop: - `OUTPUT "Score: ", score` - `IF score = 5 THEN` → `OUTPUT "Excellent"` - `ELSEIF score >= 3 THEN` → `OUTPUT "Good"` - `ELSE` → `OUTPUT "Needs improvement"` 5. Test case: all correct → score=5 → Excellent. 6. Alternative: use arrays for answers (conceptually), but since arrays not taught, hardcode per question is acceptable at this level. 7. Note: Input validation (ensuring T/F) is optional unless specified; assume valid input. ---

Quiz du chapitre

12 questions — vérifie chaque réponse pour voir l'explication.

  1. 1. Which of the following best describes the time complexity of a binary search algorithm on a sorted array of size n?
  2. 2. In pseudocode, what is the primary purpose of the 'WHILE' loop construct?
  3. 3. Which data structure follows the LIFO (Last In, First Out) principle?
  4. 4. What does the term 'algorithm' refer to in computer science?
  5. 5. A student writes a program to calculate the factorial of a number using recursion. Which of the following is the correct base case for the recursive function factorial(n)?
  6. 6. Consider the following pseudocode: SET total TO 0; FOR i FROM 1 TO 10 DO; SET total TO total + i; END FOR; DISPLAY total. What value is displayed?
  7. 7. Which of the following statements about arrays is TRUE?
  8. 8. A program uses a nested loop where the outer loop runs n times and the inner loop runs n times for each iteration of the outer loop. What is the time complexity?
  9. 9. In the context of algorithm design, what does 'divide and conquer' strategy primarily involve?
  10. 10. What is the output of the following pseudocode? SET x TO 5; SET y TO 3; IF x > y THEN; SET z TO x - y; ELSE; SET z TO y - x; END IF; DISPLAY z;
  11. 11. Which sorting algorithm has a best-case time complexity of O(n) and a worst-case of O(n^2), and is adaptive to already sorted data?
  12. 12. A recursive function to compute the nth Fibonacci number is defined as: fib(0)=0, fib(1)=1, fib(n)=fib(n-1)+fib(n-2) for n>1. What is the primary inefficiency of this naive recursive approach?