Lecture #13: Statements 4

November 1, 1999

Bob Pitha

bpitha@cs.ucsd.edu

http://www-cse.ucsd.edu/classes/fa99/cse5a

review

•      We’ve talked about:

–   expression statements

•   any valid expression with a semicolon stuck on the end

–   compound statements

•   one or more statements (and optional declarations) surrounded by braces

–   selection statements

•  if-else

•  switch

–   iteration statements

•  while

•  for

one more iteration statement: do-while

do statement while ( expression );

•      A lot like the while statement

–   except the expression is tested after statement, not before

–   the difference is that statement is always executed at least once, even if expression is never true

•   with the while statement, the body would not be executed even once in that case

do-while example

Text Box: do {
    printf (“Input a positive integer: “);
    scanf (“%d”, &n);
    if (error = (n <= 0))
        printf (“\nERROR: Try again!\n”);
} while (error);
 


jump statements: break and continue

 

break

•    break exits a loop or a switch statement immediately

–   but only from the innermost loop if it’s a nested loop

•      This example code repeatedly reads a number from the keyboard and prints its square root. If the number is negative, it stops.

Text Box: while (1) {
    scanf (“lf”, &x);
    if (x < 0.0)
        break;
    printf (”%f\n”, sqrt(x));
}
 


break example

Text Box: #include <stdio.h>
#include <math.h>

int main (void)
{
    int i, j;

    printf (“%d\n”, 2);
    for (i = 3; i <= 100; ++i) {
        for (j = 2; j < i; ++j) {
            if (i % j == 0)
                break;
            if (j > sqrt(i)) {
                printf (%d\n”, i);
                break;
            }
        }
    }
    return 0;
}
 


continue

•    continue ends the current iteration of a loop

–   the control expression is evauated

–   depending on the value, the next iteration starts

•      Unlike break, continue doesn’t end the loop, it just skips to the end of the current cycle

–   it’s not used a whole lot, but sometimes it comes in handy

goto

•      There’s another jump statement, called goto

–   it is almost universally deplored, and rarely necessary

–   we will not use it in this class