This is not the document you are looking for? Use the search form below to find more!

Report home > Computer / Internet

Programming in C A Tutorial

2.00 (9 votes)
Document Description
This memorandum is a tutorial to make learning C as painless as possible. The first part concentrates on the central features of C; the second part discusses those parts of the language which are useful (usually for getting more efficient and smaller code) but which are not necessary for the new user. This is not a ref- erence manual. Details and special cases will be skipped ruthlessly, and no attempt will be made to cover every language feature. The order of presentation is hopefully pedagogical instead of logical. Users who would like the full story should consult the C Reference Manual by D. M. Ritchie [1], which should be read for details anyway. Runtime support is described in [2] and [3]; you will have to read one of these to learn how to compile and run a C program.
File Details
Submitter
  • Username: desantis
  • Name: desantis
  • Documents: 37
Embed Code:

Add New Comment




Related Documents

Functional Programming in C++

by: dutcher, 12 pages

This paper describes FC++: a rich library supporting functional programming in C++. Prior approaches to encoding higher order functions in C++ have suffered with respect to polymorphic functions from ...

Setting up a blog in Edublogs (A tutorial)

by: song, 25 pages

Setting up a blog in Edublogs (A tutorial)

Asynchronous Socket Programming In C#

by: mine, 13 pages

Asynchronous Socket Programming In C#

Interior Design Trends in India - A Preview

by: lian, 13 pages

Interior Design Trends in India - A Preview

An Easy Timer In C Language

by: alfredina, 2 pages

An Easy Timer In C Language

network programming in c#

by: Sarfraz Alam Khan, 879 pages

language C#

Summer Training in C++

by: duccsystems, 7 pages

DUCC Systems invites all to C++ training in June and july.

Introduction to Computing and Programming with Java: A Multimedia Approach, Mark J. Guzdial, Barbara Ericson, PRENTICE HALL, IM+JavaClass+SM+PPT

by: mysmandtb, 9 pages

Solution Manuals and Test Banks I have huge collection of solution manuals and test banks. I strive to provide you unbeatable prices with excellent support. So, I assure you that you won’t be ...

UPTU MCA 1SEM CONCEPT PROGRAMMIN IN C 2010-2011

by: ASHISH, 4 pages

OLD PAPER 2010-2011

Costs Incurred in Running a Zoo

by: altairlahad, 1 pages

Zoos are structures used to house animals. Since their establishment, they have been used for recreation, scientific research and education. Although zoos are of varying sizes, operational costs are ...

Content Preview
Programming in C ? A Tutorial
Brian W. Kernighan
Bell Laboratories, Murray Hill, N. J.
1. Introduction
C is a computer language available on the GCOS and UNIX operating systems at Murray Hill and (in
preliminary form) on OS/360 at Holmdel. C lets you write your programs clearly and simply _ it has de-
cent control flow facilities so your code can be read straight down the page, without labels or GOTO’s; it
lets you write code that is compact without being too cryptic; it encourages modularity and good program
organization; and it provides good data-structuring facilities.
This memorandum is a tutorial to make learning C as painless as possible. The first part concentrates
on the central features of C; the second part discusses those parts of the language which are useful (usually
for getting more efficient and smaller code) but which are not necessary for the new user. This is not a ref-
erence manual. Details and special cases will be skipped ruthlessly, and no attempt will be made to cover
every language feature. The order of presentation is hopefully pedagogical instead of logical. Users who
would like the full story should consult the C Reference Manual by D. M. Ritchie [1], which should be read
for details anyway. Runtime support is described in [2] and [3]; you will have to read one of these to learn
how to compile and run a C program.
We will assume that you are familiar with the mysteries of creating files, text editing, and the like in
the operating system you run on, and that you have programmed in some language before.
2. A Simple C Program
main( ) {
printf("hello, world");
}
A C program consists of one or more functions, which are similar to the functions and subroutines of
a Fortran program or the procedures of PL/I, and perhaps some external data definitions. main is such a
function, and in fact all C programs must have a main. Execution of the program begins at the first state-
ment of main. main will usually invoke other functions to perform its job, some coming from the same
program, and others from libraries.
One method of communicating data between functions is by arguments. The parentheses following
the function name surround the argument list; here main is a function of no arguments, indicated by ( ).
The {} enclose the statements of the function. Individual statements end with a semicolon but are other-
wise free-format.
printf is a library function which will format and print output on the terminal (unless some other des-
tination is specified). In this case it prints

