Two Example Programs
hello.c
Compiling the program
gcc hello.c
Produces an executable called a.out for obscure historical reasons.
Better: gcc -o hello hello.c
Produces an executable called hello.
Best: make hello
Uses the make utility to compile the program producing an executable called hello.
Executing the program
./hello
Output
speed.c
Output
mph fps kph mps ppm ------ ------ ------ ------ ------ 0.00 0.00 0.00 0.00 0.00 10.00 14.67 6.11 4.55 12.67 20.00 29.33 12.22 9.09 25.34 30.00 44.00 18.33 13.64 38.02 40.00 58.67 24.44 18.19 50.69 50.00 73.33 30.55 22.74 63.36 60.00 88.00 36.65 27.28 76.03 70.00 102.67 42.76 31.83 88.71 80.00 117.33 48.87 36.38 101.38 90.00 132.00 54.98 40.92 114.05 100.00 146.67 61.09 45.47 126.72
Types in C
Actual sizes depend on the machine architecture and operating system. Integer types can be signed or unsigned.
char | 8 bit character |
short | 16 bit integer |
int | 32 bit integer |
long | 64 bit integer |
long long | 64 bit integer |
float | 32 bit floating point |
double | 64 bit floating point |
float double | 128 bit floating point |
char * | 64 bit pointer to string |
void * | 64 bit generic pointer |
Printf Formats
%d | decimal integer |
%5d | decimal integer, field width 5 |
%f | float or double |
%8.3f | float or double, field width 8, 3 decimal places |
%c | char |
%s | string |
Character Input
inout1.c
inout2.c
The correct way to read characters.
Counting Words
The state diagram describes the actions of the program.
wordcount.c
C Operators
Arithmetic Operators | + | Addition |
- | Subtraction, Negation | |
* | Multiplication | |
/ | Division | |
- | Modulus | |
Logical Operators | && | And |
|| | Or | |
! | Not | |
Bitwise Operators | & | And |
| | Or | |
^ | Exclusive Or | |
~ | Complement | |
Comparison Operators | < | Less Than |
<= | Less Than or Equal | |
== | Equal | |
!= | Not Equal | |
> | Greater Than | |
>= | Greater Than or Equal | |
Assignment Operators | = += -= *=
/= %= &= |= ^= <<= >>= | |
Miscellaneous Operators | * | Dereference |
& | Address | |
? : | Conditional | |
, | Sequence |
Control Structures
-
if (i < n) { ... } else { ... }
for (int i = 0; i < n; i++) { ... }
-
while (i < n) { ... }
-
do { ... } while (i < n)
-