Salta al contenuto
Note per Studenti Control Structures Report

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: myVariable and myvariable are 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

c
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 if are not evaluated. Make the first condition the most specific; else is the catch-all.
c
#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), Invalid outside; 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 →.

c
#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.

c
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 break there is fall-through: all following cases run whether they match or not. Not robust, avoid it (except to group labels, as case 'B': case 'C': below).
  • default runs if nothing matches; it is optional (without it, no action takes place). Cases and default may appear in any order.
  • Good form: put break also after the last case, so adding a case later does not break correctness.
c
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 range Invalid.

Ternary operator ?:

c
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 to if (a > b) z = a; else z = b;.
c
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) without if; int sgn(int x) (1, 0, -1, no if); predict x and y after int y = 1; int x = y ? (y = 0) : 2;.

goto and labels

c
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 break only exits the innermost loop.
c
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

c
#define PI 3.14159265359
#define MAX_SCORE 100
double circumference = 2 * PI * radius;

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.

c
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.

c
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; if ini < end it runs end - ini times, if ini >= end never.
  • 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.
c
/* 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.

c
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

c
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):

cpp
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 inferred

Worked 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):

c
#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 float and %3.0f / %6.4f:
c
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:

c
/* 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 for and with one of while / do-while; use #define for 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.
c
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; else is the catch-all.
  • Leap year: (year % 4 == 0 && year % 100 != 0) || year % 400 == 0.
  • switch (expr): case values are distinct integer constants. Execution starts at the match and runs until break. Without break there is fall-through. default runs when nothing matches and is optional. Group labels on purpose: case 'B': case 'C':. Put break also after the last case.
c
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");
}
c
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 ;

Teoria collegata