The C Programming Language

Getting Started

1
// hello_world.c
2
#include <stdio.h>
3
4
int main(int argc, char *argv[])
5
{
6
printf("hello, world\n");
7
return 0;
8
}
Copied!

Variables and Arithmetic Expressions

1
// f_to_c.c
2
#include <stdio.h>
3
4
/* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300 */
5
int main(int argc, char *argv[])
6
{
7
float fahr = 0; /* Temperature in Fahrenheit */
8
float celsius = 0; /* Temperature in Celsius */
9
int lower = 0; /* Lower limit of temperature table */
10
int upper = 300; /* Upper limit of temperature table */
11
int step = 20; /* Step size */
12
13
fahr = lower;
14
while (fahr <= upper)
15
{
16
celsius = (5.0 / 9.0) * (fahr - 32.0);
17
printf("%3.0f\t%6.1f\n", fahr, celsius);
18
fahr += step;
19
}
20
21
return 0;
22
}
Copied!
Data Types:
  • char: 1 byte
  • short: 2 bytes
  • long: 4 bytes
  • double: 8 bytes
Format:
  • %d: print as decimal integer
  • %6d: print as decimal integer, at least 6 characters wide
  • %f: print as floating point
  • %6f: print as floating point, at least 6 characters wide
  • %.2f: print as floating point, 2 characters after decimal point
  • %6.2f: print as floating point, at least 6 wide and 2 after decimal point

For Statement

1
// f_to_c_for_loop.c
2
#include <stdio.h>
3
4
/* print Fahrenheit-Celsius table */
5
int main(int argc, char *argv[])
6
{
7
for (int fahr = 0; fahr <= 300; fahr += 20)
8
{
9
printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
10
}
11
12
return 0;
13
}
Copied!

Symbolic Constants

1
// f_to_c_constants.c
2
#include <stdio.h>
3
4
#define LOWER 0 /* Lower limit of table */
5
#define UPPER 300 /* Upper limit of table */
6
#define STEP 20 /* Step size */
7
8
/* print Fahrenheit-Celsius table */
9
int main(int argc, char *argv[])
10
{
11
for (int fahr = LOWER; fahr <= UPPER; fahr += STEP)
12
{
13
printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
14
}
15
16
return 0;
17
}
Copied!

Character Input and Output

File Copying

1
// file_copying.c
2
#include <stdio.h>
3
4
/* copy input to output */
5
int main(int argc, char *argv[])
6
{
7
int c = 0;
8
9
while ((c = getchar()) != EOF)
10
{
11
putchar(c);
12
}
13
14
return 0;
15
}
Copied!
Precedence:
The precedence of != is higher than that of =, so the following statements are equivalent
  • c = getchar() != EOF
  • c = (getchar() != EOF).
The semantic is very different from (c = getchar()) != EOF.

Character Counting

1
// character_counting.c
2
#include <stdio.h>
3
4
/* count characters in input */
5
int main(int argc, char *argv[])
6
{
7
double nc;
8
9
for (nc = 0; getchar() != EOF; ++nc)
10
{
11
;
12
}
13
printf("%.0f\n", nc);
14
15
return 0;
16
}
Copied!

Line Counting

1
// line_counting.c
2
#include <stdio.h>
3
4
/* count lines in input */
5
int main(int argc, char *argv[])
6
{
7
int c = 0; /* Input character */
8
int nl = 0; /* Number of lines */
9
10
while ((c = getchar()) != EOF)
11
{
12
if (c == '\n')
13
{
14
++nl;
15
}
16
}
17
printf("%d\n", nl);
18
19
return 0;
20
}
Copied!

Word Counting

1
// word_counting.c
2
#include <stdio.h>
3
4
#define IN 1 /* Inside a word */
5
#define OUT 0 /* OUtside a word */
6
7
/* count lines, words, and characters in input */
8
int main(int argc, char *argv[])
9
{
10
int c = 0; /* Input character */
11
int nl = 0; /* Number of lines */
12
int nw = 0; /* Number of words */
13
int nc = 0; /* Number of characters */
14
int state = 0; /* Inside or outside a word */
15
16
state = OUT;
17
while ((c = getchar()) != EOF)
18
{
19
++nc;
20
21
if (c == '\n')
22
{
23
++nl;
24
}
25
else if (c == ' ' || c == 'n' || c == 't')
26
{
27
state = OUT;
28
}
29
else if (state == OUT)
30
{
31
state = IN;
32
++nw;
33
}
34
}
35
36
printf("Number of lines: %d\n", nl);
37
printf("Number of words: %d\n", nw);
38
printf("Number of characters: %d\n", nc);
39
40
return 0;
41
}
Copied!

Arrays

