90 דק׳

תרגול: משתנים וחשבון

התרגילים של טום ליחידה: בחירת טיפוסים ושמות, מעקב, סדר פעולות, חילוק שלמים ושארית, תוכניות החישוב מהשיעורים, משימת קבלת הסוללה, ושאלות 1-30 מהחוברת.

באנגלית בלבד

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

Two question sets, each with Tom's own numbers so you can find a question in class:

For every program: use int main(void), give every variable a value before you use it, match each % conversion to the variable's type, and test with the example plus one input of your own. In Visual Studio, keep #define _CRT_SECURE_NO_WARNINGS on line 1 of every program that uses scanf. All input follows the stated rules: you do not need if or loops.

Predict, write and run your own answer before you open one.

Lesson exercises: types and names

Checkpoint: choose, declare and justify

Write a declaration for each value, and one reason the type fits.

  1. A temperature that may be -3.75 °C
  2. A command letter such as R
  3. A timer count that an unsigned hardware register requires
  4. A history of four samples
  5. A device name of one word
  6. A value that must stay exactly 1023
Answer

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

    Exercise 1: approve or reject each name

    For each name, write VALID or INVALID. Then improve every valid name that is not clear.

    voltage · board_id · 2nd_value · total current · return · Voltage · sensor2 · _temp

    Answer

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

      Lesson exercises: tracing

      Exercise 2: complete the trace without running

      Copy the table and fill in a, b and temp after each line. Then predict the exact output.

      int a = 4;
      int b = 7;
      int temp;
      temp = a;
      a = b;
      b = temp;
      a = a + b;
      printf("a=%d, b=%d\n", a, b);
      Afterabtemp
      initialization
      temp = a
      a = b
      b = temp
      a = a + b
      Answer

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

        Lesson exercises: arithmetic

        Exercise 3: calculate exactly as C will

        All values are int. For each line, circle the operation that runs first, then write the final value.

        a = 2 + 3 * 4
        b = (2 + 3) * 4
        c = 20 / 5 * 2
        d = 20 / (5 * 2)
        e = 17 % 5 + 1
        f = 3 + 12 % 5 * 2
        Answer

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

          Exercise 4: trace the power program

          Trace the program from the lesson Arithmetic in C with the input 12.5 1.2. Use ? only before a value is assigned; never invent a value.

          double voltage, current, power;
          printf("Enter voltage and current: ");
          scanf("%lf %lf", &voltage, &current);
          power = voltage * current;
          printf("Power: %.2f W\n", power);
          Answer

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

            Exercise 5: total three series resistors

            A technician connects three resistors in series and needs the total resistance. Read r1, r2 and r3 as int ohms (each one zero or more) and print Total: <value> ohm.

            Example: 220 330 470 → Total: 1020 ohm

            Answer

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

              Exercise 6: average three sensor readings

              A sensor is read three times. Read the three readings as double and print the average with two decimals: Average: <value>.

              Example: 4.8 5.0 5.2 → Average: 5.00

              Answer

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

                Debugging incident: right formula, wrong result

                This program builds, but it does not work. Answer the four questions, repair it, predict the output for the input 7 2, then test it.

                int samples;
                int total;
                double average;
                printf("Enter total and sample count: ");
                scanf("%d %d", total, &samples);
                average = total / samples;
                printf("Average: %d\n", average);
                1. Which scanf destination is missing &?
                2. Why can the division lose the fraction?
                3. Which printf conversion does not match its value?
                4. Which input must be forbidden later?
                Answer

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

                  Exercise 7: panel perimeter and area

                  A rectangular control panel is cut from sheet material. Read the width and the height in centimeters as double (both positive). Print the perimeter and the area with two decimals.

                  Example: 12.5 8.0 → Perimeter: 41.00 cm, Area: 100.00 cm^2

                  Answer

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

                    Exercise 8: current with Ohm's law

                    A bench supply puts a voltage across a known resistance. Read the voltage and the resistance as double (resistance greater than zero) and print the current with three decimals.

                    Example: 12.0 240.0 → Current: 0.050 A

                    Answer

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

                      Exercise 9: electrical power

                      A load draws a measured current from a supply. Read the voltage and the current as double and print the power.

                      Example: 5.0 0.35 → Power: 1.75 W

                      Answer

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

                        Exercise 10: Celsius to Fahrenheit

                        A temperature probe reports Celsius, but the display needs Fahrenheit. Read celsius as double and use F = C × 9 / 5 + 32 with floating-point constants.

                        Example: 25.0 → Fahrenheit: 77.00

                        Answer

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

                          Exercise 11: a 10-bit ADC code to voltage

                          A 10-bit ADC turns 0 to 5.00 V into codes 0 to 1023. Read adc_code as int (0 to 1023) and print the voltage with three decimals. Use 5.0 and 1023.0.

                          Example: 512 → Voltage: 2.502 V

                          Answer

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

                            Exercise 12: split elapsed seconds

                            A device reports its run time in seconds. Read total_seconds as int (zero or more) and print the full minutes and the seconds left. Use both / and %.

                            Example: 137 → Minutes: 2, Seconds: 17

                            Answer

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

                              Exercise 13: swap two stored readings

                              Two sensor readings were stored under the wrong channel names. Read channel_a and channel_b as double, print them, exchange their values using one extra variable, and print them again.

                              Example: 1.25 4.75 → After: A=4.75 B=1.25

                              Answer

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

                                Team mission: the battery test receipt

                                Teams of three: driver, formula auditor, test lead. The test station keeps the operator's measurements and calculates two values.

                                • Read the pack ID as int, the voltage and the current as double, and the duration in seconds as int.
                                • Calculate the power in watts and the energy in watt-hours: power = voltage * current; and energy = power * duration_seconds / 3600.0;
                                • Print a labelled receipt:
                                --- BATTERY TEST ---
                                Pack: 73
                                Voltage: 12.50 V
                                Current: 1.20 A
                                Duration: 90 s
                                Power: 15.00 W
                                Energy: 0.38 Wh

                                The mission is done when: every input has a prompt, the types match the data, the formulas use the stored values, voltage, current, power and energy show two decimals, all labels and units appear, and the program builds and passes these tests:

                                PackVoltageCurrentSecondsExpected
                                7312.51.29015.00 W, 0.38 Wh
                                15.00.2536001.25 W, 1.25 Wh
                                00.02.0300.00 W, 0.00 Wh

                                Stretch: line the values up in columns with a field width, for example %8.2f.

                                Answer

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

                                  Exit check: trace, calculate and explain

                                  On paper: predict the exact output, explain the cast, explain the remainder, and name each variable's type.

                                  int total = 17;
                                  int groups = 5;
                                  double average;
                                  average = (double)total / groups;
                                  printf("%.2f %d\n", average, total % groups);
                                  Answer

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

                                    Workbook part A: direct calculations

                                    1. Sum, difference and product

                                    Read two integers and print their sum, difference and product, each with a label.

                                    Example: 8 3 → Sum: 11, Difference: 5, Product: 24

                                    Answer

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

                                      2. Four-number average

                                      Read four double values and print their average with two decimals: average = (a + b + c + d) / 4.0.

                                      Example: 10.0 15.0 12.0 13.0 → Average: 12.50

                                      Answer

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

                                        3. Rectangle calculations

                                        Read the width and the height of a rectangle as double. Print the perimeter and the area with two decimals: perimeter = 2.0 * (width + height), area = width * height.

                                        Answer

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

                                          4. Triangle area

                                          Read the base and the height of a triangle as double and print the area with two decimals: area = base * height / 2.0.

                                          Answer

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

                                            5. Circle measurements

                                            Read the radius of a circle as double. Print the diameter, the circumference and the area. Use const double PI = 3.14159265;.

                                            Answer

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

                                              6. Celsius to Fahrenheit

                                              Read a Celsius temperature as double and print it in Fahrenheit with two decimals: fahrenheit = celsius * 9.0 / 5.0 + 32.0.

                                              Answer

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

                                                7. Kilometers to miles

                                                Read a distance in kilometers as double. Print the original and the converted distance with two decimals: miles = kilometers * 0.621371.

                                                Answer

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

                                                  8. Price after discount

                                                  Read a price and a discount percentage as double. Store and print the discount amount and the final price: discount = price * percentage / 100.0.

                                                  Answer

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

                                                    9. Price including tax

                                                    Read a price before tax and a tax percentage as double. Calculate the tax first, then the final price: tax = price * percentage / 100.0, final price = price + tax.

                                                    Answer

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

                                                      10. Simple interest

                                                      Read a principal amount, a yearly interest rate and a number of years as double. Print the interest and the final amount: interest = principal * rate * years / 100.0.

                                                      Answer

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

                                                        Workbook part B: integer division and remainder

                                                        11. Seconds to minutes

                                                        Read a number of seconds as int (zero or more). Print the full minutes and the seconds left, using / and %.

                                                        Example: 367 → Minutes: 6, Seconds: 7

                                                        Answer

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

                                                          12. Seconds to hours, minutes and seconds

                                                          Read a total number of seconds as int and split it into full hours, minutes left and seconds left. Use / and %.

                                                          Example: 7384 → Hours: 2, Minutes: 3, Seconds: 4

                                                          Answer

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

                                                            13. Quotient and remainder

                                                            Read a positive integer and a positive divisor as int. Print the integer quotient and the remainder.

                                                            Example: 29 6 → Quotient: 4, Remainder: 5

                                                            Answer

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

                                                              14. Extract the digits

                                                              Read a three-digit integer (100 to 999). Print its hundreds, tens and units digits, each with a label. Use / and %.

                                                              Example: 572 → Hundreds: 5, Tens: 7, Units: 2

                                                              Answer

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

                                                                15. Sum of three digits

                                                                Read a three-digit integer, take out its digits, and print their sum.

                                                                Example: 572 → Digit sum: 14

                                                                Answer

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

                                                                  16. Reverse a three-digit number

                                                                  Read a three-digit integer and build the reversed number. Take out each digit before you rebuild the number.

                                                                  Example: 572 → Reversed: 275

                                                                  Answer

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

                                                                    17. Money into coins

                                                                    Read a number of cents as int (zero or more). Use as many 100-cent coins as possible, then 50-cent, then 10-cent, then 1-cent coins. Print the count of each coin.

                                                                    Example: 287 → 2, 1, 3 and 7 coins

                                                                    Answer

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

                                                                      18. Days into weeks

                                                                      Read a number of days as int (zero or more) and split it into full weeks and days left.

                                                                      Example: 45 → Weeks: 6, Days: 3

                                                                      Answer

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

                                                                        Workbook part C: problems with several steps

                                                                        19. Weighted grade

                                                                        Read three grades and their three weights as double, in the order grade1 weight1 grade2 weight2 grade3 weight3. The weights are fractions that add up to 1.0. Print the weighted grade with two decimals.

                                                                        Example: 80 0.20 90 0.30 70 0.50 → 78.00

                                                                        Answer

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

                                                                          20. Required final-test grade

                                                                          A course grade is 40% coursework and 60% final test: desired = coursework * 0.40 + final * 0.60. Read the coursework grade and the desired course grade, and print the final-test grade the student needs.

                                                                          Answer

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

                                                                            21. Average speed

                                                                            Read a distance in kilometers and a travel time in hours as double (time greater than zero). Print the average speed with two decimals.

                                                                            Answer

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

                                                                              22. Fuel consumption

                                                                              Read the distance traveled and the fuel used as double (both greater than zero). Print kilometers per liter and liters per 100 kilometers.

                                                                              Answer

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

                                                                                23. Recipe scaling

                                                                                Read the original servings, the required servings and the original flour amount as double. Print the flour needed: required flour = original flour * required servings / original servings.

                                                                                Answer

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

                                                                                  24. Split a bill

                                                                                  Read a bill amount and a tip percentage as double, and the number of people as int (greater than zero). Print the tip, the total and the amount per person.

                                                                                  Answer

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

                                                                                    25. Difference between two times

                                                                                    Read two times as int, each one in minutes from the start of the day. The second time is later. Print the difference in hours and minutes: difference = second time - first time.

                                                                                    Answer

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

                                                                                      26. Percentage change

                                                                                      Read an original value and a new value as double (the original is not zero). Print the change and the percentage change.

                                                                                      Answer

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

                                                                                        Workbook part D: predict and trace

                                                                                        27. Predict integer division

                                                                                        Predict the exact output, and explain why it is not 2.33.

                                                                                        int a = 7;
                                                                                        int b = 3;
                                                                                        double result;
                                                                                        result = a / b;
                                                                                        printf("%.2f\n", result);
                                                                                        Answer

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

                                                                                          28. Predict division after a cast

                                                                                          Predict the exact output, and explain what the cast changes.

                                                                                          int a = 7;
                                                                                          int b = 3;
                                                                                          double result;
                                                                                          result = (double)a / b;
                                                                                          printf("%.2f\n", result);
                                                                                          Answer

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

                                                                                            29. Complete the trace

                                                                                            Write x, y and z after every assignment. Use ? while z has no value.

                                                                                            int x = 5;
                                                                                            int y = 2;
                                                                                            int z;
                                                                                            z = x + y;
                                                                                            x = z * 2;
                                                                                            y = x - z;
                                                                                            z = x + y;
                                                                                            Answer

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

                                                                                              30. Evaluate exactly as C does

                                                                                              Find the value of each expression. Apply parentheses and C's order of operations. d is a double; the others are int.

                                                                                              a = 5 + 4 * 3;
                                                                                              b = (5 + 4) * 3;
                                                                                              c = 25 / 4;
                                                                                              d = 25 / 4.0;
                                                                                              e = 25 % 4;
                                                                                              f = 18 / 3 * 2;
                                                                                              g = 18 / (3 * 2);
                                                                                              h = 2 + 17 % 5 * 3;
                                                                                              Answer

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