C Tutorial
- 2 -
hello, world
A function is invoked by naming it, followed by a list of arguments in parentheses. There is no CALL state-
ment as in Fortran or PL/I.
3. A Working C Program; Variables; Types and Type Declarations
Here’s a bigger program that adds three integers and prints their sum.
main( ) {
int a, b, c, sum;
a = 1; b = 2; c = 3;
sum = a + b + c;
printf("sum is %d", sum);
}
Arithmetic and the assignment statements are much the same as in Fortran (except for the semi-
colons) or PL/I. The format of C programs is quite free. We can put several statements on a line if we want,
or we can split a statement among several lines if it seems desirable. The split may be between any of the
operators or variables, but not in the middle of a name or operator. As a matter of style, spaces, tabs, and
newlines should be used freely to enhance readability.
C has four fundamental types of variables:
int
integer (PDP-11: 16 bits; H6070: 36 bits; IBM360: 32 bits)
char
one byte character (PDP-11, IBM360: 8 bits; H6070: 9 bits)
float
single-precision floating point
double double-precision floating point
There are also arrays and structures of these basic types, pointers to them and functions that return them,
all of which we will meet shortly.
All variables in a C program must be declared, although this can sometimes be done implicitly by
context. Declarations must precede executable statements. The declaration
int a, b, c, sum;
declares a, b, c, and sum to be integers.
Variable names have one to eight characters, chosen from A-Z, a-z, 0-9, and _, and start with a non-
digit. Stylistically, it’s much better to use only a single case and give functions and external variables
names that are unique in the first six characters. (Function and external variable names are used by various
assemblers, some of which are limited in the size and case of identifiers they can handle.) Furthermore,
keywords and library functions may only be recognized in one case.
4. Constants
We have already seen decimal integer constants in the previous example _ 1, 2, and 3. Since C is of-
ten used for system programming and bit-manipulation, octal numbers are an important part of the lan-
guage. In C, any number that begins with 0 (zero!) is an octal integer (and hence can’t have any 8’s or 9’s
in it). Thus 0777 is an octal constant, with decimal value 511.
A ‘‘character’’ is one byte (an inherently machine-dependent concept). Most often this is expressed
as a character constant, which is one character enclosed in single quotes. However, it may be any quantity
that fits in a byte, as in flags below:
char quest, newline, flags;
quest = ???;
newline = ?\n?;
flags = 077;

