90 דק׳

תרגול: החלטות מתקדמות ותכנון בדיקות

14 האתגרים ו־32 בעיות התכנות של יחידה 5: מעקב, נפילה ב־switch, אופרטור התנאי, בדיקות גבול, טבלאות החלטה ותוכניות שלמות. כל תשובה מוסתרת עד שפותחים אותה.

באנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

How to use this page

Two sets of questions. The challenges (1-14) ask you to trace, prove and repair: a correct output for one ordinary input is not enough; full credit needs a trace, a counterexample, a boundary test or a design explanation. The coding problems (01-32) ask for complete programs in the style of an online judge: read from the input, print only the required output, no prompts such as "Enter a number".

None of them needs loops, arrays, strings or your own functions. The difficulty is in exact specifications, priority, boundaries and testing. Try each one before you open the answer.

A good workflow for every problem:

  1. Rewrite the rules as cases that do not overlap.
  2. Mark invalid input and the rules that override others.
  3. Write the smallest clear decision structure.
  4. Run the examples given.
  5. Add your own boundary tests: below, at and above every boundary.

In Visual Studio: one project per problem (or replace main.c between problems), and keep #define _CRT_SECURE_NO_WARNINGS as the first line so scanf compiles.

Challenges A: trace before you touch the code

Challenge 1: The safety state that gets overwritten

int state = 0;
int battery = 10;
int temperature = 20;
 
if (battery < 15)
    state = 3;
if (temperature >= 80)
    state = 3;
else if (temperature >= 60)
    state = 2;
else
    state = 1;
 
printf("%d\n", state);

a. State the exact output. b. Trace every assignment to state in the order it happens. c. Write the smallest change to the structure that stops a critical-battery state from being overwritten. d. Give one input pair that proves the repaired program keeps the intended priority.

Answer

נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

    Challenge 2: Two indentations, one parser

    if (enabled)
        if (temperature >= 80)
            printf("SHUTDOWN\n");
    else
        printf("RUN\n");

    a. For enabled = 0 and temperature = 20, what prints? b. Add braces that keep the program's actual behaviour. c. Write a second braced version in which RUN belongs to the outer if. d. Explain why indentation alone cannot settle the question.

    Answer

    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

      Challenge 3: Fall-through map

      switch (code) {
          case 1: printf("A");
          case 2: printf("B");
          case 3: printf("C"); break;
          case 4:
          case 5: printf("D"); break;
          default: printf("X");
      }

      a. Complete the table for codes 1, 2, 3, 4, 5 and 9: exact output, the first label executed, and why the switch is left. b. Which fall-through is clearly intentional? c. Insert the minimum number of break statements so that codes 1, 2 and 3 print only their own letter, while codes 4 and 5 still share D.

      Answer

      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

        Challenge 4: The branch that must not run

        int divisor = 0;
        int sensor_ok = 0;
        int value = sensor_ok ? (100 / divisor) : -1;
         
        printf("%d\n", value);

        a. Predict the output. b. Explain why no division by zero happens in this run. c. Change only one initializer so that the program has undefined behaviour. Which operation causes it? d. Rewrite the assignment with if ... else with exactly the same behaviour.

        Answer

        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

          Challenge 5: Choose a structure and defend it

          SpecificationYour choiceWhy
          a char command is R, S or X
          temperature is below 60, 60-79, or 80 and above
          choose the larger of two ints
          check the battery only when a device is enabled
          the mode selects a limit, then the temperature selects a state

          a. Complete the table with switch, if / else if, nested if, ?:, or a combination you can justify. b. For one row, name a second structure that would also work but would show the specification less clearly.

          Answer

          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

            Challenges B: prove or repair the decision

            Challenge 6: A legal branch that can never run

            if (temperature >= 60)
                printf("WARN\n");
            else if (temperature >= 80)
                printf("SHUTDOWN\n");
            else
                printf("RUN\n");

            a. Which branch can never run? Prove it with logic, not with one test. b. Give one input that shows the safety defect. c. Repair the branch order. d. List the three boundary tests around 60 and the three around 80, with the expected outputs.

            Answer

            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

              Challenge 7: A minimal test set is not a random test set

              A controller implements: below 0 INVALID; 0-39 LOW; 40-69 NORMAL; 70-89 HIGH; 90-100 CRITICAL; above 100 INVALID.

              a. Choose eight values that give strong evidence about every internal boundary and both invalid regions. (You cannot test every below / at / above value with eight.) b. Explain what fault each chosen value could reveal. c. Name one plausible wrong program that your set would miss, and add a ninth test for it.

              Answer

              נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                Challenge 8: Audit a decision table

                RowBatteryTemperatureResult
                1below 15anySHUTDOWN
                215 or moreabove 80SHUTDOWN
                315 or more60-80WARN
                415 or morebelow 60RUN

                a. The requirement says "80 °C or higher is SHUTDOWN". Find the defect. b. Is the table overlapping, incomplete, or both? Justify precisely. c. Repair only the cells that must change. d. Give two tests that tell the original table and the repaired table apart.

                Answer

                נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                  Challenge 9: Diagnose from a black-box log

                  The hidden program should map N to limit 80, T to 70 and S to 60. At or above the limit it prints SHUTDOWN, within 10 °C below it prints WARN, otherwise RUN. An invalid mode prints INVALID.

                  TestInputExpectedObserved
                  B1N, 79WARNWARN
                  B2N, 80SHUTDOWNWARN
                  B3N, 81SHUTDOWNSHUTDOWN
                  B4T, 69WARNWARN
                  B5X, 20INVALIDRUN

                  a. State one likely defect that explains B2 and B3 together. b. State one independent likely defect that explains B5. c. Choose one confirming test for each guess, with its expected result. d. Explain why the log does not prove the exact source code.

                  Answer

                  נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                    Challenges C: implement under constraints

                    Challenge 10: Command decoder with grouped cases

                    Write a complete C17 program that reads one character command. Upper and lower case must both work: R or r prints RESET, S or s prints STATUS, H or h prints HELP, every other character prints INVALID. Use one switch, and group the cases without repeating any output statement.

                    InputExpected output
                    RRESET
                    sSTATUS
                    hHELP
                    ?INVALID

                    a. Submit the program. b. Mark every intentional fall-through with a short comment. c. Explain why scanf(" %c", &command) has a space before %c.

                    Answer

                    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                      Challenge 11: Rewrite without changing behaviour

                      int output;
                      if (a > b)
                          output = a;
                      else
                          output = b;
                       
                      if (output % 2 == 0)
                          printf("EVEN %d\n", output);
                      else
                          printf("ODD %d\n", output);

                      a. Rewrite only the assignment to output with ?:. b. Write a complete program that reads a and b and prints the same result. c. Test ties, negative numbers, and one case where the larger number is odd. d. When a equals b, does the original choose a or b? Show that your rewrite keeps this detail.

                      Answer

                      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                        Challenge 12: Thermal chamber controller

                        Write a complete C17 program. The inputs are the mode (N, T or S), an integer temperature and an integer battery percentage.

                        RuleRequirement
                        Validitymode N, T or S; temperature -40 to 120; battery 0 to 100 (inclusive)
                        LimitsN: 80 °C, T: 70 °C, S: 60 °C
                        Priorityinvalid input → INVALID; battery below 15 → SHUTDOWN
                        Heattemperature >= limit → SHUTDOWN; temperature >= limit - 10 → WARN; otherwise RUN

                        a. Use switch to choose the limit and conditions for validation and ranges. b. Print exactly one result word. c. Run the eight acceptance tests from lesson 3 plus at least four boundary tests of your own. d. Attach a test table with expected and observed output.

                        Answer

                        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                          Challenge 13: Fan supervisor with priority and a hysteresis note

                          A fan controller reads mode (0 OFF, 1 AUTO, 2 MANUAL), an integer temperature and manual_level (0-3). The temperature must be -20 to 100.

                          PriorityResult
                          invalid inputINVALID
                          mode 0FAN 0
                          mode 2FAN manual_level
                          mode 1 and temperature below 40FAN 0
                          mode 1 and temperature 40-59FAN 1
                          mode 1 and temperature 60-79FAN 2
                          mode 1 and temperature 80-100FAN 3

                          a. Write the complete program. b. Decide whether manual_level must be valid when the mode is OFF or AUTO. State and justify your choice before coding. c. Write tests that show your choice. d. In two sentences: why may a real thermostat need hysteresis? (No need to implement it.)

                          Answer

                          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                            Challenge 14: Certification challenge: repair and defend

                            #include <stdio.h>
                             
                            int main(void) {
                                char mode; int temperature; int battery; int limit;
                                scanf("%c%d%d", &mode, &temperature, &battery);
                                switch (mode) {
                                case 'N': limit = 80;
                                case 'T': limit = 70; break;
                                case 'S': limit = 60; break;
                                }
                                if (battery < 0 || battery > 100 && temperature < -40 || temperature > 120)
                                    printf("INVALID\n");
                                else if (temperature > limit) printf("SHUTDOWN\n");
                                else if (temperature > limit - 10) printf("WARN\n");
                                else if (battery < 15) printf("SHUTDOWN\n");
                                else printf("RUN\n");
                                return 0; }

                            a. Find at least six independent defects or risks: control flow, boundaries, validation and input handling. b. For each defect, give a test that can expose it. c. Write a repaired complete program. d. Explain the priority of your repaired decisions in plain English. e. State one reasonable ambiguity in the requirement that must be confirmed with the customer.

                            Answer

                            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                              Coding problems A: precision warm-up

                              Problem 01: Signal polarity

                              Classify one integer x (-1,000,000 to 1,000,000). Zero is its own category. Every other value is classified by sign and by parity. Print exactly ZERO, POSITIVE EVEN, POSITIVE ODD, NEGATIVE EVEN or NEGATIVE ODD.

                              InputExpected output
                              7POSITIVE ODD
                              -12NEGATIVE EVEN
                              0ZERO

                              Test also: zero, negative odd values, and the fact that in C the remainder of a negative odd number is not +1.

                              Answer

                              נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                Problem 02: Distance from an interval

                                Given an inclusive interval [low, high], print the smallest integer distance from x to that interval. The distance is 0 when x is inside. Input: three integers x low high (low ≤ high).

                                InputExpected output
                                3 7 124
                                9 7 120
                                20 7 128

                                Test also: both sides of the interval, both end points, and a one-value interval.

                                Answer

                                נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                  Problem 03: Closest to zero

                                  Print whichever of a and b is closer to zero. If both are equally close, print the larger value. Use at least one ?: in your solution.

                                  InputExpected output
                                  -8 55
                                  -6 66
                                  4 44

                                  Test also: opposite values, equal inputs, zero, and two negative inputs.

                                  Answer

                                  נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                    Problem 04: Median of three

                                    Print the median of three integers: the value that would be in the middle if they were sorted. Repeated values are allowed.

                                    InputExpected output
                                    9 2 55
                                    4 4 104
                                    7 1 77

                                    Test also: all six orders of three different values, duplicates, all equal.

                                    Answer

                                    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                      Problem 05: Second distinct maximum

                                      Print the second-largest distinct value among three integers. If there is none, print NONE.

                                      InputExpected output
                                      8 3 55
                                      8 8 33
                                      4 4 4NONE

                                      Test also: the maximum twice, the smaller value twice, negatives, all equal.

                                      Answer

                                      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                        Problem 06: Three-way temperature trend

                                        Three readings in a row. Print RISING if each is strictly greater than the one before, FALLING if each is strictly smaller, FLAT if all three are equal, and MIXED otherwise.

                                        InputExpected output
                                        2 5 9RISING
                                        7 7 7FLAT
                                        3 3 4MIXED

                                        Test also: a plateau at either step, and a change of direction.

                                        Answer

                                        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                          Problem 07: Three-digit mirror

                                          A mirror number reads the same from both ends. Decide whether a three-digit number is one. Print YES, NO, or INVALID if n is not between 100 and 999.

                                          InputExpected output
                                          737YES
                                          740NO
                                          99INVALID

                                          Test also: 100, 101, 999 and values outside the range.

                                          Answer

                                          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                            Problem 08: Exact change decision

                                            A vending controller has only 5-unit and 2-unit coins: at most two 5s and at most five 2s. For a target from 0 to 20, print a pair five_coins two_coins that makes the target exactly, preferring more 5s. If no pair exists, print IMPOSSIBLE. A target outside 0-20 prints INVALID.

                                            InputExpected output
                                            142 2
                                            91 2
                                            1IMPOSSIBLE

                                            Test also: 0, 1, odd targets, and targets that need fewer 5s than possible.

                                            Answer

                                            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                              Coding problems B: boundaries and state

                                              Problem 09: Triangle by sides

                                              Classify three side lengths. A valid triangle has positive sides, and the sum of any two sides is greater than the third. Print INVALID, EQUILATERAL, ISOSCELES or SCALENE.

                                              InputExpected output
                                              5 5 5EQUILATERAL
                                              2 3 5INVALID
                                              5 7 5ISOSCELES

                                              Test also: zero or negative sides, a flat triangle (2 3 5), and the longest side in each position.

                                              Answer

                                              נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                Problem 10: Inclusive interval relationship

                                                Compare the inclusive intervals [a, b] and [c, d] (a ≤ b, c ≤ d). Print IDENTICAL if both end points match, TOUCH if they share exactly one value, OVERLAP if they share more than one value, and DISJOINT otherwise.

                                                InputExpected output
                                                1 5 1 5IDENTICAL
                                                1 5 5 9TOUCH
                                                1 8 3 4OVERLAP

                                                Test also: the intervals in reverse order, one inside the other, one-value intervals, and a shared left end point.

                                                Answer

                                                נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                  Problem 11: Gregorian date validator

                                                  Decide whether day month year is a valid date (year 1900-2100). A leap year is divisible by 400, or divisible by 4 but not by 100. Print VALID or INVALID.

                                                  InputExpected output
                                                  29 2 2000VALID
                                                  29 2 1900INVALID
                                                  31 4 2026INVALID

                                                  Test also: century years, month 0 and 13, day 0, the 30-day months, and the end of February.

                                                  Answer

                                                  נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                    Problem 12: Next minute

                                                    Given a 24-hour time hour minute, print the time one minute later as HH:MM, or INVALID (valid: hour 0-23, minute 0-59).

                                                    InputExpected output
                                                    14 0814:09
                                                    23 5900:00
                                                    7 60INVALID

                                                    Test also: minute 58 and 59, hour 22 and 23, midnight, negative values.

                                                    Answer

                                                    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                      Problem 13: Weekday shift

                                                      Day codes are 1 = MON to 7 = SUN. Move delta days (-6 to 6) from the given day and print the three-letter name, or INVALID.

                                                      InputExpected output
                                                      1 -1SUN
                                                      7 1MON
                                                      3 4SUN

                                                      Test also: both directions of wrap-around, delta 0, and an invalid day or delta.

                                                      Answer

                                                      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                        Problem 14: Hex digit decoder

                                                        Convert one hexadecimal digit (0-9, A-F or a-f) to its value, or print INVALID.

                                                        InputExpected output
                                                        99
                                                        B11
                                                        f15
                                                        GINVALID

                                                        Test also: 0, 9, A, F, a, f, and the letters just after F and f.

                                                        Answer

                                                        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                          Problem 15: Rock paper scissors

                                                          Two players enter R, P or S. Rock beats scissors, scissors beats paper, paper beats rock. Print PLAYER1, PLAYER2, DRAW or INVALID.

                                                          InputExpected output
                                                          R SPLAYER1
                                                          R PPLAYER2
                                                          S SDRAW

                                                          Test also: all nine valid pairs, and an invalid move from either player.

                                                          Answer

                                                          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                            Problem 16: Safe integer calculator

                                                            Read a op b and evaluate it for +, -, *, / and % with C's integer rules. Division or remainder by zero prints ERROR; an unknown operator prints INVALID.

                                                            InputExpected output
                                                            17 / 53
                                                            9 % 0ERROR
                                                            4 ^ 2INVALID

                                                            Test also: negative division, zero with every operator, every operator once.

                                                            Answer

                                                            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                              Coding problems C: competing rules

                                                              Problem 17: Compare two fractions

                                                              Compare a/b and c/d exactly, without converting to double. Denominators are positive. Print FIRST, SECOND or EQUAL.

                                                              InputExpected output
                                                              1 3 2 5SECOND
                                                              -1 2 -3 4FIRST
                                                              2 6 1 3EQUAL

                                                              Test also: negative numerators, equal fractions written differently, values near zero.

                                                              Answer

                                                              נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                Problem 18: Dominant magnitude

                                                                For three integers, print the largest absolute value and how many inputs have it. Use ?: for each absolute value.

                                                                InputExpected output
                                                                -9 4 99 2
                                                                -3 -7 27 1
                                                                0 0 00 3

                                                                Test also: equal magnitudes with opposite signs, all equal, all zero.

                                                                Answer

                                                                נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                  Problem 19: RGB dominant channel

                                                                  Classify an RGB sample (each 0-255). All equal: GRAY. Exactly two channels share the maximum: RG, RB or GB. Otherwise the single largest channel: R, G or B. Out-of-range values: INVALID.

                                                                  InputExpected output
                                                                  80 80 80GRAY
                                                                  200 200 10RG
                                                                  10 90 40G

                                                                  Test also: each pair tie, all equal, each single maximum, invalid channels.

                                                                  Answer

                                                                  נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                    Problem 20: Policy-adjusted grade

                                                                    Input: score late_days integrity_ok (score 0-100, late days 0-5, integrity 0 or 1). Invalid data prints INVALID. A failed integrity check prints DISQUALIFIED. Otherwise subtract 5 points per late day (not below 0) and print the adjusted score and its grade: A 90+, B 80+, C 70+, D 60+, otherwise F.

                                                                    InputExpected output
                                                                    94 1 189 B
                                                                    80 0 0DISQUALIFIED
                                                                    12 5 10 F

                                                                    Test also: every grade boundary after the penalty, the floor at zero, the override order, invalid flags.

                                                                    Answer

                                                                    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                      Problem 21: Parking bill

                                                                      Parking is free for 0-15 minutes. 16-75 minutes cost 500 cents. Each started hour after that costs 300 cents more. The daily maximum is 2000 cents. Minutes outside 0-1440 print INVALID.

                                                                      InputExpected output
                                                                      150
                                                                      76800
                                                                      1361100
                                                                      14402000

                                                                      Test also: 15/16, 75/76, an exact extra hour and a started one, the point where the cap begins.

                                                                      Answer

                                                                      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                        Problem 22: Progressive energy charge

                                                                        Energy is charged in tiers: the first 100 kWh at 50 cents each, the next 200 kWh at 75 cents, everything above that at 120 cents. Plan G gets 10% off the total; plan R does not. Fractions of a cent are dropped. Input kwh plan (kwh 0-1000, plan R or G), otherwise INVALID.

                                                                        InputExpected output
                                                                        100 R5000
                                                                        101 R5075
                                                                        350 G23400

                                                                        Test also: tier boundaries 100/101 and 300/301, zero use, both plans, an invalid plan.

                                                                        Answer

                                                                        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                          Problem 23: Elevator request filter

                                                                          An elevator serves floors -2 to 12 but has no floor 0. In service mode S it may go to any valid floor; in public mode P the basement floors (below 0) are blocked. Input mode current target. Print INVALID, BLOCKED, STAY, UP or DOWN.

                                                                          InputExpected output
                                                                          P 3 -1BLOCKED
                                                                          S 3 -1DOWN
                                                                          P 5 5STAY

                                                                          Test also: floor 0, both basement floors, the same floor, and moving across the missing floor.

                                                                          Answer

                                                                          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                            Problem 24: Access badge decision

                                                                            A door controller reads badge_level (0-3), required_level (1-3), pin_ok, schedule_open and emergency (each 0 or 1). Invalid data: INVALID. Emergency: EMERGENCY_ACCESS. Otherwise a wrong PIN: DENIED. A closed schedule lets in only level 3. An open schedule grants access when the badge level is at least the required level; otherwise DENIED.

                                                                            InputExpected output
                                                                            2 2 1 1 0GRANTED
                                                                            3 2 1 0 0GRANTED
                                                                            3 2 0 0 1EMERGENCY_ACCESS

                                                                            Test also: emergency with a wrong PIN, a closed schedule at levels 2 and 3, badge 0, a badge exactly at the required level.

                                                                            Answer

                                                                            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                              Coding problems D: engineering judge

                                                                              Problem 25: Loan risk gate

                                                                              Input age income debt late_payments (age 18-70, income and debt 0-1,000,000, late payments 0-10), otherwise INVALID. Under 21 or 3+ late payments: DECLINED. PRIME needs income ≥ 12000, debt ≤ 30% of income and no late payments. STANDARD needs income ≥ 7000, debt ≤ 45% of income and at most one late payment. Every other valid case: REVIEW.

                                                                              InputExpected output
                                                                              30 15000 4000 0PRIME
                                                                              24 8000 3600 1STANDARD
                                                                              40 20000 2000 3DECLINED

                                                                              Test also: exactly 30% and 45%, a PRIME case that also meets STANDARD, zero income, the decline priority.

                                                                              Answer

                                                                              נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                Problem 26: Resistor tolerance test

                                                                                A resistor passes when the measured value is within tolerance percent of the nominal value, inclusive. Compare with integers: |measured - nominal| * 100 <= nominal * tolerance. Input nominal measured tolerance (nominal 1-100000, measured 0-200000, tolerance 1-20), otherwise INVALID. Print PASS, LOW or HIGH.

                                                                                InputExpected output
                                                                                1000 950 5PASS
                                                                                1000 949 5LOW
                                                                                1000 1051 5HIGH

                                                                                Test also: both exact tolerance limits and one unit outside each.

                                                                                Answer

                                                                                נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                  Problem 27: ADC window decoder

                                                                                  A 10-bit ADC reading: 0-99 FAULT_LOW, 100-399 LOW, 400-699 NORMAL, 700-899 HIGH, 900-1023 FAULT_HIGH. Values outside 0-1023: INVALID.

                                                                                  InputExpected output
                                                                                  99FAULT_LOW
                                                                                  400NORMAL
                                                                                  1024INVALID

                                                                                  Test also: every value just below, at and above the four internal boundaries.

                                                                                  Answer

                                                                                  נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                    Problem 28: Parcel dispatch

                                                                                    Zones 1, 2 and 3 cost 400, 700 and 1000 cents. Every started kilogram above 2000 g costs 100 cents more. A fragile parcel costs 250 cents more. A fragile zone-3 parcel above 5000 g is rejected. Input zone weight_grams fragile express (zone 1-3, weight 1-20000, fragile 0/1, express is reserved and must be 0), otherwise INVALID. Print the fee in cents, REJECT or INVALID.

                                                                                    InputExpected output
                                                                                    1 2000 0 0400
                                                                                    2 2001 1 01050
                                                                                    3 5001 1 0REJECT

                                                                                    Test also: exactly 2000 g, the started-kilogram boundaries, the rejection priority, every invalid field.

                                                                                    Answer

                                                                                    נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                      Problem 29: Battery charge controller

                                                                                      A charger reads temperature voltage_mv percent connected (temperature -50 to 100 °C, voltage 0-20000 mV, percent 0-100, connected 0 or 1). Follow this exact priority:

                                                                                      1. invalid data: INVALID
                                                                                      2. not connected: IDLE
                                                                                      3. unsafe temperature, below 0 °C or above 45 °C: BLOCKED_TEMP
                                                                                      4. weak supply, below 4500 mV: BLOCKED_SUPPLY
                                                                                      5. full battery, 95% or more: FULL
                                                                                      6. below 20%: FAST
                                                                                      7. otherwise: NORMAL
                                                                                      InputExpected output
                                                                                      25 5000 10 1FAST
                                                                                      50 5000 10 1BLOCKED_TEMP
                                                                                      25 3000 100 0IDLE

                                                                                      Test also: inputs that match several rules at once, especially a disconnected charger with unsafe values that are still valid.

                                                                                      Answer

                                                                                      נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                        Problem 30: Dual-sensor arbitration

                                                                                        Two temperature sensors, each with a health flag: healthy1 value1 healthy2 value2 (flags 0/1, values -100 to 200 even for an unhealthy sensor), otherwise INVALID. Neither healthy: SENSOR_FAULT. Exactly one healthy: DEGRADED and that reading. Both healthy but more than 5 apart: DISAGREE. Otherwise OK and their average with one decimal.

                                                                                        InputExpected output
                                                                                        1 20 1 24OK 22.0
                                                                                        1 20 1 26DISAGREE
                                                                                        0 90 1 18DEGRADED 18

                                                                                        Test also: a difference of exactly 5, the readings in reverse order, both unhealthy, invalid data on an unhealthy sensor.

                                                                                        Answer

                                                                                        נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                          Problem 31: Traffic light transition

                                                                                          The current state is R, G or Y. Event T advances R → G, G → Y, Y → R. Event E (emergency) forces R from any state. Print the next state, or INVALID.

                                                                                          InputExpected output
                                                                                          R TG
                                                                                          G TY
                                                                                          G ER
                                                                                          B TINVALID

                                                                                          Test also: every normal transition, the emergency from every state, an invalid state or event.

                                                                                          Answer

                                                                                          נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                            Problem 32: Robot motion permit

                                                                                            A robot receives mode calibrated obstacle_cm tilt_deg load_kg speed (mode A automatic or M manual; calibrated 0/1; obstacle 0-500; tilt -90 to 90; load 0-50; speed 0-100). Priority: invalid data INVALID; not calibrated CALIBRATE; obstacle closer than 20 cm STOP; tilt beyond 15° either way UNSAFE_TILT; over the mode limits LIMIT (automatic: load ≤ 20 and speed ≤ 60; manual: load ≤ 35 and speed ≤ 80); otherwise MOVE.

                                                                                            InputExpected output
                                                                                            A 1 100 5 10 50MOVE
                                                                                            M 1 10 40 40 90STOP
                                                                                            A 0 5 30 50 100CALIBRATE

                                                                                            Test also: inputs that match several rules, the exact boundaries 20 / 15 / 60 / 80 / 20 / 35, both modes.

                                                                                            Answer

                                                                                            נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

                                                                                              Before you hand in

                                                                                              • Every trace gives the exact output.
                                                                                              • Every repair comes with a test that failed before it.
                                                                                              • Complete programs use int main(void) and return 0;.
                                                                                              • Every variable has a value before it is used.
                                                                                              • Every switch handles unexpected input (default).
                                                                                              • Boundary tests cover below, at and above where it matters.
                                                                                              • Expected and observed output are written separately.
                                                                                              • Design explanations refer to the specification.