2. Control Conditions
|
|
Unlike C++ or Java, no boolean type (in C89/C90) |
– in C99, bool type available (use stdbool.h)
– bool which expands to _Bool
– true which expands to 1
– false which expands to 0
– e.g. bool keep_going = true; |
Condition is an expression (or series of expressions) |
– e.g. n<3 or x<y || z<y |
Expression is non-zero condition true⇒ condition true |
Expression must be numeric (or a pointer) |
const char str[ ] = "some text" ;
if (str) / ∗ string is not null ∗ /
return 0; |
|
|
2.1 The if Statement |
|
2.1.1 The if-else statement |
|
The if-else statement is used to express decisions.
|
|
|
// find x in list[0] <= list[1] <= ... <= list[n-1]
int binsearch(int list[], int x, int n)
{
int min, max, mid;
min = 0;
max = n - 1;
while (min <= max) {
mid = (min+max)/2;
if (x < list[mid]) max = mid - 1;
else if (x > list[mid]) min = mid + 1;
else return mid; /* found match */
}
return -1; /* not found */
} |
|
|
2.1.2 Nesting if Statement |
|
To associate else with outer if statement: use braces |
|
|
|
2.2 The switch statement |
|
The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. |
– Alternative conditional statement
– Integer (or character) variable as input
– Considers cases for value of variable |
|
The syntax of the switch statement is |
|
|
#include <stdio.h> |
int main() /* count digits, white space, others */
{ |
int c, i, nwhite, nother, ndigit[10]; |
|
nwhite = nother = 0;
for (i=0; i<10; i++) |
ndigit[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’: |
ndigit[c-’0’]++;
break; |
case ‘ ’:
case ‘\n’:
case ‘\t’: |
nwhite++;
break; |
default: |
nother++;
break; |
} |
} |
for (i=0; i<10; i++)
printf(“digit %i = %d\n”, i, ndigits[i]);
printf(“white space = %d, other =%d\n”, nwhite, nother); |
|
return 0; |
} |
|
|