C Tutorial
- 3 -
The sequence ‘\n’ is C notation for ‘‘newline character’’, which, when printed, skips the terminal to
the beginning of the next line. Notice that ‘\n’ represents only a single character. There are several other
‘‘escapes’’ like ‘\n’ for representing hard-to-get or invisible characters, such as ‘\t’ for tab, ‘\b’ for back-
space, ‘\0’ for end of file, and ‘\\’ for the backslash itself.
float and double constants are discussed in section 26.
5. Simple I/O _ getchar, putchar, printf
main( ) {
char c;
c = getchar( );
putchar(c);
}
getchar and putchar are the basic I/O library functions in C. getchar fetches one character from
the standard input (usually the terminal) each time it is called, and returns that character as the value of the
function. When it reaches the end of whatever file it is reading, thereafter it returns the character repre-
sented by ‘\0’ (ascii NUL, which has value zero). We will see how to use this very shortly.
putchar puts one character out on the standard output (usually the terminal) each time it is called. So
the program above reads one character and writes it back out. By itself, this isn’t very interesting, but ob-
serve that if we put a loop around this, and add a test for end of file, we have a complete program for copy-
ing one file to another.
printf is a more complicated function for producing formatted output. We will talk about only the
simplest use of it. Basically, printf uses its first argument as formatting information, and any successive ar-
guments as variables to be output. Thus
printf ("hello, world\n");
is the simplest use _ the string ‘‘hello, world\n’’ is printed out. No formatting information, no variables, so
the string is dumped out verbatim. The newline is necessary to put this out on a line by itself. (The con-
struction
"hello, world\n"
is really an array of chars. More about this shortly.)
More complicated, if sum is 6,
printf ("sum is %d\n", sum);
prints
sum is 6
Within the first argument of printf, the characters ‘‘%d’’ signify that the next argument in the argument list
is to be printed as a base 10 number.
Other useful formatting commands are ‘‘%c’’ to print out a single character, ‘‘%s’’ to print out an en-
tire string, and ‘‘%o’’ to print a number as octal instead of decimal (no leading zero). For example,
n = 511;
printf ("What is the value of %d in octal?", n);
printf (" %s! %d decimal is %o octal\n", "Right", n, n);
prints
What is the value of 511 in octal? Right! 511 decimal is 777 octal
Notice that there is no newline at the end of the first output line. Successive calls to printf (and/or putchar,
for that matter) simply put out characters. No newlines are printed unless you ask for them. Similarly, on
input, characters are read one at a time as you ask for them. Each line is generally terminated by a newline
(\n), but there is otherwise no concept of record.

C Tutorial
- 4 -
6. If; relational operators; compound statements
The basic conditional-testing statement in C is the if statement:
c = getchar( );
if( c == ??? )
printf("why did you type a question mark?\n");
The simplest form of if is
if (expression) statement
The condition to be tested is any expression enclosed in parentheses. It is followed by a statement.
The expression is evaluated, and if its value is non-zero, the statement is executed. There’s an optional
else clause, to be described soon.
The character sequence ‘==’ is one of the relational operators in C; here is the complete set:
==
equal to (.EQ. to Fortraners)
!=
not equal to
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
The value of ‘‘expression relation expression’’ is 1 if the relation is true, and 0 if false. Don’t for-
get that the equality test is ‘==’; a single ‘=’ causes an assignment, not a test, and invariably leads to disas-
ter.
Tests can be combined with the operators ‘&&’ (AND), ‘| |’ (OR), and ‘!’ (NOT). For example, we can test
whether a character is blank or tab or newline with
if( c==? ? | | c==?\t? | | c==?\n? ) ...
C guarantees that ‘&&’ and ‘| |’ are evaluated left to right _ we shall soon see cases where this matters.
One of the nice things about C is that the statement part of an if can be made arbitrarily complicated
by enclosing a set of statements in {}. As a simple example, suppose we want to ensure that a is bigger
than b, as part of a sort routine. The interchange of a and b takes three statements in C, grouped together
by {}:
if (a < b) {
t = a;
a = b;
b = t;
}
As a general rule in C, anywhere you can use a simple statement, you can use any compound state-
ment, which is just a number of simple or compound ones enclosed in {}. There is no semicolon after the }
of a compound statement, but there is a semicolon after the last non-compound statement inside the {}.
The ability to replace single statements by complex ones at will is one feature that makes C much
more pleasant to use than Fortran. Logic (like the exchange in the previous example) which would require
several GOTO’s and labels in Fortran can and should be done in C without any, using compound state-
ments.
7. While Statement; Assignment within an Expression; Null Statement
The basic looping mechanism in C is the while statement. Here’s a program that copies its input to
its output a character at a time. Remember that ‘\0’ marks the end of file.
main( ) {
char c;
while( (c=getchar( )) != ?\0? )

C Tutorial
? 5 ?
putchar(c);
}
The while statement is a loop, whose general form is
while (expression) statement
Its meaning is
(a) evaluate the expression
(b) if its value is true (i.e., not zero)
do the statement, and go back to (a)
Because the expression is tested before the statement is executed, the statement part can be executed zero
times, which is often desirable. As in the if statement, the expression and the statement can both be arbi-
trarily complicated, although we haven’t seen that yet. Our example gets the character, assigns it to c, and
then tests if it’s a ‘\0’’. If it is not a ‘\0’, the statement part of the while is executed, printing the character.
The while then repeats. When the input character is finally a ‘\0’, the while terminates, and so does main.
Notice that we used an assignment statement
c = getchar( )
within an expression. This is a handy notational shortcut which often produces clearer code. (In fact it is
often the only way to write the code cleanly. As an exercise, re-write the file-copy without using an assign-
ment inside an expression.) It works because an assignment statement has a value, just as any other expres-
sion does. Its value is the value of the right hand side. This also implies that we can use multiple assign-
ments like
x = y = z = 0;
Evaluation goes from right to left.
By the way, the extra parentheses in the assignment statement within the conditional were really nec-
essary: if we had said
c = getchar( ) != ?\0?
c would be set to 0 or 1 depending on whether the character fetched was an end of file or not. This is be-
cause in the absence of parentheses the assignment operator ‘=’ is evaluated after the relational operator
‘!=’. When in doubt, or even if not, parenthesize.
Since putchar(c) returns c as its function value, we could also copy the input to the output by nest-
ing the calls to getchar and putchar:
main( ) {
while( putchar(getchar( )) != ?\0? ) ;
}
What statement is being repeated? None, or technically, the null statement, because all the work is really
done within the test part of the while. This version is slightly different from the previous one, because the
final ‘\0’ is copied to the output before we decide to stop.
8. Arithmetic
The arithmetic operators are the usual ‘+’, ‘?’, ‘*’, and ‘/’ (truncating integer division if the operands
are both int), and the remainder or mod operator ‘%’:
x = a%b;
sets x to the remainder after a is divided by b (i.e., a mod b). The results are machine dependent unless a
and b are both positive.
In arithmetic, char variables can usually be treated like int variables. Arithmetic on characters is
quite legal, and often makes sense:
c = c + ?A? ? ?a?;

