Introduction to C Programming

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

Hello, world!

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.

char8 bit character
short16 bit integer
int32 bit integer
long64 bit integer
long long64 bit integer
float32 bit floating point
double64 bit floating point
float double128 bit floating point
char *64 bit pointer to string
void *64 bit generic pointer

Printf Formats

%ddecimal integer
%5ddecimal integer, field width 5
%ffloat or double
%8.3ffloat or double, field width 8, 3 decimal places
%cchar
%sstring

Character Input

inout1.c

inout2.c

The correct way to read characters.

Counting Words

The state diagram describes the actions of the program.

Not In Word In Word Start Whitespace Non-Whitespace Whitespace Non-Whitespace

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