Aims and Objectives
More about if
switch
Conditional Expressions
More Loops
break and continue
if-else
if (expression) statement1 else statement2 /* where the else is optional */
if (n >= 0) for (i = 0; i < n; i++) if (s[i] > 0) { printf("..."); return i; } else printf("error -- n is negative\n");
if (expression) statement else if (expression) statement else if (expression) statement else if (expression) statement else statement
//Function name: binsearch int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low + high) / 2; if (x < v[mid]) { high = mid - 1; } else if ( x > v[mid]) { low = mid + 1; } else /* found match */ return mid; } return -1; /* no match */ }
switch (expression) { case const-expr: statements case const-expr: statements case const-expr: statements default: statements }
#include <stdio.h> //Program name: count.c /* Program to count digits, white space, others */main() { int c, i, nwhite, nother, ndigits[10]; nwhite = nother = 0; for (i = 0; i < 10; ndigits[i++] = 0) ; while ((c = getchar()) != EOF) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigits[c - '0']++; break; case ' ': case '\n': case '\t': nwhite++; break; default: nother++; break; } } printf("digits = "); for (i = 0; i < 10; i++) printf(" %d", ndigits[i]); printf(", white space = %d, other = %d\n", nwhite, nother); }
/* find the larger of a and b */ if (a < b) max = b; else max = a;
var = expr1 ? expr2 : expr3 z = (a < b) ? b : a; printf("You have %d item%s\n", i, (i==1) ? "" : "s");
#include <ctype.h> int atoi(char s[]) { int i, n, sign; /* skip leading white space */ for (i = 0; isspace(s[i]); i++) ; sign = (s[i] == '-') ? -1 : 1; /* skip sign */ if (s[i] == '-' || s[i] == '+') i++; for (n = 0; isdigit(s[i]); i++) n = 10 * n + (s[i] - '0'); return sign * n; }
The atoi function is in the stdlib library.
do-while
do statement while (condition) ;
#include <string.h> #include <ctype.h> . . . /* remove trailing blanks from a string */ int trim(char s[]) { int i; for (i = strlen(s) - 1; i >= 0; i--) if (! isspace(s[i])) break; s[i+1] = '\0'; return i; }
for (i = 0; i < n; i++) if (a[i] < 0) continue; /* if a[i] is positive, do this */