C Tutorial
? 6 ?
converts a single lower case ascii character stored in c to upper case, making use of the fact that corre-
sponding ascii letters are a fixed distance apart. The rule governing this arithmetic is that all chars are con-
verted to int before the arithmetic is done. Beware that conversion may involve sign-extension _ if the left-
most bit of a character is 1, the resulting integer might be negative. (This doesn’t happen with genuine
characters on any current machine.)
So to convert a file into lower case:
main( ) {
char c;
while( (c=getchar( )) != ?\0? )
if( ?A?<=c && c<=?Z? )
putchar(c+?a???A?);
else
putchar(c);
}
Characters have different sizes on different machines. Further, this code won’t work on an IBM machine,
because the letters in the ebcdic alphabet are not contiguous.
9. Else Clause; Conditional Expressions
We just used an else after an if. The most general form of if is
if (expression) statement1 else statement2
the else part is optional, but often useful. The canonical example sets x to the minimum of a and b:
if (a < b)
x = a;
else
x = b;
Observe that there’s a semicolon after x=a.
C provides an alternate form of conditional which is often more concise. It is called the ‘‘conditional
expression’’ because it is a conditional which actually has a value and can be used anywhere an expression
can. The value of
a<b ? a : b;
is a if a is less than b; it is b otherwise. In general, the form
expr1 ? expr2 : expr3
means ‘‘evaluate expr1. If it is not zero, the value of the whole thing is expr2; otherwise the value is
expr3.’’
To set x to the minimum of a and b, then:
x = (a<b ? a : b);
The parentheses aren’t necessary because ‘?:’ is evaluated before ‘=’, but safety first.
Going a step further, we could write the loop in the lower-case program as
while( (c=getchar( )) != ?\0? )
putchar( (?A?<=c && c<=?Z?) ? c??A?+?a? : c );
If’s and else’s can be used to construct logic that branches one of several ways and then rejoins, a
common programming structure, in this way:
if(...)
{...}
else if(...)
{...}

