Control Structures
In questa pagina 9
Basic syntax rules
- Braces
{ }define code blocks (compound statements) for loops and conditionals; they tell the compiler the scope of the block. - Semicolon ends every statement (declarations, assignments, calls, control structures); a missing one is a syntax error.
- Case sensitive:
myVariableandmyvariableare different identifiers. - Programs that are a linear sequence of statements are very limited: control structures make statements optional (conditionals) or repeated (loops).
if / else if / else
if (condition1) {
// condition1 true
} else if (condition2) {
// condition1 false and condition2 true
} else {
// none of the above
}- The condition is an expression: 0 is false, non-zero is true.
- Conditions are checked top to bottom; the first match wins and later
else ifare not evaluated. Make the first condition the most specific;elseis the catch-all.
#include <stdio.h>
int main() {
int number = 5;
if (number > 0) printf("The number is positive.\n");
else if (number < 0) printf("The number is negative.\n");
else printf("The number is zero.\n");
return 0;
}- Slide exercises: score (0-100) to letter A (90-100), B (80-89), C (70-79), D (60-69), F (0-59),
Invalidoutside; maximum of three integers; temperature category (below 0 Freezing, 0-15 Cold, 16-25 Mild, 26-35 Warm, above 35 Hot).
Combining conditions: leap year (worked example)
Specification: read a year; it is leap if divisible by 4 and not by 100, or divisible by 400. Condition operators are in Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →.
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}switch
Multi-way decision: tests whether an expression matches one of several constant integer values.
switch (expression) {
case constant1:
// code
break;
case constant2:
// code
break;
default:
// no case matched
}- Any number of
cases; all case values must be different, and each is an integer constant, constant expression or enumerated type (same type as the switch variable, a literal or constant). - Execution starts at the matching case and goes on until a
break, which jumps to the line after the switch. - Without
breakthere is fall-through: all following cases run whether they match or not. Not robust, avoid it (except to group labels, ascase 'B': case 'C':below). defaultruns if nothing matches; it is optional (without it, no action takes place). Cases anddefaultmay appear in any order.- Good form: put
breakalso after the last case, so adding a case later does not break correctness.
char grade = 'B';
switch (grade) {
case 'A': printf("Excellent!\n"); break;
case 'B':
case 'C': printf("Well done\n"); break;
case 'D': printf("You passed\n"); break;
case 'F': printf("Better try again\n"); break;
default: printf("Invalid grade\n");
}The slides also show a day-of-week example: dayCode 1..7 prints Monday..Sunday, default prints Invalid day code.
- Slide exercises: vowel or consonant by grouping cases; score to letter with
switch(score/10)and fall-through to group ranges, out of rangeInvalid.
Ternary operator ?:
z = (a > b) ? a : b; /* z = max(a, b) */- Form:
expression1 ? expression2 : expression3. If expression1 is non-zero, only expression2 is evaluated and is the value; otherwise only expression3. Equivalent toif (a > b) z = a; else z = b;.
const char* status = (age < 18) ? "minor" : "adult";
printf("You are: %s", status);- Pros: compact, fewer lines. Nesting is possible,
int result = (x > 0) ? ((x == 1) ? 100 : 200) : -1;, but reduces readability: use for simple conditions only. - Slide exercises:
double safe_div(double num, double den)(0.0 if den is 0.0);int max3(int a, int b, int c)withoutif;int sgn(int x)(1, 0, -1, noif); predictxandyafterint y = 1; int x = y ? (y = 0) : 2;.
goto and labels
goto label;
...
label: statement;- Jumps to a labelled statement in the same function; the label can be any identifier except a C keyword, placed above or below the
goto. - Never necessary and generally discouraged (buggy, hard to follow code). Legitimate use: abandon deeply nested processing, e.g. leave two or more loops at once, since
breakonly exits the innermost loop.
for (i = 1; i <= 5; ++i) {
for (j = 1; j <= 5; ++j) {
if (i == 3 && j == 3) goto endLoop;
printf("%d %d\n", i, j);
}
}
endLoop:
printf("Loop ended\n");Quote in the slide (Stroustrup): "The fact that 'goto' can do anything is exactly why we don't use it."
Symbolic constants
#define PI 3.14159265359
#define MAX_SCORE 100
double circumference = 2 * PI * radius;- Defined with the preprocessor (
#define NAME value, no;), conventionally in uppercase; the preprocessor replaces every occurrence (see Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →). - Advantages: readability, maintainability (change in one place), error prevention (no typos or accidental changes), consistency.
- Cannot be changed during execution, unlike variables. Enums are an alternative for related constants (Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →).
Loops
A loop executes a block 0, 1 or more times depending on a condition; one execution of the block is an iteration; a function with a loop is iterative.
- The block must contain something that eventually makes the condition false, otherwise there is an infinite loop (sometimes designed on purpose, often a logic error).
- If the condition is false on the first check, the block runs 0 times (while, for) or 1 time (do-while).
- Tracing an iterative function: add a column for the loop condition and a row per iteration with the values of the modified variables.
while (loop at initial condition)
Use it when the number of iterations is unknown and some input must not be processed even once.
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}The condition is tested; if true the body runs, then it is tested again; when false execution continues after the loop. The body is a block in braces or a single statement.
for (counter loop)
Use when the number of iterations is known before entering the loop.
for (i = 0; i < 5; i++) {
printf("%d ", i);
}for (statement1; cond2; statement3): statement1 runs once (initialization), cond2 is checked before every iteration, statement3 (update) runs after each iteration. All three are optional.- Idiom
for (i = ini; i < end; i++)loops for i from ini to end - 1; ifini < endit runsend - initimes, ifini >= endnever. - To run n times use
for (i = 0; i < n; i++): starting from 0 is better because of arrays. - Hints: meaningful names, correct initialization/condition/update, avoid hard-coded limits (use variables or constants), choose the loop that fits.
/* print Fahrenheit-Celsius table */
for (fahr = 0; fahr <= 100; fahr = fahr + 1)
printf("%3.0ff\t%6.4fc\n", fahr, (5.0/9.0)*(fahr-32));do-while (loop with final condition)
Use when the number of iterations is unknown and every input must be processed at least once.
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);Condition tested at the bottom, body always runs at least once; note the final ;. Used less often than while and for but valuable (e.g. showing a menu).
| Loop | Condition check | If false at start |
|---|---|---|
| for | before iteration | never executes |
| while | before iteration | never executes |
| do-while | after iteration | executes once |
break and continue
for (int i = 0; i < 10; i++) {
if (i == 5) break; // prints 0 1 2 3 4
printf("%d ", i);
}
for (int i = 0; i < 10; i++) {
if (i == 5) continue; // prints 0..9 skipping 5
printf("%d ", i);
}break exits the loop immediately; continue skips the rest of the current iteration and goes to the next.
C++ loops
Same for, while, do-while, break, continue (with std::cout << i << " "), plus the range-based for (C++11):
std::vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) { std::cout << num << " "; }
for (auto num : nums) { std::cout << num << " "; } // element type inferredWorked example: temperature table (variables, loops, printf)
Print Fahrenheit and Celsius for 0 to 100 F with celsius = 5 * (fahr-32) / 9. First version (integers, as in the slide, main() without int):
#include <stdio.h>
main()
{
int fahr, celsius;
int lower, upper;
lower = 0;
upper = 100;
fahr = lower;
while (fahr <= upper) {
celsius = 5 * (fahr-32) / 9;
printf("%df\t%dc\n", fahr, celsius);
fahr = fahr + 1;
}
}- Output
0f -17c,1f -17c, ... : integer arithmetic truncates, and 0 F is really about -17.8 C. - Not pretty: add a width to
%d:printf("%3d %6d\n", fahr, celsius)right-justifies in fields 3 and 6 wide. - Fix accuracy with
floatand%3.0f/%6.4f:
float celsius, fahr;
float lower, upper;
lower = 0; upper = 100; fahr = lower;
while (fahr <= upper) {
celsius = 5 * (fahr - 32) / 9;
printf("%3.0ff\t%6.4fc\n", fahr, celsius);
fahr = fahr + 1;
}Output: 0f -17.7778c, 1f -17.2222c, ..., 100f 37.7778c. Here fahr = lower and fahr <= upper work with the int constants converted to float.
printf conversions:
| Spec | Result |
|---|---|
%d |
decimal integer |
%4d |
decimal integer, at least 4 wide |
%f |
floating point |
%6f |
floating point, at least 6 wide |
%.4f |
4 digits after the decimal point |
%6.4f |
at least 6 wide, 4 after the point |
%o %x %c %s %% |
octal, hexadecimal, character, string, a literal percent |
printf("%.3f", 6.2789) prints 6.279 (rounded). Width and precision may be omitted.
Exercises with solutions in the slides:
/* heading above the table */
printf("Fahrenheit\tCelsius\n");
while (fahr <= upper) {
celsius = 5 * (fahr - 32) / 9;
printf("%3.0ff\t\t%6.4fc\n", fahr, celsius);
fahr = fahr + 1;
}
/* Celsius to Fahrenheit table, same structure */
fahr = ((celsius * 9) / 5) + 32;
printf("%3.0fc\t\t%6.4ff\n", celsius, fahr); // 0c 32.0000f, 1c 33.8000f, ...C++ version of the Celsius table uses <iomanip>: cout << fixed << setprecision(2); cout << setw(6) << celsius << "c: " << setw(6) << fahr << "f" << endl; with fahr = (celsius * 9.0 / 5.0) + 32; and celsius++.
Exercises given in the slides (no solution provided)
- for: print 50 down to 1; multiplication table of a user integer up to 10; even numbers 1-100.
- while: sum of first n naturals (n from user); count 50 down to 1; even numbers 100 down to 1.
- do-while: factorial of a user number; guess a random number from 1 to 50 with higher/lower hints.
- Currency conversion: for amounts 1..100 USD print EUR (1 USD = 0.91) and GBP (1 USD = 0.76), stopping when GBP exceeds 60; solve with
forand with one ofwhile/do-while; use#definefor the lower and upper values.
Versione ripasso
- Braces
{ }make blocks,;ends every statement, C is case sensitive. The condition is an expression: 0 is false, non-zero is true.
if (number > 0) printf("positive\n");
else if (number < 0) printf("negative\n");
else printf("zero\n");if / else if / else: conditions are checked top to bottom, the first match wins and the others are not evaluated. Put the most specific condition first;elseis the catch-all.- Leap year:
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0. switch (expr):casevalues are distinct integer constants. Execution starts at the match and runs untilbreak. Withoutbreakthere is fall-through.defaultruns when nothing matches and is optional. Group labels on purpose:case 'B': case 'C':. Putbreakalso after the last case.
switch (grade) {
case 'A': printf("Excellent!\n"); break;
case 'B':
case 'C': printf("Well done\n"); break; // B and C share one block
default: printf("Invalid grade\n");
}- Ternary:
z = (a > b) ? a : b;evaluates only one of the two branches. Use it for simple choices only, nesting hurts readability. goto label;/label: statement;: never needed. Its only sensible use is to leave two or more nested loops at once, sincebreakexits only the innermost one.#define PI 3.14159265359: a symbolic constant with no;, replaced by the preprocessor (Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →). Readable, one place to change, cannot change at run time.- Loops, by when the test happens:
for (i = 0; i < n; i++) { } // known count: runs n times, i from 0 to n-1
while (cond) { } // 0 or more times, test first
do { } while (cond); // at least once, test last, note the final ;breakexits the loop,continuejumps to the next iteration (in aforthe update still runs). Make sure the condition eventually becomes false, otherwise the loop is infinite.- C++ range-based for (C++11):
for (int num : nums) { ... }. - Temperature table: with
intthe division5 * (fahr - 32) / 9truncates, so 0 F prints as -17 C. Usefloatand5.0 / 9.0for exact values. - printf:
%3.0fmeans width 3 with no decimals,%6.4fwidth 6 with 4 decimals,%.3fof 6.2789 prints 6.279. - Loop check table:
forandwhiletest before each iteration, so a false start means zero runs;do-whiletests after the body, so it runs once. - Exercises from the slides (no solutions given):
forfor the multiplication table of a user number up to 10;whilefor the sum of the first n naturals;do-whilefor the factorial of a user number, or for a guessing game with a random number from 1 to 50. - Typical errors: missing
break(fall-through),=instead of==in a condition, off-by-one with<versus<=, forgotten update in awhile, integer division where a real result is needed, missing;afterdo { } while. - Related: Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions → (condition operators), Functions, Variables and ScopeHow to declare variables, define and call functions with prototypes and return values, pass arguments by value or through pointers, and use function pointers.Functions, Variables and Scope →.