Chapter 4. Flow
of control
Home
procedence
and associativity of operators
|
Operators |
Associativity |
|
+(unary) -(unary)
++ -- !
* / %
+ -
<
<= > >=
==
!=
&&
||
= += -= *= /= etc |
right to left
left to right
left to right
left to right
left to right
left to right
left to right
right to left |
กก
|
/* Count blanks, digits, letters, newlines, and others. */
#include <stdio.h>
int main(void)
{
int blank_cnt = 0, c, digit_cnt = 0,
letter_cnt = 0, nl_cnt = 0, other_cnt = 0;
while ((c = getchar()) != EOF) /* braces not necessary */
if (c == ' ')
++blank_cnt;
else if (c >= '0' && c <= '9')
++digit_cnt;
else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
++letter_cnt;
else if (c == '\n')
++nl_cnt;
else
++other_cnt;
printf("%10s%10s%10s%10s%10s%10s\n\n",
"blanks", "digits", "letters", "lines", "others", "total");
printf("%10d%10d%10d%10d%10d%10d\n\n",
blank_cnt, digit_cnt, letter_cnt, nl_cnt, other_cnt,
blank_cnt + digit_cnt + letter_cnt + nl_cnt + other_cnt);
return 0;
}
|
กก
|
/* Print a table of values for some boolean functions. */
#include <stdio.h>
int main(void)
{
int b1, b2, b3, b4, b5; /* boolean variables */
int cnt = 0;
printf("\n%5s%5s%5s%5s%5s%5s%7s%7s%11s\n\n", /* headings */
"Cnt", "b1", "b2", "b3", "b4", "b5",
"fct1", "fct2", "majority");
for (b1 = 0; b1 <= 1; ++b1)
for (b2 = 0; b2 <= 1; ++b2)
for (b3 = 0; b3 <= 1; ++b3)
for (b4 = 0; b4 <= 1; ++b4)
for (b5 = 0; b5 <= 1; ++b5)
printf("%5d%5d%5d%5d%5d%5d%6d%7d%9d\n",
++cnt, b1, b2, b3, b4, b5,
b1 || b3 || b5, b1 && b2 || b4 && b5,
b1 + b2 + b3 + b4 + b5 >= 3);
putchar('\n');
return 0;
}
|
|
/* A test that fails. */
#include <stdio.h>
int main(void)
{
int cnt = 0;
double sum = 0.0, x;
for (x = 0.0; x != 9.9; x += 0.1) { /* trouble! */
sum += x;
printf("cnt = %5d\n", ++cnt);
}
printf("sum = %f\n", sum);
return 0;
}
|
|
/* Print Fibonacci numbers and quotients. */
#include <stdio.h>
#define LIMIT 46
int main(void)
{
long f0 = 0, f1 = 1, n, temp;
printf("%7s%19s%29s\n%7s%19s%29s\n%7s%19s%29s\n", /* headings */
" ", "Fibonacci", "Fibonacci",
" n", " number", " quotient",
"--", "---------", "---------");
printf("%7d%19d\n%7d%19d\n", 0, 0, 1, 1); /* first two cases */
for (n = 2; n <= LIMIT; ++n) {
temp = f1;
f1 += f0;
f0 = temp;
printf("%7ld%19ld%29.16f\n", n, f1, (double) f1 / f0);
}
return 0;
}
|
กก
[Last Update: 2001.3.28] Dongseo University Cyber Campus
|