C Tutorial
? 7 ?
else if(...)
{...}
else
{...}
The conditions are tested in order, and exactly one block is executed _ either the first one whose if is satis-
fied, or the one for the last else. When this block is finished, the next statement executed is the one after
the last else. If no action is to be taken for the ‘‘default’’ case, omit the last else.
For example, to count letters, digits and others in a file, we could write
main( ) {
int let, dig, other, c;
let = dig = other = 0;
while( (c=getchar( )) != ?\0? )
if( (?A?<=c && c<=?Z?) | | (?a?<=c && c<=?z?) ) ++let;
else if( ?0?<=c && c<=?9? ) ++dig;
else ++other;
printf("%d letters, %d digits, %d others\n", let, dig, other);
}
The ‘++’ operator means ‘‘increment by 1’’; we will get to it in the next section.
10. Increment and Decrement Operators
In addition to the usual ‘?’, C also has two other interesting unary operators, ‘++’ (increment) and
‘??’ (decrement). Suppose we want to count the lines in a file.
main( ) {
int c,n;
n = 0;
while( (c=getchar( )) != ?\0? )
if( c == ?\n? )
++n;
printf("%d lines\n", n);
}
++n is equivalent to n=n+1 but clearer, particularly when n is a complicated expression. ‘++’ and ‘??’ can
be applied only to int’s and char’s (and pointers which we haven’t got to yet).
The unusual feature of ‘++’ and ‘??’ is that they can be used either before or after a variable. The
value of ++k is the value of k after it has been incremented. The value of k++ is k before it is incremented.
Suppose k is 5. Then
x = ++k;
increments k to 6 and then sets x to the resulting value, i.e., to 6. But
x = k++;
first sets x to to 5, and then increments k to 6. The incrementing effect of ++k and k++ is the same, but
their values are respectively 5 and 6. We shall soon see examples where both of these uses are important.
11. Arrays
In C, as in Fortran or PL/I, it is possible to make arrays whose elements are basic types. Thus we can
make an array of 10 integers with the declaration
int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes
begin at zero, so the elements of x are
x[0], x[1], x[2], ..., x[9]

