Data and Control Structures in C
C Syntax and Control Structures
C syntax and control structures determine how you represent values, calculate results, and choose which statements execute. You use these rules when processing measurements, checking limits, or repeating work over an array. The snippets here use C99 or later and assume that declarations and statements appear inside a valid function body; the focus is the statements themselves.
Types, expressions, and statements
A declaration gives an object a type and a name. For example, int count = 0; creates an integer object with an initial value. Use double for floating-point values and char for character-sized integer storage. A plain character constant uses single quotes, as in 'A'. Do not assume that int always occupies a particular number of bytes.
An expression combines values, objects, and operators to compute a value. Assignment also changes an object: count = count + 1; evaluates the addition and stores the result. Most declarations and expression statements end with a semicolon. Braces group statements into a block.
An array stores a fixed number of elements of one type:
int delays[3] = {8, 13, 19};
int first = delays[0];The three valid indices are 0, 1, and 2. Accessing delays[3] is outside this array. C does not automatically check an index against the array's length.
Operators and arithmetic types
The operators +, -, *, and / perform arithmetic. When both operands of / have integer types, the result is an integer quotient truncated toward zero. For integer values where division is defined, the quotient and remainder satisfy
Here, % produces the integer remainder. The divisor must be nonzero, and the quotient must be representable in its result type. Keep calculations within the type's range.
Example: For positive integers, 11 / 4 is 2 and 11 % 4 is 3. Assigning 11 / 4 to a double stores 2.0. Writing 11.0 / 4 instead produces 2.75 because the division uses floating-point arithmetic.
A cast such as (double) total can make that conversion. Comparison operators include <, <=, >, >=, ==, and !=. They produce an int value of 1 for true or 0 for false. Assignment uses =, whereas equality testing uses ==.
Choosing a path
A control structure determines which statements run and whether they repeat. In a condition, zero is false and a nonzero value is true:
if (delay >= limit) {
flagged = 1;
} else {
flagged = 0;
}Use braces to make each branch's extent clear. A semicolon immediately after if (condition) would create an empty controlled statement.
Logical && requires both conditions to be true; || requires at least one. They use short-circuit evaluation. Thus, count != 0 && total / count > limit checks count before considering division. Logical ! reverses truth. Bitwise & and | do not provide this short-circuit protection.
A switch chooses among integer-valued cases. Execution starts at a matching case, or at default if provided and no case matches. It continues through subsequent statements unless redirected, commonly by break; case labels do not automatically stop execution.
Repeating statements
Choose a loop according to where its test belongs and how its state changes.
Form | Condition checked | Minimum body executions |
|---|---|---|
while (condition) | Before each iteration | 0 |
do { body } while (condition); | After each iteration | 1 |
for (initialization; condition; update) | Before each iteration | 0 |
In for (int i = 0; i < 3; i++), initialization happens once. Each successful test permits a body execution, and i++ then increases i by one. The indices visited are 0, 1, and 2.
break exits the nearest enclosing loop or switch. continue skips the remaining statements of the current loop iteration. In a for loop, continue still leads to the update expression before the next test.
What to remember
- Operand types determine arithmetic before assignment occurs.
- Conditions interpret zero as false and nonzero as true.
- Array indices must remain within the valid range.
- Track tests, updates, break, and continue explicitly.
Example: Screening response times
A technician records five response times, in milliseconds, and wants the mean of readings at least 20 ms. Use C syntax and control structures to analyze the following statements, which execute inside a valid function body.
An accumulator stores a running total as a loop processes values. Here, total accumulates selected response times, while count records how many readings were selected.
int readings[5] = {14, 22, 18, 25, 17};
int count = 0;
int total = 0;
for (int i = 0; i < 5; i++) {
if (readings[i] >= 20) {
total += readings[i];
count++;
}
}Assume all integer calculations are within range.
a) Find the final count and total, including the unit represented by total.
Start with count = 0 and total = 0. The loop visits indices 0 through 4 because it tests i < 5 before each body execution.
At index 0, the condition 14 >= 20 is ________, so neither object changes. At index 1, the reading is accepted: the running total becomes ________, and count becomes 1.
At index 2, 18 ms is below the threshold, so the total and count stay unchanged. At index 3, 25 ms is accepted:
At index 4, 17 ms is rejected. The update then makes i equal to 5, and the next test fails before another array access.
The final answers are count = 2 readings and total = 47 ms. The total represents the sum of the selected response times.
b) The technician appends double mean = total / count;. Find the stored value, then rewrite the statement to retain the fractional result and calculate that result.
The operands total and count both have type ________. Their division therefore produces an integer quotient before assignment to mean:
Conversion to the destination type then stores 23.0 ms. The fractional part has already been discarded.
Convert total to ________ before dividing. The parenthesized type name is a cast:
double mean = (double) total / count;This makes the division floating-point:
The corrected statement stores 23.5 ms. Casting the quotient afterward, as in (double) (total / count), would still produce 23.0 ms.
c) The threshold is changed from 20 ms to 30 ms, and the loop is rerun from the same initial values. Determine the new count and total, then write a conditional that calculates mean only when at least one reading qualifies. Otherwise, set an integer object named has_mean to 0.
All five readings are below 30 ms. No iteration enters the selection branch, leaving count = 0 and total = 0 ms. Evaluating total / count would attempt division by zero.
Use a condition before calculating the mean:
double mean = 0.0;
int has_mean = 0;
if (count > 0) {
mean = (double) total / count;
has_mean = 1;
} else {
has_mean = 0;
}Evaluate the division only after establishing that the count is positive. With the 30 ms threshold, the condition is false, so the else branch leaves has_mean = 0. The initialized mean remains 0.0, but it is a placeholder rather than a calculated mean; subsequent code should use has_mean to decide whether a result is available.
A monitoring program needs one object containing an integer sensor identifier and a double reading. Complete the following statements about declaring this grouped type and accessing its members.
The C keyword that introduces a type grouping these named members is .
For an object named sample, the single punctuation character placed between sample and reading to access its reading member directly is .
A monitoring program has received no readings yet. Which statements about the following C code are true? Select every true statement.
int count = 0;
int total = 0;
int alarm = 0;
if (count != 0 && total / count >= 20) {
alarm = 1;
}