Professional Documents
Culture Documents
false true
a<b
if (j < k) {
min = j;
max = k;
}
switch (x) {
case 1: x = x + 1;
case 2: x = x + 2;
break; /* exit switch */
case 3: x = x + 3;
default: x = 0;
}
// break jumps to here
x = x + 2;
• Now consider the default case. This does not need a break
because it is placed as the final statement
switch (x) {
case 1: x = x + 1;
/* fall through */
case 2: x = x + 2;
break; // exit switch
case 3: x = x + 3;
/* fall through */
default: x = 0;
}
if (operator == ‘+’)
result = a + b;
else if (operator == ‘-’)
result = a - b;
else if (operator == ‘*’)
result = a * b;
else if (operator == ‘/’) {
if ( b == 0)
printf(“error – division by 0\n”);
else result = a / b;
}
else printf(“unknown operator\n”);
switch (operator ) {
case ‘+’: result = a + b;
break;
case ‘-’: result = a - b;
break;
case ‘*’: result = a * b;
break;
case ‘/’: if ( b == 0)
printf(“error – division by 0\n”);
else result = a / b;
break;
default: printf(“unknown operator\n”);
}
false
true
for (loop2_exprs) {
loop_body_2
}
loop_body_1b
}
February 2006 Basis-C-2/LL 46
Nested for loops 3
• Most compilers allow 15 nesting levels –
DON’T DO IT!!
int i = 1, sum = 0;
while (i <= 10)
{
sum = sum + i;
i= i + 1;
}
printf(“Sum = %d\n”, sum);
February 2006 Basis-C-2/LL 51
for and while
for(expr1; expr2; expr3)
statement
Is equivalent to
expr1;
while(expr2){
statement;
expr3;
}
while (expression)
{
statements
continue;
more_statements
}
do
statement
while (expression);
-- Blair P. Houghton
(On the subject of C program indentation)
-- Bjarne Stroustrup