C Tutorial
? 8 ?
If an array has n elements, the largest subscript is n?1.
Multiple-dimension arrays are provided, though not much used above two dimensions. The declara-
tion and use look like
int name[10] [20];
n = name[i+j] [1] + name[k] [2];
Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row (opposite to For-
tran), so the rightmost subscript varies fastest; name has 10 rows and 20 columns.
Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline
at the end).
main( ) {
int n, c;
char line[100];
n = 0;
while( (c=getchar( )) != ?\n? ) {
if( n < 100 )
line[n] = c;
n++;
}
printf("length = %d\n", n);
}
As a more complicated problem, suppose we want to print the count for each line in the input, still
storing the first 100 characters of each line. Try it as an exercise before looking at the solution:
main( ) {
int n, c; char line[100];
n = 0;
while( (c=getchar( )) != ?\0? )
if( c == ?\n? ) {
printf("%d0, n);
n = 0;
}
else {
if( n < 100 ) line[n] = c;
n++;
}
}
12. Character Arrays; Strings
Text is usually kept as an array of characters, as we did with line[ ] in the example above. By con-
vention in C, the last character in a character array should be a ‘\0’ because most programs that manipulate
character arrays expect it. For example, printf uses the ‘\0’ to detect the end of a character array when
printing it out with a ‘%s’.
We can copy a character array s into another t like this:
i = 0;
while( (t[i]=s[i]) != ?\0? )
i++;
Most of the time we have to put in our own ‘\0’ at the end of a string; if we want to print the line with
printf, it’s necessary. This code prints the character count before the line:
main( ) {
int n;

C Tutorial
? 9 ?
char line[100];
n = 0;
while( (line[n++]=getchar( )) != ?\n? );
line[n] = ?\0?;
printf("%d:\t%s", n, line);
}
Here we increment n in the subscript itself, but only after the previous value has been used. The character
is read, placed in line[n], and only then n is incremented.
There is one place and one place only where C puts in the ‘\0’ at the end of a character array for you,
and that is in the construction
"stuff between double quotes"
The compiler puts a ‘\0’ at the end automatically. Text enclosed in double quotes is called a string; its
properties are precisely those of an (initialized) array of characters.
13. For Statement
The for statement is a somewhat generalized while that lets us put the initialization and increment
parts of a loop into a single statement along with the test. The general form of the for is
for( initialization; expression; increment )
statement
The meaning is exactly
initialization;
while( expression ) {
statement
increment;
}
Thus, the following code does the same array copy as the example in the previous section:
for( i=0; (t[i]=s[i]) != ?\0?; i++ );
This slightly more ornate example adds up the elements of an array:
sum = 0;
for( i=0; i<n; i++)
sum = sum + array[i];
In the for statement, the initialization can be left out if you want, but the semicolon has to be there.
The increment is also optional. It is not followed by a semicolon. The second clause, the test, works the
same way as in the while: if the expression is true (not zero) do another loop, otherwise get on with the next
statement. As with the while, the for loop may be done zero times. If the expression is left out, it is taken
to be always true, so
for( ; ; ) ...
and
while( 1 ) ...
are both infinite loops.
You might ask why we use a for since it’s so much like a while. (You might also ask why we use a
while because...) The for is usually preferable because it keeps the code where it’s used and sometimes
eliminates the need for compound statements, as in this code that zeros a two-dimensional array:
for( i=0; i<n; i++ )
for( j=0; j<m; j++ )
array[i][j] = 0;

C Tutorial
- 10 -
14. Functions; Comments
Suppose we want, as part of a larger program, to count the occurrences of the ascii characters in some
input text. Let us also map illegal characters (those with value>127 or <0) into one pile. Since this is pre-
sumably an isolated part of the program, good practice dictates making it a separate function. Here is one
way:
main( ) {
int hist[129];
/* 128 legal chars + 1 illegal group */
...
count(hist, 128);
/* count the letters into hist */
printf( ... );
/* comments look like this; use them */
...
/* anywhere blanks, tabs or newlines could appear */
}
count(buf, size)
int size, buf[ ]; {
int i, c;
for( i=0; i<=size; i++ )
buf[i] = 0;
/* set buf to zero */
while( (c=getchar( )) != ?\0? ) {
/* read til eof */
if( c > size | | c < 0 )
c = size;
/* fix illegal input */
buf[c]++;
}
return;
}
We have already seen many examples of calling a function, so let us concentrate on how to define one.
Since count has two arguments, we need to declare them, as shown, giving their types, and in the case of
buf, the fact that it is an array. The declarations of arguments go between the argument list and the opening
‘{’. There is no need to specify the size of the array buf, for it is defined outside of count.
The return statement simply says to go back to the calling routine. In fact, we could have omitted it,
since a return is implied at the end of a function.
What if we wanted count to return a value, say the number of characters read? The return statement
allows for this too:
int i, c, nchar;
nchar = 0;
...
while( (c=getchar( )) != ?\0? ) {
if( c > size | | c < 0 )
c = size;
buf[c]++;
nchar++;
}
return(nchar);
Any expression can appear within the parentheses. Here is a function to compute the minimum of two inte-
gers:
min(a, b)
int a, b; {
return( a < b ? a : b );
}

Download
Programming in C A Tutorial

 

 

Your download will begin in a moment.
If it doesn't, click here to try again.

Share Programming in C A Tutorial to:

Insert your wordpress URL:

example:

http://myblog.wordpress.com/
or
http://myblog.com/

Share Programming in C A Tutorial as:

From:

To:

Share Programming in C A Tutorial.

Enter two words as shown below. If you cannot read the words, click the refresh icon.

loading

Share Programming in C A Tutorial as:

Copy html code above and paste to your web page.

loading