1
// arrays.c
2
#include <stdio.h>
3
4
/* count digits, white space, others */
5
int main(int argc, char *argv[])
6
{
7
int c = 0;
8
int i = 0;
9
int nwhite = 0;
10
int nother = 0;
11
12
int ndigit[10] = {0};
13
14
while ((c = getchar()) != EOF)
15
{
16
if (c >= '0' && c <= '9')
17
{
18
++ndigit[c - '0'];
19
}
20
else if (c == ' ' || c == '\n' || c == '\t')
21
{
22
++nwhite;
23
}
24
else
25
{
26
++nother;
27
}
28
}
29
30
printf("digits =");
31
for (i = 0; i < 10; i++)
32
{
33
printf(" %d", ndigit[i]);
34
}
35
printf(", white space = %d, other = %d\n",
36
nwhite, nother);
37
}
Copied!

Functions

1
// power.c
2
#include <stdio.h>
3
4
// Function prototype
5
int power(int m, int n);
6
7
/* test power function */
8
int main(int argc, char *argv[])
9
{
10
for (int i = 0; i < 10; ++i)
11
{
12
printf("%d %d %d\n", i, power(2, i), power(-3, i));
13
}
14
15
return 0;
16
}
17
18
/* power: raise base to n-th power; n >= 0 */
19
int power(int base, int n)
20
{
21
int p = 1;
22
23
for (int i = 0; i <= n; ++i)
24
{
25
p *= base;
26
}
27
28
return p;
29
}
Copied!

Arguments-Call by Value

In C, all function arguments are passed "by value". This means that the called function is given the values of its arguments in temporary variables rather than the originals. This leads to some different properties than are seen with "call by reference" languages like Fortran or with var parameters in Pascal, in which the called routine has access to the original argument, not a local copy.

Character Arrays

In C, strings are represented by char arrays. Every char array is terminated by a null byte (\0). For example, a string constant like "hello\n" is stored in memory as in the following diagram:
char array
Below is a sample program that takes input and prints out the longest line:
1
// longest_line.c
2
#include <stdio.h>
3
4
#define MAXLINE 1000 /* Maximum input line size */
5
6
int get_line(char line[], int maxline);
7
void copy(char to[], char from[]);
8
9
/* print longest input line */
10
int main(int argc, char *argv[])
11
{
12
int len = 0; /* Current line length */
13
int max = 0; /* Maximum length seen so far */
14
char line[MAXLINE] = {0}; /* Current input file */
15
char longest[MAXLINE] = {0}; /* Longest line saved here */
16
17
while ((len = get_line(line, MAXLINE)) > 0)
18
{
19
if (len > max)
20
{
21
max = len;
22
copy(longest, line);
23
}
24
}
25
26
if (max > 0)
27
{
28
printf("%s", longest);
29
}
30
31
return 0;
32
}
33
34
/* get_line: read a line into `s`, return `length` */
35
int get_line(char s[], int lim)
36
{
37
int c = 0;
38
int i = 0;
39
40
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
41
{
42
s[i] = c;
43
}
44
45
if (c == '\n')
46
{
47
s[i] = c;
48
++i;
49
}
50
51
s[i] = '\0';
52
53
return i;
54
}
55
56
/* copy: copy `from` into `to`; assume `to` is big enough */
57
void copy(char to[], char from[])
58
{
59
int i = 0;
60
61
while ((to[i] = from[i]) != '\0')
62
{
63
++i;
64
}
65
}
Copied!

External Variables and Scope

In C, local variables are called "automatic variables". If you wish local variables retain their values between calls, use the static keyword.
In C, global variables are called "external varaibles". An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.
Below is an updated version of longest_line.c which shows the usage of external variables:
1
// longest_line_extern.c
2
#include <stdio.h>
3
4
#define MAXLINE 1000 /* Maximum input line size */
5
6
int max = 0; /* Maximum length seen so far */
7
char line[MAXLINE] = {0}; /* Current input file */
8
char longest[MAXLINE] = {0}; /* Longest line saved here */
9
10
int get_line(void);
11
void copy(void);
12
13
/* print longest input line; specialized version */
14
int main(int argc, char *argv[])
15
{
16
int len = 0; /* Current line length */
17
extern int max;
18
extern char longest[];
19
20
while ((len = get_line()) > 0)
21
{
22
if (len > max)
23
{
24
max = len;
25
copy();
26
}
27
}
28
29
if (max > 0)
30
{
31
printf("%s", longest);
32
}
33
34
return 0;
35
}
36
37
/* get_line: specialized version */
38
int get_line(void)
39
{
40
int c = 0;
41
int i = 0;
42
extern char line[];
43
44
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
45
{
46
line[i] = c;
47
}
48
49
if (c == '\n')
50
{
51
line[i] = c;
52
++i;
53
}
54
55
line[i] = '\0';
56
57
return i;
58
}
59
60
/* copy: specialized version */
61
void copy(void)
62
{
63
int i = 0;
64
extern char line[];
65
66
while ((longest[i] = line[i]) != '\0')
67
{
68
++i;
69
}
70
}
Copied!

Reference

https://kremlin.cc/k&r.pdf
K&R