Course Code: BBC103
Course: AKTU BCA 1st Year, Semester I
Unit: Decisions, Loops and Functions
Unit II Overview
Choose actions, repeat work and organise reusable calculations. Learn conditional execution, switch, loop forms, multiple counters, nested loops, function interfaces, call by value and recursive functions through traces and complete C programs.
Topics Covered
| Syllabus area | Pages |
|---|---|
| Conditional execution and decision ladders | 2-4 |
| Switch, case restrictions and fall-through | 4-6 |
| Loop forms, counters and nested iteration | 7-11 |
| Break, continue and loop verification | 11-13 |
| Function categories, prototypes and definitions | 13-15 |
| Calls, returns, value passing and program design | 15-17 |
| Recursion and comparison with iteration | 18-19 |
| Worked examples and C programs | 19-23 |
| Exam questions with answers | 24-26 |
| Quick revision and glossary | 27-28 |
Learning Outcomes
-
1. Choose and trace conditional statements.
-
2. Develop loops with reliable progress.
-
3. Use break and continue in the right context.
-
4. Define, call and combine compatible functions.
-
5. Explain value passing and bounded recursion.
Included in These Notes
32 explained sections; 27 labelled diagrams and charts; 10 colourful context images; 16 worked cases; 20 complete C programs; 24 short answers; 6 structured long answers; comparison tables and quick revision.
Study Approach
Understand. Identify conditions, valid domains and required results.
Compare. Compare paths, loop destinations and function interfaces.
Apply. Trace states and returns; build and verify boundary cases.
Core idea: each branch, loop and function needs a clear contract. Track the selected path, progress, parameter values and returned results instead of guessing output.
1. Control flow and meaningful conditions
Control flow determines which statements execute and how often. Unit I introduced expressions; Unit II uses their results to select actions, repeat work and organise functions. A program should follow a clear requirement rather than a collection of memorised patterns.
Conditions in C17. An allowed scalar expression is false when it compares equal to zero and true otherwise. Relational/equality and logical operators produce int results 0 or 1. Assignment = and equality == are different operations; parentheses should make the intended test clear.
Three organising questions. Which action is permitted? What repeats and when does it stop? Which reusable function has responsibility for the work? Define the input domain and expected result before choosing if, switch or a loop.
Convention. Examples use hosted C17 and the same portable beginner style as Unit I. Exact code is printed in monospace and paired with its output. Context illustrations are visual aids; labelled flowcharts and compiled examples carry the precise programming meaning.
2. The if statement: one conditional action
The if statement has the form if (condition) statement. It executes the controlled statement only when the condition is true. If false, execution continues after that statement. A braced compound statement allows several statements to form one controlled block.
Example. With score = 8, if (score > 0) { score += 2; } updates score to 10. For a false test, the update is skipped. Indentation helps readers, but braces and statement syntax determine actual grouping.
Semicolon trap. if (condition); has a null statement as its controlled body. A following braced block is then separate and can execute regardless of the test. Do not add a semicolon after the condition merely because many C statements end in one.
Use. A single optional update or warning suits if. If exactly one of two alternatives must happen, an if-else expresses that requirement more directly than unrelated tests.
Complete C example
#include <stdio.h>
int main(void)
{
int score = 8;
if (score > 0) {
score += 2;
}
printf(“%d\n”, score);
return 0;
}
Output for the stated example: 10
3. if-else: two exclusive alternatives
The form if (condition) statement1 else statement2 chooses exactly one alternative when control reaches it. A true condition selects the first; a false condition selects the second. Each alternative can be a braced block.
Even/odd example. For an integer value n, n % 2 == 0 selects the even case, otherwise the odd case. This test also classifies negative representable integers correctly because a nonzero remainder identifies the odd case.
Mutual exclusion. Two independent if statements are not automatically the same as one if-else. The first action may change the state used by the second test, so both can execute. Choose the construct from the required behaviour.
Testing. Include values that make the condition true and false, plus meaningful boundaries. For parity, use zero, a positive even value, an odd value and a valid negative value. The printed fixed-input example makes one path visible.
Complete C example
#include <stdio.h>
int main(void)
{
int n = 7;
if (n % 2 == 0) {
puts(“even”);
} else {
puts(“odd”);
}
return 0;
}
Output for the stated example: odd
4. Nested if and the dangling-else rule
A nested if places one conditional inside another. It is useful when a second decision is relevant only after the first condition succeeds. For example, first validate that a score is in range, then decide whether it reaches a pass threshold.
Association rule. An else belongs to the nearest preceding unmatched if permitted by the grammar. It does not attach according to visual indentation. Without braces, readers can mistake an inner else for an outer alternative.
Clear grouping. Use braces around both outer and inner blocks when the relationship matters. A structured outline is: if valid, then test pass/fail; else report invalid. This represents three outcomes without relying on misleading indentation.
Avoid deep nesting. Combine suitable predicates, use an else-if ladder or separate responsibilities into functions where that clarifies the requirement. Simplification should preserve which conditions are tested and which actions can run.
Complete C example
#include <stdio.h>
int main(void)
{
int score = 64;
if (score >= 0 && score <= 100) {
if (score >= 40) {
puts(“pass”);
} else {
puts(“fail”);
}
} else {
puts(“invalid”);
}
return 0;
}
Output for the stated example: pass
5. Else-if ladders and boundary ordering
An else-if ladder tests alternatives in order. Once a condition is true, its statement executes and the remaining alternatives in that ladder are skipped. A final else handles the remaining valid cases when appropriate.
Threshold example. After validating 0 to 100, test score >= 75, else score >= 60, else score >= 40, else below 40. High-to-low ordering prevents the broad lower threshold from capturing high scores too early.
Boundaries. Decide whether the limits are inclusive. Values 39, 40, 59, 60, 74 and 75 are useful tests for that stated scheme. These are teaching thresholds, not a claim about an official university grading policy.
Completeness. Invalid input handling and category assignment are separate responsibilities. A final else does not automatically establish that an out-of-range score is a valid lowest category.
6. switch: dispatch using a discrete selector
A switch selects an entry point according to the value of an integer controlling expression. Each case labels a matching constant value. The selector is evaluated for that switch execution and the appropriate label is chosen after the required integer promotions/conversions.
Basic structure. switch (choice) { case 1: action; break; case 2: other_action; break; default: fallback; }. The braces form the switch body; the labels mark positions inside it. Case labels are not ordinary Boolean tests.
Example. The fixed selector 2 jumps to case 2 and prints Save. break then exits the switch. A selector matching no case would enter default if present. The user-interface labels are illustrative.
Use. Small menu selections, integer status codes and character commands often suit switch. Range comparisons or combinations of unrelated predicates often fit if-else better.
Complete C example
#include <stdio.h>
int main(void)
{
int choice = 2;
switch (choice) {
case 1: puts(“Open”); break;
case 2: puts(“Save”); break;
default: puts(“Other”); break;
}
return 0;
}
Output for the stated example: Save
7. Restrictions on switch and case values
In the selected C17 subset, the controlling expression must have integer type, including relevant character/enumeration types. A float, double or string is not a valid direct selector. Use suitable comparisons or other logic for those requirements.
Case labels require integer constant expressions. A literal such as 3 or an enumeration constant can be used. An ordinary variable is not allowed as a case value. A const-qualified int object is not automatically an integer constant expression in C.
Uniqueness. Case values must be distinct after conversion to the promoted selector type. A switch can have at most one default label. An inner switch can have its own labels; restrictions apply to the relevant switch, not every switch in the source file together.
Portability. GNU case ranges such as case 1 … 5 are extensions, not ordinary ISO C17 syntax. A case label introduces a statement position in C17; a braced block can contain declarations and statements clearly when local variables are needed.
| Allowed idea | Invalid direct use | Reason |
|---|---|---|
| switch on int/char/enum | switch on double | Selector must be integer |
| case 3: | case variable: | Requires integer constant expression |
| Distinct case values | Duplicate converted values | Labels must be unique in that switch |
| Optional one default | Two default labels | At most one in that switch |
8. break, default and intentional fall-through in switch
break terminates the nearest enclosing switch or loop. In a switch case, it normally prevents execution from continuing into following labelled statements. Without it or another transfer, control can fall through; the next case is not compared again as a new condition.
Grouped labels. case ‘y’: case ‘Y’: can deliberately share one action. A comment should make intentional fall-through clear. Omitting break accidentally is a common source of extra output or incorrect updates.
default is optional and used when no case matches. It need not be physically last. When a case matches, dispatch goes to that case even if a default label appears earlier in the source. Later fall-through still follows normal sequential execution.
Nested constructs. A break inside a loop nested within a switch exits that nearest loop, not both constructs. A return exits the current function.
These have different control destinations and should not be substituted blindly.
9. Choosing switch or if-else
if-else accepts general scalar conditions, including ranges and compound logical tests. switch dispatches using one integer selector and constant labels. Both can express some of the same finite-choice tasks, but their natural applications differ.
Examples. score >= 40 and temperature < limit fit comparisons. A numbered menu with choices 1, 2 and 3 can fit switch. Comparing strings is not achieved by passing a string directly to switch.
Readability. A long ladder of equality tests on the same selector may be clearer as switch. A ladder of intervals may be clearer as if-else. Structure code so that default/error paths are easy to see.
Efficiency. Do not assert that switch is always faster. Compiler strategy depends on case distribution, target and optimisation. Select the correct clear construct first, then measure relevant performance if necessary.
| Aspect | if-else | switch |
|---|---|---|
| Decision form | General scalar conditions | One integer selector |
| Ranges | Direct comparisons | No ordinary case ranges in ISO C17 |
| Labels | No case labels | Distinct constant integer labels |
| Alternative flow | First true ladder branch | Dispatch plus possible fall-through |
| Best fit | Ranges/compound predicates | Discrete menu/status values |
10. Iteration: initial state, test, work and progress
A loop repeats a controlled statement. Its design identifies an initial state, continuation condition, useful body work and progress toward termination. Finiteness should follow from the valid input assumptions rather than an accidental test result.
Count-controlled repetition uses a known count or bounded counter. Condition/sentinel-controlled repetition depends on input or a changing state. A sentinel is a designated stop value and should not be processed as ordinary data unless the requirement says so.
Three forms. while and for test before entering the body; do-while tests after an execution. Each body can be a braced block. A loop is not guaranteed to run a fixed number of times merely because it uses for.
Trace method. Record the counter/state before the test, the test result, changes in the body and the update. Zero-iteration and one-iteration cases reveal many off-by-one errors.
11. while: test before repeated work
The form while (condition) statement evaluates its condition before each body execution. When false initially, the body executes zero times. After the body, control returns to the condition unless a control-transfer statement changes the path.
Example. Start i = 1, print i and increment it while i <= 3. The successful tests see 1, 2 and 3; the final test sees 4 and exits. There are three body executions and four condition evaluations in this ordinary trace.
Progress. If the required increment is omitted or skipped, the condition may remain true indefinitely. Updating before processing instead of afterward can change which values are handled.
Input loops. Test successful input conversion before using a newly read value, and define how failure/end-of-input terminates the loop. Continually retrying a failed conversion without managing the unread invalid input can create a non-progressing program.
Complete C example
#include <stdio.h>
int main(void)
{
int i = 1;
while (i <= 3) {
printf(“%d “, i);
++i;
}
putchar(‘\n’);
return 0;
}
Output for the stated example: 1 2 3
12. do-while: execute once before the test
The form do statement while (condition); executes its body before the continuation test. Consequently, the body executes at least once when control reaches the do statement normally. The semicolon after the condition is required.
Example. With i initially 5, the example prints 5, increments to 6 and then tests i < 3. The false condition prevents another iteration. An equivalent-looking while with an initial test would execute zero times.
Typical use. A menu/action that should be shown once before asking whether to repeat can suit do-while. Input validation still needs a defined conversion/error path; using do-while does not automatically make user input valid.
continue behaviour. A continue in the body moves to the do-while condition test. It does not skip the test and restart the body immediately. A break exits the loop entirely.
Complete C example
#include <stdio.h>
int main(void)
{
int i = 5;
do {
printf(“%d\n”, i);
++i;
} while (i < 3);
return 0;
}
Output for the stated example: 5
13. for: initialisation, condition and update
The common form is for (initialisation; condition; update) statement. Initialisation runs once, then the condition is tested before each iteration. After a normally completed body, the update runs before the next condition test.
Example. for (int i = 1; i <= 5; ++i) adds the values 1 through 5 to sum. The counter declared in that initialisation belongs to its for-controlled scope; the sum object is declared outside so it remains available afterward.
Omitted parts. The semicolons remain even if clauses are omitted. In for (;;), the omitted condition acts as an always-true continuation condition; termination needs a defined transfer or external arrangement. It is not equivalent to the invalid syntax while().
continue destination. In a for loop, continue goes to the update expression, then the condition. A mechanical rewrite as while can change behaviour if it places an essential update after a continue path.
Complete C example
#include <stdio.h>
int main(void)
{
int sum = 0;
for (int i = 1; i <= 5; ++i) {
sum += i;
}
printf(“%d\n”, sum);
return 0;
}
Output for the stated example: 15
14. Multiple loop variables and comma expressions
A for loop can manage several variables. A declaration such as int i = 0, j = 4 declares two counters of the stated type. An update such as ++i, –j uses the comma operator to perform both updates in sequence.
Example. for (int i = 0, j = 4; i < j; ++i, –j) visits pairs (0,4) and (1,3), then stops when both become 2. Both counters follow the single explicit continuation condition.
Condition trap. Writing i < n, j < m as the condition uses a comma expression: its final value comes from j < m. It does not mean both comparisons must be true. Use && for a genuine logical conjunction.
Clarity. Multiple variables are useful when their relation is simple, such as two ends approaching each other. Too many updates or unrelated side effects in the header obscure correctness. Declared comma-separated names and comma-operator expressions have different grammatical roles.
Complete C example
#include <stdio.h>
int main(void)
{
for (int i = 0, j = 4;
i < j; ++i, –j) {
printf(“%d:%d “, i, j);
}
putchar(‘\n’);
return 0;
}
Output for the stated example: 0:4 1:3
15. Nested loops and row-column reasoning
A nested loop runs an inner loop as part of an outer loop body. For three rows and four columns, an inner body that runs four times on each of three outer iterations runs 12 times overall.
Reset the inner state. A for initialisation inside the outer body normally resets its inner counter for each row. Placing an inner counter initialisation only before the outer loop can change the result after the first pass.
Dependent bounds. A triangular pattern with j from 1 to i does not have the same total as a rectangular grid. For n rows, 1 + 2 + … + n gives n(n+1)/2 inner executions under the stated inclusive bounds.
Control targets. break exits the nearest loop; continue proceeds with the nearest loop’s continuation action. An inner break does not automatically terminate all outer iterations. A function return has a broader destination.
| Outer/inner bounds | Inner executions |
|---|---|
| 3 rows, 4 columns each | 3 x 4 = 12 |
| Row i has i columns for i=1..4 | 1 + 2 + 3 + 4 = 10 |
| Initial condition false for inner loop | Zero for that outer pass |
Complete C example
#include <stdio.h>
int main(void)
{
for (int row = 1; row <= 3; ++row) {
for (int col = 1; col <= 4;
++col) {
printf(“%d “, col);
}
putchar(‘\n’);
}
return 0;
}
Output for the stated example: 1 2 3 4 1 2 3 4 1 2 3 4
16. Assignment operators and reliable loop updates
Compound assignments such as **+=, -=, =, /= and %=* combine an operation with assignment. Bitwise and shift compound forms also exist. For a simple counter, i += 2 advances it by two within valid representability limits.
Accumulator. total += value stores an updated total. Initialise total to the correct identity before use: 0 for a sum and 1 for an ordinary non-empty product/factorial construction. The empty product convention also gives 0! = 1.
Type and range. A counter or accumulator can overflow even if the loop looks finite mathematically. Choose an appropriate type and input bound. Signed overflow is undefined; unsigned wrap can still make a stopping condition wrong.
Single evaluation. Compound assignment evaluates its left operand once in the relevant semantic sense; it is not always a safe source-text expansion. Prefer straightforward updates in beginner loop headers and avoid unsequenced modifications to the same object.
| Form | Simple-variable meaning | Watch |
|---|---|---|
| i += 2 | Advance by two | Range and termination |
| sum += x | Accumulate a sum | Initial zero and range |
| product *= x | Accumulate a product | Initial value and overflow |
| n /= 10 | Remove a decimal quotient digit for nonnegative n | Integer arithmetic |
| n %= 10 | Keep decimal remainder for nonnegative n | Not the same as n /= 10 |
17. break: early exit from the nearest loop
A break statement exits the nearest enclosing loop or switch. It is useful when a successful search, an accepted sentinel or an unrecoverable condition makes further iterations unnecessary.
Example. Scan positive candidates up to 20; when the first multiple of 7 is found, print it and break. The first accepted candidate is 7. Control resumes after the for loop, not at its update expression.
Nested context. If the break is inside an inner switch rather than directly controlling the loop, its nearest enclosing break target can be the switch. Read the actual nesting before claiming that the loop exits.
Design. A clearly explained early exit can improve a loop. Several hidden exits make proof and maintenance harder. State which values may remain unprocessed and how the program distinguishes success from reaching the normal loop limit.
Complete C example
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 20; ++i) {
if (i % 7 == 0) {
printf(“%d\n”, i);
break;
}
}
return 0;
}
Output for the stated example: 7
18. continue: skip the remaining current iteration
A continue statement skips the rest of the current iteration of the nearest enclosing loop. It does not exit that loop. The next destination depends on the loop form: update for for, condition for while and trailing condition for do-while.
Example. In a for loop from 1 through 5, continue when i is even. The remaining body prints only 1, 3 and 5. The for update still executes after each continue.
while pitfall. If an essential counter increment appears after a continue path in a while body, that path can repeatedly skip the update. Place progress correctly or restructure the condition rather than assuming continue increments anything itself.
Switch inside a loop. continue applies to the enclosing loop even when written inside a nested switch. This differs from break, which can exit that switch. Both statements should be traced to their actual destinations.
Complete C example
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 5; ++i) {
if (i % 2 == 0)
continue;
printf(“%d “, i);
}
putchar(‘\n’);
return 0;
}
Output for the stated example: 1 3 5
19. Loop comparison and debugging checklist
while suits a clearly expressed precondition, do-while guarantees an initial body execution when reached normally, and for groups a familiar initialisation/test/update. Any choice still needs correct input and progress logic.
Off-by-one. i < n and i <= n differ at the boundary. Count actual processed values rather than simply reading the final counter value. A counter can be one past the last processed value after normal termination.
Test set. Use zero repetitions if allowed, one repetition, a typical case, a maximum valid input and relevant early-exit/continue paths. Check condition-evaluation counts separately from body-execution counts.
Errors. Wrong accumulator identity, unintended null bodies, stale inner counters, skipped updates, overflow and unhandled input failure are distinct problems. A dry-run table should show the precise step that stops making progress or deviates from the required values.
| Feature | while | do-while | for |
|---|---|---|---|
| First test | Before body | After body | Before body |
| Minimum normal body runs | 0 | 1 | 0 |
| Explicit update clause | No | No | Yes, optional |
| continue destination | Condition | Trailing condition | Update then condition |
20. Functions: purpose and division of responsibility
A function is a named unit of executable behaviour with a declared interface. It may receive parameters, perform work and return a value. The calling function uses that interface instead of duplicating the implementation everywhere.
Benefits. Reuse, abstraction, readability, testing and maintenance improve when functions have focused responsibilities. A long function is not automatically modular merely because it has a name.
Example plan. A geometry program can separate input handling, area calculation and display. A calculation function can be tested with known values without repeating input logic in every call.
Execution. Defining a function makes its body available; it does not run the body immediately. Execution enters it when a call is evaluated. On return, control continues at the caller unless program termination or another special operation changes that flow.
21. Types of functions and interface categories
Library functions are supplied through the implementation’s library interfaces, such as printf and getchar declared by stdio.h. User-defined functions are written for the application. A header normally provides declarations, not a claim that all function implementation code is textually inserted.
Four introductory categories combine parameter presence and value-return presence: no parameters/no value, parameters/no value, no parameters/value, and parameters/value. These describe an interface, not four different calling mechanisms.
Choose deliberately. A reusable arithmetic calculation often takes values and returns a result. A reporting routine may take information and return void. Hidden global dependence can make a superficially no-argument interface harder to test.
void. In a return type it indicates no returned value. In the C17 prototype void report(void), the parameter-list void means no parameters. These two positions have different grammatical roles.
| Category | Prototype example | Possible role |
|---|---|---|
| No parameters, no value | void greet(void); | Display fixed greeting |
| Parameters, no value | void show(int x); | Display supplied value |
| No parameters, value | int initial_value(void); | Return a defined starting value |
| Parameters, value | int add(int a, int b); | Compute sum within range |
22. Declarations and function prototypes
A function declaration introduces its name and type information. A prototype specifies parameter types. For example, int add(int a, int b); declares a two-int-parameter function returning int; the names are optional in that prototype.
Visibility. Put a suitable prototype before a call, or place a compatible definition before that call. Modern C17 code does not rely on an implicit function declaration or an assumed int return type.
Empty parentheses caveat. In a C17 declaration, int f(); does not specify the parameter types; int f(void); explicitly specifies no parameters. Do not teach those declarations as identical. Later language revisions change some rules, so these notes keep their stated C17 mode.
Consistency. Declaration, definition and calls must agree. A diagnostic can identify an incorrect argument count/type relationship when a suitable prototype is visible, but a successful build is not a proof that every function contract is respected.
Complete C example
#include <stdio.h>
int add(int a, int b);
int main(void)
{
printf(“%d\n”, add(4, 5));
return 0;
}
int add(int a, int b)
{
return a + b;
}
Output for the stated example: 9
23. Function definitions and parameter objects
A definition includes the function header and body. In int add(int a, int b) { return a + b; }, a and b are parameter objects used by that invocation, and the return expression supplies the result.
Formal versus actual. Parameters appear in the definition/interface. Arguments are expressions supplied by a call. In add(x, 3), x and 3 are argument expressions; their values initialise the corresponding parameters after the required conversions.
Local work. A function may declare automatic local objects for its calculation. Their scope and lifetime are not the same as the caller’s identically named objects. Each ordinary recursive invocation has its own automatic local/parameter state in the abstract execution model.
Syntax. A prototype ends in a semicolon; a function definition has a braced body. Standard C does not permit defining an ordinary function inside another function body; GNU nested functions are an extension and are not used here.
24. Function calls and return to the caller
A call evaluates a function designator and argument expressions, supplies values and transfers control to the function. A call can be an expression, such as result = add(4, 5), or part of a statement.
Return path. For an ordinary return, the caller receives any returned value and continues at the surrounding expression/statement. Returning from a helper does not exit every function or automatically terminate the program.
Argument order. C17 does not specify a universal left-to-right order for evaluating function arguments. Do not rely on f(g(), h()) calling g before h. Separate evaluations when the order matters.
Avoid conflicting changes. Passing expressions such as i++ and ++i in one call can create unsequenced modifications and undefined behaviour. Parameter passing by value does not repair an invalid argument-expression evaluation.
25. Passing arguments, types and function contracts
Arguments are converted for corresponding parameters according to the visible interface and language rules. An int parameter receiving a representable floating value can receive a truncated integer; if a real-valued calculation is intended, choose a suitable parameter type.
Contract. State valid ranges, meanings and units. int square(int n) requires n*n to be representable if that implementation is used. A correct prototype does not guarantee arithmetic range safety.
Multiple results. A simple scalar-return function yields one declared return value. Multiple-result techniques using pointers/structures are developed in later units. Do not introduce an imaginary language pass-by-reference rule to explain them.
Variadic note. printf uses a special variadic interface and relevant default promotions. Its format string must still match the actual arguments. The ordinary fixed-parameter examples here are not a complete explanation of variadic function design.
| Interface issue | Correct reasoning |
|---|---|
| int parameter, representable 2.9 argument | Parameter receives converted integer 2 |
| double parameter for a fractional calculation | Choose to preserve an intended real value |
| Argument count | Must agree with the appropriate prototype |
| Valid range | Must satisfy the function contract |
| Returned value | Has the declared result type after applicable conversion |
26. Return values, void functions and all-path reasoning
A return expression; ends the current function invocation and supplies a converted value for its declared result type. A void function can use return; to return without a value; reaching its closing brace also returns without a value.
Non-void helpers. Ensure that every relevant execution path provides the intended result. Reaching the closing brace of a non-void helper and then using its absent result has undefined behaviour. main has a specific hosted exception: reaching its end returns 0 in the chosen standard.
Type consistency. Returning a representable double expression from an int-return function converts it to int, truncating the fractional part. That may be valid C but wrong for the intended contract.
Use the result. A caller can assign, compare, print or deliberately ignore an ordinary returned value. Returning a value and printing it are different operations: a pure add function need not display anything.
27. Call by value: copies, not caller-variable replacement
C passes arguments by value. A function parameter receives the relevant converted value of its argument. Assigning to a scalar parameter changes that parameter object, not the caller’s separate scalar object.
Example. Caller x is 10. change(x) receives n = 10, increments its local n and prints 11. After it returns, the caller’s x is still 10. The shared numeric starting value does not make the two objects identical.
Swap consequence. A helper that swaps two plain int parameters only swaps its own copies. To change a caller object through an address, a later pointer-based interface can be used; even a pointer argument is itself passed by value.
Design. Return a computed value when that is the natural interface, for example x = incremented(x). Avoid claiming that call-by-value means a function can never affect anything outside itself: pointer-reachable objects, I/O and global state are separate possibilities.
Complete C example
#include <stdio.h>
void change(int n);
int main(void)
{
int x = 10;
change(x);
printf(“caller=%d\n”, x);
return 0;
}
void change(int n)
{
++n;
printf(“inside=%d\n”, n);
}
Output for the stated example: inside=11 caller=10
28. Writing a multifunction program
A multifunction program divides responsibilities among cooperating functions. main can coordinate input, calls and reporting, while helpers perform focused calculations. Small clear interfaces make it easier to change one part without rewriting all others.
Geometry example. rectangle_area(length, width) computes a product; rectangle_perimeter(length, width) computes twice the sum. Main obtains valid dimensions, calls both and formats results. Each helper has a defined parameter/result type.
Build organisation. Several functions can be defined in one source file. They can also be separated into compatible translation units with suitable declarations and linking; detailed project organisation is beyond this introductory unit.
Test separately and together. Known values can verify each calculation, while an end-to-end test checks input and output coordination. Reuse should reduce duplication without introducing unnecessary tiny functions that obscure the task.
29. Scope and automatic local state in functions
Scope is where a name can be used according to language rules. A parameter name belongs to the function’s definition context, and a block-local declaration is used within its relevant block scope. Equal names in different functions can denote distinct objects.
Automatic state. Ordinary local/parameter objects support separate invocations. Conceptual activation records explain which call owns which value. A physical stack is common, but exact layout, addresses and optimisation are implementation details, not universal C requirements.
Avoid returning an invalid local address. A local automatic object does not remain available merely because the function returns its address. Full pointer/lifetime work belongs to later units; returning a scalar value is a different valid action.
Later topics. Static and external storage classes are assigned to Unit IV. They change persistence/linkage questions and should not be confused with the basic call-by-value explanation. The present examples use clear automatic local state.
30. Recursion: base case and progress
A recursive function calls itself directly or participates in a call cycle through other functions. Recursion expresses a problem in terms of a smaller or otherwise progressing instance of the same kind.
Two requirements. A base case supplies a result without another recursive call. The recursive case must progress toward it for the valid domain. Merely writing if somewhere in the function does not establish termination.
Factorial model. For non-negative n, 0! = 1 and n! = n x (n-1)! for n>0. An implementation can use n<=1 as a combined base case for n=0 or 1. Reject invalid negative inputs before converting to an unsigned domain.
Limits. Result range and call resources matter. A mathematically terminating recursion can still be unsuitable for a large input. Tail-call optimisation is not guaranteed, so do not promise constant memory for every tail-recursive C function.
31. Recursive factorial and an activation trace
The complete example defines an unsigned-input factorial with result type unsigned long long and calls it for 5. The valid teaching domain is 0 through 20; 20! fits the minimum required unsigned long long range, while larger inputs are not accepted as a universal guarantee.
Descent. fact(5) waits for fact(4), which waits for fact(3), then fact(2), then the base fact(1). Each invocation retains its own relevant n until its result is formed.
Unwinding. Return values combine as 1, 2, 6, 24 and 120. fact(0) also returns 1 directly. A recursive-call count and a multiplication count are different measurements.
Verification. Test the base values 0 and 1, a small ordinary value and the stated upper bound using an appropriately bounded driver. The fixed example is not an unrestricted input validator.
Complete C example
#include <stdio.h>
unsigned long long fact(unsigned int n);
int main(void)
{
printf(“%llu\n”, fact(5u));
return 0;
}
unsigned long long fact(unsigned int n)
{
if (n <= 1u)
return 1u;
return n * fact(n – 1u);
}
Output for the stated example: 120
32. Recursion versus iteration and final design choices
Iteration maintains a changing state in a loop. Recursion expresses progress through calls and returns. Both can implement factorial or Euclid’s greatest-common-divisor method. They are alternative organisations, not automatic correctness guarantees.
Euclid example. gcd(a,b) returns a when b=0; otherwise it calls gcd(b,a%b) for a stated non-negative/unsigned domain. Remainders drive progress. A convention such as gcd(0,0)=0 should be stated if that input is allowed.
Efficiency. Simple factorial iteration has a small fixed amount of explicit working state; direct recursion conceptually has one active chain proportional to depth. Actual optimisation can change implementation details. Naive recursive Fibonacci repeats overlapping work and should not be assumed efficient.
Final method. Select control structures and function interfaces from the requirement. Trace branch boundaries, loop progress, argument values, return paths and recursion bases. Compile with diagnostics and compare valid/edge-case outputs with independent expectations.
| Aspect | Iteration | Direct recursion |
|---|---|---|
| Progress | State/counter update | Smaller/progressing call |
| Stopping | Condition or defined exit | Base case |
| Working state | Explicit loop objects | Separate active invocation state conceptually |
| Common risks | Skipped update/off-by-one | Missing base/progress, depth |
| Best choice | Depends on clarity and constraints | Depends on clarity and constraints |
SOLVED EXAMPLES AND APPLICATIONS
The following are original teaching cases. Trace the selected path, state updates and returned values under the stated C17 assumptions.
Solved example 2.1: One optional action
For int x = 0, execute if (x > 0) { x += 5; } then print x. What is printed?
-
1. Condition. 0 > 0 is false.
-
2. Flow. The controlled update is skipped; x remains 0.
Answer. 0. The statement after the if continues normally.
Solved example 2.2: Boundary category
After validating the range 0-100, a ladder tests >=75, then >=60, then >=40, then else. Which band receives score 60?
-
1. Ordered tests. 60 >= 75 is false; 60 >= 60 is true.
-
2. Stop selecting. That branch runs and later ladder alternatives are skipped.
Answer. The stated >=60 band. These are teaching thresholds, not an official grading rule.
Solved example 2.3: Dangling else
An unbraced outer if contains an inner if followed by else. Which if gets that else?
-
1. Grammar. The else associates with the nearest unmatched if permitted by the syntax.
-
2. Readability. Braces make a different intended outer/inner grouping explicit.
Answer. The inner if in this described nesting. Indentation does not override the grammar.
Solved example 2.4: Switch fall-through
A switch enters case 1, which prints A and has no break. Next is case 2, which prints B then breaks. What happens for selector 1?
-
1. Dispatch. Control starts at case 1.
-
2. Sequential execution. It continues into case 2 statements without testing the label again, then exits at break.
Answer. A followed by B, in the formatting used by the calls. Removing break can change behaviour, not just speed.
Solved example 2.5: Case-label validity
Can an ordinary int variable or a double selector be used directly for switch dispatch/case labels in ISO C17?
-
1. Selector. A direct double controlling expression is invalid; switch requires integer type.
-
2. Case. An ordinary variable is not an integer constant expression for a case label.
Answer. No to those respective uses. A const int object is not automatically a valid case constant either.
Solved example 2.6: while count and tests
Start i=2; while (i <= 4) { process i; ++i; }. Count body executions and condition evaluations.
-
1. Visits. The body processes 2, 3 and 4: three executions.
-
2. Final check. The condition is tested again for 5 and is false: four evaluations in total.
Answer. 3 body runs, 4 tests, final i = 5, assuming ordinary completion and representable updates.
Solved example 2.7: Post-test minimum
Start i=5 and execute do { process i; ++i; } while (i < 3);. How often does the body run?
-
1. First action. A do-while body executes before its first test.
-
2. Test. After the increment i=6, so 6<3 is false.
Answer. One body execution and one condition evaluation.
Solved example 2.8: Two counters
Trace for (int i=0,j=4; i<j; ++i,–j). Which pairs reach the body?
-
1. First visits. The condition succeeds at (0,4) and (1,3).
-
2. Stop. The update produces (2,2), where i<j is false.
Answer. The body visits (0,4) and (1,3), not (2,2).
Solved example 2.9: Nested loop total
For i from 1 through 4, an inner loop runs j from 1 through i. Find the total inner executions.
-
1. Row counts. The rows contribute 1, 2, 3 and 4 visits.
-
2. Total. 1+2+3+4 = 10.
Answer. 10. Multiplying 4 by 4 would incorrectly assume rectangular bounds.
Solved example 2.10: continue in a for loop
For i=1 through 5, continue on even i and print otherwise. What values print, and does the update run after continue?
-
1. Selection. Even 2 and 4 skip printing; odd 1,3,5 reach it.
-
2. Destination. for continue proceeds to the update expression before the next condition.
Answer. 1, 3 and 5 print. The declared for update still runs on the continue path.
Solved example 2.11: Nearest break target
An outer for contains an inner while, and break is executed inside that while. Does it end the outer for?
-
1. Target. The nearest enclosing loop/switch is the inner while in this arrangement.
-
2. Resume. Control continues after the inner while within the outer body.
Answer. No. It exits the inner while; outer execution follows its remaining body/update/condition.
Solved example 2.12: Value-copy trace
Caller x=10 is passed to void change(int n), which sets n=99. What is x afterward?
-
1. Parameter object. n receives a copy of the relevant argument value.
-
2. Local update. Assigning 99 to n changes that parameter, not the separate caller object.
Answer. x remains 10. Pointer-based caller modification is a different interface, while the pointer argument itself is also passed by value.
Solved example 2.13: Return conversion
An int-return helper returns the representable expression 7.9. What result does its caller receive?
-
1. Declared type. The result is converted to the function return type int.
-
2. Conversion. Representable floating-to-integer conversion truncates the fractional part toward zero.
Answer. Integer 7. This may be valid C but unsuitable for a contract requiring the fraction.
Solved example 2.14: Function interface correction
In C17, does int f(); explicitly declare that f accepts no arguments?
-
1. Declaration meaning. An empty parameter list in this declaration does not specify parameter types.
-
2. Explicit form. int f(void); supplies the intended no-parameter prototype.
Answer. No. Use the explicit void parameter list for this C17 no-argument interface.
Solved example 2.15: Factorial recursive trace
Using fact(n)=1 for n<=1 and n*fact(n-1) otherwise, trace fact(4). Count calls and non-base multiplications.
-
1. Calls. fact(4), fact(3), fact(2), fact(1): four invocations.
-
2. Returns. 1 -> 2 -> 6 -> 24. The non-base cases multiply three times.
Answer. 24, with four calls and three non-base multiplications for this stated base-case choice.
Solved example 2.16: Recursive Euclid trace
For unsigned inputs, gcd(a,b) returns a if b=0, otherwise gcd(b,a%b). Trace gcd(48,18).
-
1. Remainders. 48%18=12; 18%12=6; 12%6=0.
-
2. Calls. (48,18) -> (18,12) -> (12,6) -> (6,0); base returns 6.
Answer. The greatest common divisor is 6; each recursive step progresses toward a zero second argument.
Complete practice programs
Input conversions are checked before values are used. Additional valid-domain restrictions are stated with each example.
Practice program 2.1: Largest of three
Read three representable int values. Independent comparisons update a current maximum and handle ties.
#include <stdio.h>
int main(void)
{
int a, b, c;
if (scanf(“%d %d %d”, &a, &b, &c) != 3)
return 1;
int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;
printf(“%d\n”, largest);
return 0;
}
Sample input: 23 17 23 Output: 23
Practice program 2.2: Prime test
Accept int n from 0 to 10000. Values below 2 are not prime. The divisor bound d<=n/d avoids a squared-bound overflow pattern.
#include <stdio.h>
int main(void)
{
int n;
if (scanf(“%d”, &n) != 1) return 1;
if (n < 0 || n > 10000) return 2;
int prime = n >= 2;
for (int d = 2; prime && d <= n / d;
++d) {
if (n % d == 0) {
prime = 0;
break;
}
}
puts(prime ? “prime” : “not prime”);
return 0;
}
Sample input: 29 Output: prime
Practice program 2.3: Four interfaces
Four fixed-value calls show the parameter/result categories.
#include <stdio.h>
void greet(void) { puts(“Hi”); }
void show(int x) { printf(“%d\n”, x); }
int start(void) { return 4; }
int add(int a, int b) { return a + b; }
int main(void)
{
greet();
show(3);
printf(“%d\n”, start());
printf(“%d\n”, add(4, 5));
return 0;
}
Sample input: None (fixed values) Output: Hi 3 4 9
Practice program 2.4: Arithmetic switch
Read two finite representable double values with an operator between them. Results are assumed representable. Unsupported operators and division by zero return status 2.
#include <stdio.h>
int main(void)
{
double a, b, result;
char op;
if (scanf(“%lf %c %lf”,
&a, &op, &b) != 3)
return 1;
switch (op) {
case ‘+’: result = a + b; break;
case ‘-‘: result = a – b; break;
case ‘*’: result = a * b; break;
case ‘/’:
if (b == 0.0) return 2;
result = a / b;
break;
default: return 2;
}
printf(“%.2f\n”, result);
return 0;
}
Sample input: 6 / 3 Output: 2.00
Practice program 2.5: Multifunction geometry
Main calls area and perimeter helpers for fixed dimensions 7 and 4.
#include <stdio.h>
double area(double l, double w);
double perimeter(double l, double w);
int main(void)
{
double l = 7.0, w = 4.0;
printf(“Area=%.2f\n”, area(l, w));
printf(“Perimeter=%.2f\n”,
perimeter(l, w));
return 0;
}
double area(double l, double w)
{
return l * w;
}
double perimeter(double l, double w)
{
return 2.0 * (l + w);
}
Sample input: None (fixed values) Output: Area=28.00 Perimeter=22.00
Practice program 2.6: Recursive GCD
Read two unsigned values in the stated range 0-10000. This example defines gcd(0,0)=0 by its base rule.
#include <stdio.h>
unsigned int gcd(unsigned int a,
unsigned int b);
int main(void)
{
unsigned int a, b;
if (scanf(“%u %u”, &a, &b) != 2)
return 1;
if (a > 10000u || b > 10000u)
return 2;
printf(“%u\n”, gcd(a, b));
return 0;
}
unsigned int gcd(unsigned int a,
unsigned int b)
{
if (b == 0u) return a;
return gcd(b, a % b);
}
Sample input: 252 198 Output: 18
Trace the practice calls
The geometry helpers receive values and return results; main performs the displayed formatting.
| Helper call | Calculation | Returned value |
|---|---|---|
| area(7.0, 4.0) | 7 x 4 | 28.0 |
| perimeter(7.0, 4.0) | 2 x (7 + 4) | 22.0 |
Recursive GCD: sample input 252, 198
| Current call | Remainder | Next action |
|---|---|---|
| gcd(252,198) | 54 | gcd(198,54) |
| gcd(198,54) | 36 | gcd(54,36) |
| gcd(54,36) | 18 | gcd(36,18) |
| gcd(36,18) | 0 | gcd(18,0) |
| gcd(18,0) | Not evaluated | Base returns 18 |
The returned 18 passes back through the callers. The base test occurs before remainder evaluation, so the base call does not divide by zero.
Boundary and rejection checks
| Program/input | Expected output | Exit status |
|---|---|---|
| Prime test: 1 | not prime | 0 |
| Prime test: 2 | prime | 0 |
| Arithmetic: 7 / 0 | No result printed | 2 |
| GCD: 0 0 | 0 (stated convention) | 0 |
EXAM QUESTIONS WITH ANSWERS
Practice questions covering the definitions, comparisons and applications in Unit II.
Short-answer practice
Q1. What controls an if decision?
Answer. Its allowed scalar condition is false when equal to zero and true otherwise.
Q2. Why use braces?
Answer. They make a compound controlled statement and the intended nesting explicit; indentation alone does not group statements.
Q3. What is dangling else?
Answer. An else associates with the nearest unmatched if permitted by the grammar, not according to indentation.
Q4. How does an else-if ladder select?
Answer. It chooses the first true condition in order and skips the remaining alternatives in that ladder.
Q5. Which switch selectors are allowed here?
Answer. Integer controlling expressions, including relevant character/enumeration types; not direct floating or string selectors in ISO C17.
Q6. What must a case label contain?
Answer. An integer constant expression with a distinct converted value in that switch.
Q7. Is default mandatory or always last?
Answer. No. It is optional and can appear elsewhere in the switch body; at most one belongs to that switch.
Q8. Define switch fall-through.
Answer. Sequential execution continues into following labelled statements without a new selector comparison when no control transfer stops it.
Q9. Can switch always replace if?
Answer. No. General ranges and compound predicates are natural if conditions; switch uses one integer selector with constant labels.
Q10. Which loop must initially run once?
Answer. A do-while body executes before its first condition test when the statement is reached normally.
Q11. What does a for update do?
Answer. It runs after a normally completed body or a continue path, before the next condition test.
Q12. What happens in for (;;) ?
Answer. The omitted continuation condition is treated as true; termination needs an appropriate defined transfer or other arrangement.
Q13. How are multiple counters updated?
Answer. A for declaration can introduce several names and a comma expression can sequence several update operations.
Q14. What does an inner break exit?
Answer. The nearest enclosing loop or switch, not every enclosing construct.
Q15. What does continue skip?
Answer. The rest of the current iteration; it then goes to the loop-form-specific continuation destination.
Q16. Why initialise an accumulator?
Answer. The initial value determines the calculation, such as zero for a sum and one for a product.
Q17. Define a function prototype.
Answer. A declaration specifying a function interface with parameter types; it supports consistent declarations and calls.
Q18. Declaration versus definition?
Answer. A declaration introduces type/name information; a definition also supplies the executable function body.
Q19. Arguments versus parameters?
Answer. Arguments are call expressions; parameters are the callee objects/interfaces receiving the corresponding converted values.
Q20. What are four interface categories?
Answer. No parameters/no value; parameters/no value; no parameters/value; parameters/value.
Q21. What does call by value mean?
Answer. The callee receives argument values in separate parameter objects; assigning to a scalar parameter does not replace its caller object.
Q22. Returning versus printing?
Answer. Returning supplies a result to the caller; printing writes output to a stream. A calculation helper need not print.
Q23. What makes recursion terminate?
Answer. A valid base case and recursive progress that reaches it for the stated input domain, within applicable resource/range limits.
Q24. Is tail-call optimisation guaranteed?
Answer. No. Do not promise a particular memory use or physical stack layout solely from a recursive C source form.
Structured long-answer practice
Use a definition, clearly separated points, a relevant example and a labelled diagram or comparison where appropriate. Match the length to the marks and the question rather than memorising a fixed word count.
Long question 1. Explain if, if-else, nesting and ordered decisions.
Answer
-
1. Condition. An allowed scalar expression supplies truth: zero is false, nonzero true. Tests must express the intended comparison; = and == have different roles.
-
2. Single and dual actions. if performs one optional controlled action. if-else chooses exactly one of two alternatives. Braced blocks group multiple statements; an unintended null statement changes the controlled body.
-
3. Nesting. An inner if can refine a decision after an outer condition. Else associates with the nearest unmatched if, so braces make the intended relationship clear.
-
4. Ladders. Ordered else-if conditions choose the first true branch. Range validation and classification are separate responsibilities; threshold order determines which band catches a boundary.
-
5. Testing. True/false, equal-boundary and invalid-input cases are traced independently. Two separate if statements can both run and are not automatically equivalent to one exclusive if-else.
Long question 2. Explain switch restrictions, break, default and comparison with if-else.
Answer
-
1. Dispatch. A switch evaluates an integer selector and transfers to a matching converted constant case value. Case values belong to their relevant switch and must be distinct there.
-
2. Restrictions. Ordinary variable case labels, direct double/string selectors and GNU range cases are not ordinary ISO C17 forms. A const int object is not automatically an integer constant expression.
-
3. Flow. After dispatch, execution is sequential until a transfer or the end. Break exits the nearest loop/switch; grouped labels can deliberately share an action. Accidental missing breaks cause unwanted fall-through.
-
4. Default. One optional default handles no-match dispatch and need not be last. When a case matches, it is selected even if a default appears earlier in source order.
-
5. Choice. Discrete menu/status values suit switch. Ranges and compound predicates suit if-else. Correctness/readability come first; switch is not universally faster on every target.
Long question 3. Compare while, do-while and for with control transfers.
Answer
-
1. Pre-test loops. while tests before the body and can run zero times. for performs initialisation once, tests before the body and updates before the next test after ordinary completion.
-
2. Post-test loop. do-while executes before its first test and requires its trailing semicolon. It suits tasks that genuinely need one initial execution.
-
3. Break and continue. Break exits the nearest loop/switch. Continue skips the rest of an iteration, going to a while/do test or a for update then test. A nested switch can change a break target while continue still targets the loop.
-
4. Nested/multiple state. Several counters can share an explicit condition and sequenced update. Inner loops need suitable reinitialisation; dependent bounds require summing visits rather than blindly multiplying dimensions.
-
5. Correctness. Initial state, valid input, progress and range must support termination. Off-by-one tests, skipped updates, null bodies and accumulator identity are separate error sources. Trace zero/one/typical and boundary cases.
Long question 4. Explain functions, prototypes, calls and returns.
Answer
-
1. Role. Functions encapsulate focused behaviour behind an interface. Library functions have declared standard interfaces; user functions serve application requirements. Parameter/result presence gives four introductory categories.
-
2. Declaration and definition. A prototype states parameter types; a compatible definition supplies the body. In C17, f(void) explicitly has no parameters, while an empty declaration list f() does not specify parameter types.
-
3. Call. Argument expressions supply values with the required conversions. Their evaluation is not universally left to right. The caller then continues after an ordinary return using any result in its surrounding expression.
-
4. Return. A value return converts to the declared result type. A void function has no returned value. Relevant non-void helper paths should provide the intended result; main has its specific hosted end-of-function rule.
-
5. Program organisation. Main can coordinate input, calculations and output through several helpers. Compatible declarations, valid arithmetic domains and independently checked results matter as much as syntactic separation.
Long question 5. Explain call by value and scope using an example.
Answer
-
1. Copy. C argument passing supplies values. With x=10 and change(x), an int parameter n receives 10 as a separate object.
-
2. Local modification. Incrementing or assigning n changes that parameter. The caller x remains 10 after return unless a different interface/effect explicitly modifies it.
-
3. Scope and lifetime. Equal names in different function scopes can denote different objects. Each ordinary recursive invocation has its own automatic state conceptually; physical stack details are implementation-dependent.
-
4. Swap and addresses. Swapping two plain int parameters exchanges only their local copies. A later pointer-based interface can reach caller objects, while the pointer argument itself is still passed by value.
-
5. Design consequence. Return a result when natural, for example x=incremented(x). Call by value does not mean every function is free from I/O, global effects or pointer-reachable modification; those are separate concerns.
Long question 6. Explain recursion and compare it with iteration.
Answer
-
1. Definition. A direct recursive call invokes the same function; indirect recursion uses a call cycle. A base case avoids another recursive call, and the recursive case progresses toward it for a stated domain.
-
2. Factorial. For the defined unsigned teaching domain 0-20, n<=1 returns 1 and otherwise n*fact(n-1) combines the result. fact(4) invokes 4,3,2,1 and returns 1,2,6,24.
-
3. Euclid. gcd(a,b) returns a when b=0, otherwise gcd(b,a%b). For 48,18 the argument pairs become 18,12 then 12,6 then 6,0, returning 6.
-
4. Resources. Representable results, call depth and input validation remain necessary. A mathematical termination argument does not guarantee enough machine resources; tail-call optimisation is not promised.
-
5. Iteration comparison. A loop updates explicit state; recursion uses progressing calls and return combination. Choose the form that meets clarity and resource needs. Repeated overlapping work, as in naive Fibonacci recursion, can make a particular recursive method inefficient.
QUICK REVISION – UNIT II
The complete unit at a glance
| Syllabus area | Essential understanding |
|---|---|
| Conditional execution | if, if-else, nearest unmatched else, ordered ladders and boundaries. |
| Switch | Integer selector, constant case labels, converted uniqueness, optional default and fall-through. |
| Iteration | Initial state, condition, body and progress; pre-test versus post-test. |
| Multiple/nested loops | Several counters need one intended condition; inner visits depend on their actual bounds. |
| Assignments / transfers | Compound updates retain type/range limits; break and continue have precise destinations. |
| Functions | Library/user categories, four parameter-result combinations, declarations and definitions. |
| Interfaces | Visible compatible prototypes, arguments, converted parameter values and typed returns. |
| Program design | Main plus focused helpers; local scope and automatic invocation state. |
| Call by value | Scalar parameter assignment changes its own object, not the separate caller object. |
| Recursion | Base case, progress, valid domain, result range and call-resource limits. |
Control destination map
| Construct | Next destination / effect |
|---|---|
| if-else | Exactly one alternative when reached. |
| case without a transfer | Sequential flow into following statements, including later labels. |
| break | After the nearest enclosing switch or loop. |
| continue in for | Update expression, then condition. |
| continue in while | Condition test. |
| continue in do-while | Trailing condition test. |
| return | Caller of the current invocation, with a value where appropriate. |
Loop and function quick comparisons
| Question | Key answer |
|---|---|
| Minimum body runs | while/for can run zero times; do-while runs at least once when reached normally. |
| Several loop conditions | Use a logical combination when all are required; a comma expression yields its final operand. |
| Nested iteration count | Multiply only for rectangular fixed bounds; sum for dependent bounds. |
| Function prototype | Declares parameter types; definition supplies the body. |
| C17 no-argument form | Use f(void); an empty declaration list f() does not specify parameter types. |
| Argument passing | C passes values, including pointer values; changing a scalar parameter alone does not replace its caller object. |
| Return versus display | A function can return without printing, or print with no scalar result. |
| Recursion progress | Each valid recursive step must approach a base case; resource/range constraints still apply. |
Abbreviations and key terms
| Term | Meaning | Term | Meaning |
|---|---|---|---|
| Condition | Expression used to decide control flow | Break | Exit nearest loop/switch |
| Branch | Selected alternative action path | Continue | Skip to loop continuation action |
| Else-if ladder | Ordered first-true selection | Prototype | Declaration of parameter types |
| Case label | Constant switch entry label | Definition | Function interface plus body |
| Fall-through | Sequential flow into following case code | Argument | Expression supplied by a call |
| Default | Optional no-match switch label | Parameter | Callee object receiving a value |
| Iteration | One repeated body execution | Return type | Declared result type |
| Pre-test | Condition before body | Void | No returned value in that role |
| Post-test | Condition after body | Call by value | Argument values copied to parameters |
| Accumulator | Object storing a running result | Recursion | Progressing direct/indirect self calls |
| Sentinel | Designated value ending processing | Base case | Non-recursive stopping case |
| Nested loop | Loop inside another loop body | Activation | One function invocation state |
Common mistakes to avoid
-
Adding an unintended semicolon after an if or loop condition.
-
Using indentation instead of braces to explain else association.
-
Putting a broad low threshold before a needed higher category.
-
Using floating/string selectors or ordinary variable case labels in ISO C17.
-
Forgetting intentional-versus-accidental switch fall-through.
-
Confusing body-execution count with condition-evaluation count.
-
Using comma when both comparisons need logical AND.
-
Skipping an essential while update through continue.
-
Assuming an inner break exits all enclosing loops.
-
Reading an uninitialised accumulator or ignoring range limits.
-
Treating a prototype as a definition or f() as f(void) in C17.
-
Assuming a scalar parameter update replaces the caller variable.
-
Confusing printed output with a returned value.
-
Writing recursion without a valid base, progress and result/depth bounds.
Final check: identify the chosen path, loop progress and transfer destination, then verify interfaces, parameter copies, return paths and recursion boundaries using independent tests.