Back up to Programming Main Site
C-Programming Examples and Exercises
Week 1: Program Basics, Variable Declaration, Loops, Arithmatic
Operators, and Comments
- Hello World Example: Use this simple example to
ensure that you are able to compile and run programs with the development
environment. To compile and run with DevC++:
- Download the program (right-click, save link target as...)
- Save to your computer - It is recommended that you make a new
folder (directory) for each example.
- Open the file in DevC++.
- Go to the "Execute" menu. Click "Compile and Run".
- Area of Rectangles Example: This example
computes and prints the area of rectangles that have widths of 10 and
varying heights from 1 to 25. Compile, run, and read the output of
the example. Look for the following main points:
- Comments: A large comment at the top explains how comments work.
Comments are critical to good programs and good teamwork!
- Macro Definitions: The definition of RECTANGLE_WIDTH is a macro
definition, used to contain a constant value and give it a symbolic
name. Read the explanation of macros in the source code.
- Main: The main function is the starting point for programs. The
computer begins the program with the first line of main. With the
robot, main begins as soon as the robot is powered on.
- Variable declarations: See the comment in the source that explains
declarations. A declaration sets aside memory for a variable and gives
the variable a name. Remember... a variable has no value unless you
assign one! If you forget to give a variable a value before using
it, the compiler will not issue an error. Instead, your program
will be unpredictable!
- "for" loops: A loop is a convenient way to execute the same code
multiple times. The body of the loop is executed until the "condition" of
the loop is no longer true. The body of the loop is the part in braces
- { ... } - following the for statement. If no braces are used, the
body is just the next statement.
A "for" statement has three main parts, all within parenthesis:
- Initialization (
i = 1 in the example): This
expression is executed only once, at the beginning of the loop. You
typically use this to set up a counter variable (like "i" in the
example).
- Test (
i <= 25 in the example): Executed each
iteration through the loop. If it evaluates "true", the body of
the loop runs. If "false", the loop ends. Note that if this test
is false when the loop initially begins, the body is skipped
entirely.
- Increment (
++i in the example): Executed
at the end of each iteration of the loop, after the loop body
executes but before the test condition. You typically use this to
increment or add to a loop counter variable.
- Assignment: You give variables a value with assignment (using the '='
operator). The example has two assignment statements:
i =
0 and area = RECTANGLE_WIDTH * i.
- Arithmetic: In the body of the loop, the example performs
multiplication of the rectangle's dimensions. The '*' operator
multiplies two values. Other operations available are addition (+),
subtraction (-), and division (/).
- Comparison: You can compare variables with statements like
i <=
25. The <= operator checks if the first value is less-than
or equal-to the second value. Most other mathematical comparisons are
available, just as you'd expect.
- Additional Lessons:
- While loops: A "while" loop is an alternative to a "for" loop. It
looks like the following:
while (test) {
body
}
At the beginning of the loop, the "test" condition is executed. If it
is true, the body executes once. The test is then executed again - if
true, the body executes again. This continues until the test is false.
- Perimeter Exercise: Take the area example and modify it to compute
the perimeter of the same rectangles as the original. Also substitute a "while"
loop for the "for" loop.
Week 2: Functions and Arrays
- Function and Array Example: This example
illustrates the use of arrays and functions. Main Points:
- A function can be used to encapsulate a task in a program. It takes
input in the form of arguments and can return a single value.
Functions are a good way to contain code that might be executed
multiple time or from multiple places in a program.
- The main function is a special function - the program begins
there.
- Function prototypes state the existence of the function. They must
appear in the file somewhere before they are used. They are
typically done at the top of a file, or in a header file (we'll cover header
files in another week). Note the prototype for the distance function.
- Function definitions contain the source code for what the function
actually will do. A function definition can occur anywhere.
- Arrays contain a series of the same type of values in a big
"chunk" of memory. They allow you to hold a set of values and make it
easy to perform the same operation on multiple values. Note how the
arrays of points can be iterated over in a loop. In this way, the loop
can easily perform the same operations on a set of input data (in this
case, the distance function is called, followed by a print
statement). Each item in an array is called an element of the
array.
- Arrays are declared in a similar way to simple variables (note the
similarity between the declarations of "int i" and "int
end_points[NUM_POINTS]")
- Arrays can be declared without values (see the declaration of
end_points). In this case, you must give the size. The array is just
a chunk of memory at this point, just like "int i" is an empty chunk
of memory. We can't meaningfully use the array until it is given
values. In this example, we give it values in the first "for" loop.
- Arrays can also be declared with initial values. See the declaration
of start_points. An immediate assignment (=) gives the array initial
values (in {braces}). Note that you don't need to give a size here - the
size is determined from the number of values.
- "Indexing" an array is how we get the individual elements of the
array. Arrays are "indexed" starting with an index of zero (0). The
last element of an array has an index that is one less than its size
(so the index of the last element of an array of 5 elements is 4!).
Indexing is done by adding brackets to the end of the array name with
the index in the middle (so, myarray[10] would give me the 11th
element in an array named "myarray" -- remember, array indexes start
at 0!). In the example program, the array is indexed with the loop
variable, i. This lets us move one by one through the points
arrays.
- Function and Array Exercise: The exercise
program contains the skeleton of a full program. You are to add the missing
parts. When complete, the program should compute and print out the
perimeter and area of five rectangles. The 5 rectangles' dimensions are given
in a comment above the main function.
- The exercise comes with two functions defined to print out the area
and perimeter values once you have calculated them.
- Declare and define two new functions, one to compute area of a
rectangle. One to compute perimeter.
- Create arrays to hold the dimensions of the rectangles.
- Use either a "for" or "while" loop to iterate over the elements of the
arrays. Each iteration in the loop can represent one rectangle by indexing
your arrays of the dimensions.
- The body of the loop should pass the dimensions of a rectangle to your
new area and perimeter functions, then pass the results to the print
functions.
- In the end, you should get 10 lines of print outs - one area line and
one perimeter line for each of the 5 rectangles.
Week 3: If-Else and More Functions
Week 4: Data types Until now, we've been using only integer data.
These exercises introduce you to the other data types. Compile, run, and
examine the results.
Week 5: Multiple files Until now, we've been compiling simple
programs with only one .c file. Practical programs have many source files,
even into the hundreds.
- Multiple files exercise: Download all 3 files to one folder on
your computer. arm.c arm.h
armtest.c
To compile these in Dev C++, you will need to create a project and
add the three files to the project. A "project" in Dev C++ and in most
other programming software packages is a grouping of many source files
together to form a single program when compiled.
Back up to Programming Main Site