Read: switch §3.4 of the C Programming Language, pp 52-3

break, continue, switch

We have alread studied several control constructs:

while (...)
if (...)
for(...)
There are a few others to talk about.

  1. break. The keyword break breaks execution out of the enclosing loop or switch. Execution continues with the statement after the loop or switch. Below we have code that should be put inside of function main.
    int secret = 849;
    int num;
    while (1==scanf("%d", &num) ) {
      if (num==secret) {
        printf("You guessed the secret.\n");
        break;
      }
      printf("Guess again. Enter another number.\n");
    }
    printf("Done.\n");
    
  2. continue. Keyword continue ends the current repetition and execution re-starts at the top of the loop. In this case scanf tries to get another integer. This code counts the number of numbers that are less than 100.
    int count=0;
    int num;
    while (1==scanf("%d", &num) ) {
      if (num>=100)
        continue;
      count++;
    }
    printf("%d\n", count);
    
  3. switch. The code below uses the switch statement to count vowels and non-vowels (this includes consonants, spaces, newlines, punctuation). Please read the description of switch in the "C Programming Language" mentioned at the top of this page.
    char str[100];
    fgets(str, 100, stdin);
    int vCount = 0, nonVCount=0;
    int i=0;
    while (str[i]) {
      switch (str[i]) {
        case 'a': case 'e': case 'i':
        case 'o': case 'u': case 'y':
        case 'A': case 'E': case 'I':
        case 'O': case 'U': case 'Y':
          vCount++;
          break;
        default:
          nonVCount++;
          break;
      }
      i++;
    }
    printf("Number of vowels %d number of non-vowels %d\n", vCount, nonVCount);
    

next: Problems 04