Engineering Algorithms in C: Reliable Calculations

Engineering Algorithms in C involves turning a specified calculation into statements that preserve its meaning. Even when your equation is correct, a program can produce the wrong result through integer division, an incorrect array boundary, or an overwritten value. Your task is to make the types, storage, and execution order match the supplied calculation. The examples here use C11 and assume all values and intermediate results fit within their numeric types.

Match numeric types to the calculation

Use integer types for discrete counts and floating-point types for quantities that can have fractional values. C does not track physical units, so names such as force_N and duration_s help you keep quantities consistent.


C type

Typical engineering use

Important consideration

int

Small signed counts or status values

Division between integers discards the fractional part

size_t

Array lengths and indices

It is unsigned and is declared by the standard header stddef.h

double

Forces, temperatures, and calculated ratios

Many decimal values are represented approximately


A type conversion changes the type used to represent a value. An explicit conversion, called a cast, applies to the expression immediately following it.


C
int completed = 3;
int total = 8;
double fraction = (double)completed / total;


Here, converting completed before division makes the division floating-point, giving 0.375. Without the cast, completed / total produces integer zero, which is then stored as 0.0. Writing (double)(completed / total) also converts too late: the fractional information has already been discarded.



Implement accumulation with valid bounds

Consider a supplied calculation for the mean of nn force readings:


F‾=1n∑i=0n−1Fi,n>0.\overline{F}=\frac{1}{n}\sum_{i=0}^{n-1}F_i,\qquad n>0.


An accumulator is a variable that stores a running total. Initialize a sum to zero before adding any readings. For an array containing nn elements, the valid indices run from zero through n−1n-1.


C
#include "stddef.h"

double mean_force_N(const double force_N[], size_t n)
{
    double sum_N = 0.0;
    for (size_t i = 0; i < n; ++i) {
        sum_N += force_N[i];
    }
    return sum_N / (double)n;
}


Before calling this function, the caller must ensure that n is positive and that the array contains at least n readable, finite values. Reject an empty dataset before calling it. The function's const parameter prevents it from changing the readings through that parameter.


The loop initializes i to zero, tests i < n before each iteration, and increases i after processing a reading. Thus, each specified element contributes once. Changing the condition to i <= n would attempt to read an element beyond the array. Starting at one would omit the first reading.


The cast on n makes the intended floating-point division explicit. It is optional here because sum_N already has type double.

Preserve updates and verify behavior

An assignment stores a new value immediately. In a recurrence such as estimate = estimate + correction, the right-hand side uses the current estimate before replacing it. If two supplied equations both require the previous state, save the necessary old values before either update overwrites them.


Implement stated boundaries literally. A requirement of “at least the limit” corresponds to >=; “greater than the limit” corresponds to >. Test a value exactly at the limit to distinguish these cases.


Check a function against small cases whose answers you can calculate independently. The force readings 10.0, 14.0, and 18.0 N have a mean of 14.0 N. A single reading should return that reading, while a constant dataset should return its common value. These checks target different implementation errors; successful compilation alone does not establish correctness.



Enable compiler warnings and investigate their messages. Keep full working precision during the calculation, then choose the displayed precision when reporting the result. Formatting a number to two decimal places changes its presentation, not the accuracy of the underlying measurements.


What to remember

  • Choose types before translating arithmetic expressions.
  • Initialize accumulators and use valid array indices.
  • Preserve old values when updates require the previous state.
  • Verify units, boundary cases, and independently calculated results.

Example: Implementing a Heater Energy Calculation

An electrical heater operates at 180 W, 240 W, 210 W, and 270 W during four consecutive intervals. Each value is constant throughout its complete interval of 0.40 s0.40\ \text{s}. Use C11 to implement the supplied calculation


E=∑i=0n−1PiΔt.E=\sum_{i=0}^{n-1}P_i\Delta t.


Assume the array contains at least nn readable, finite power values, n>0n>0, and Δt>0\Delta t>0. All intermediate results fit within double. Include the standard header stddef.h to declare size_t.


a) Write a function heater_energy_J that accepts the power array, its length, and the common interval duration. Return the total energy in joules.


Use double for power, duration, and energy because the calculation can contain fractional values. Initialize the energy accumulator once, before the loop. The loop must visit indices ________ through n - 1.


Define the function as follows:


double heater_energy_J(const double power_W[], size_t n, double dt_s) { double energy_J = 0.0; for (size_t i = 0; i < n; ++i) { energy_J += power_W[i] * dt_s; } return energy_J; }


The declaration double energy_J = 0.0; initializes the running total. Each iteration executes energy_J += power_W[i] * dt_s;, adding the energy from one interval. After the loop, return energy_J; supplies the total to the caller.


Each contribution has units W⋅s=J\text{W}\cdot\text{s}=\text{J}. For example, the first iteration adds


180 W×0.40 s=72.0 J.180\ \text{W}\times0.40\ \text{s}=72.0\ \text{J}.


The function preserves the input readings and returns the accumulated energy. Its caller is responsible for satisfying the stated input assumptions.


b) Show the caller's declarations and function call. Calculate the total energy and the average power over the complete operating period.


Store the four readings in an array. In the scope where the array is declared, dividing its total storage size by one element's storage size gives its element count. Place these statements inside the calling function, with the definition of heater_energy_J available before the call:

  • const double power_W[] = {180.0, 240.0, 210.0, 270.0};
  • const size_t n = sizeof power_W / sizeof power_W[0];
  • const double dt_s = 0.40;
  • double energy_J = heater_energy_J(power_W, n, dt_s);
  • double mean_power_W = energy_J / ((double)n * dt_s);

The accumulator changes as follows:

  • Index 0: 180(0.40)=72.0 J180(0.40)=72.0\ \text{J} is added, giving 72.0 J72.0\ \text{J}.
  • Index 1: 240(0.40)=96.0 J240(0.40)=96.0\ \text{J} is added, giving 168.0 J168.0\ \text{J}.
  • Index 2: 210(0.40)=84.0 J210(0.40)=84.0\ \text{J} is added, giving 252.0 J252.0\ \text{J}.
  • Index 3: 270(0.40)=108.0 J270(0.40)=108.0\ \text{J} is added, giving 360.0 J360.0\ \text{J}.

The complete duration is


t=nΔt=4(0.40 s)=1.60 s.t=n\Delta t=4(0.40\ \text{s})=1.60\ \text{s}.


Therefore,


P‾=Et=360.0 J1.60 s=225.0 W.\overline{P}=\frac{E}{t}=\frac{360.0\ \text{J}}{1.60\ \text{s}}=225.0\ \text{W}.


The total energy is 360.0 J, and the average power is 225.0 W. The average lies between the smallest and largest supplied powers, as expected.


c) Using the caller's array and length, calculate the percentage of intervals with power at least 240 W. Write the counting code and verify its result.


“At least” includes equality, so use >=. Initialize the counter to ________ and increment it only when the current reading satisfies the condition. Execute these statements in order:

  • size_t high_count = 0;
  • for (size_t i = 0; i < n; ++i) { if (power_W[i] >= 240.0) { ++high_count; } }
  • double high_percent = 100.0 * (double)high_count / (double)n;

The readings of 240 W and 270 W satisfy the condition. Thus, high_count becomes ________ out of four intervals:


percentage=10024=50.0%.\text{percentage}=100\frac{2}{4}=50.0\%.


The floating-point arithmetic preserves fractional percentages for other datasets as well. Because these intervals have equal duration, 50.0% of the intervals also represents 50.0% of the operating time.

A component-testing program records seven passing components out of eight tested components:


C
int passed = 7;
int tested = 8;
double fraction = passed / tested;


Which replacement for the final declaration correctly calculates the dimensionless passing fraction?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A laboratory program reads one load measurement in kilonewtons into a C variable of type double. Complete the three placeholders so that the program checks whether that measurement was successfully read. Assume the standard input/output declarations are available.


C
double load_kN;
int converted = scanf(FORMAT, DESTINATION);
if (converted != EXPECTED) {
    printf("Invalid load\n");
}


The string literal replacing FORMAT must contain ; enter only the conversion specification, without quotation marks. The expression replacing DESTINATION must be . The integer replacing EXPECTED must be .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A load-monitoring program processes four force readings in newtons:


C
const double load_N[] = {8.0, 12.0, 15.0, 20.0};
double selected_sum_N = 0.0;
int selected_count = 0;

for (int i = 0; i < 4; ++i) {
    if (load_N[i] >= 12.0) {
        selected_sum_N += load_N[i];
        ++selected_count;
    }
}


What are the final selected count and selected sum?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice