العودة إلى الدراسة

المحاضرة 2 من 10

35 دقيقة تقريبًا

Count the Work Before Writing Big O

Trace small pieces of code, then count fixed work, loops, halving, consecutive parts, and alternative branches.

تصفّح الدفتر
Step 1 of 7 · Follow the example

Fixed work: read a value or find an average

Goal: Recognize work whose size stays fixed.

First, consider reading one number and printing it. In C++, cin reads input and cout writes output:

الكود أو الخطوات
cin >> X;
cout << X;

For a fixed-size value, this is a fixed amount of work: O(1)O(1). The 1 means the work does not grow with input size. It does not mean there is only one instruction.

Now find the average of three numbers. Add A, B, and C, store the result in Sum, then divide by 3. Try 3, 6, and 9: the sum is 18 and the average is 6.

The number of inputs is always three, so this calculation also takes O(1)O(1) work under the fixed-size arithmetic assumption.

The steps and what assignment means
الكود أو الخطوات
cin >> A >> B >> C
Sum = A + B + C
Avg = Sum / 3

A variable is a named place to store a value. The assignment Sum = A + B + C calculates the right-hand side, then stores the result in Sum on the left.

In C++, integer division discards the fractional part. Use double values or divide by 3.0 when a fractional average is needed.

If reading takes a fixed cost c1c_1 and printing takes a fixed cost c2c_2, their total c1+c2c_1+c_2 is also fixed. The two costs do not have to be equal.

Remember: O(1) means constant growth, not one operation.

موضعك محفوظ تلقائيًا
خطوة صغيرة. فهم أعمق.ألجولاب · دفتر شخصي للدراسة