Getting Started with Programming in C
A program in the C programming language (or other computer languages) indicates a sequence of detailed instructions that specify the steps to be followed to solve a problem.
Programs provide a mechanism for communicating algorithms
Since a program articulates a proposed algorithm to accomplish a desired task, the program should be considered as a formal mechanism for precise communication. As a communication vehicle, a program has at least three audiences:
-
The author: When developing a program, the author must be able to review the steps for logical correctness, completeness, and efficiency. As proposed solutions to problems, programs may become long and complex. When a program is clear and easy to read, the author can review the program's logic and effectiveness.
-
Other people: In a class setting, an instructor and perhaps other students may read an algorithm to review correctness and efficiency and to gain insights in alternative approaches for solving a problem. In a software development environment (e.g., in industry), original programs are changed by new groups of developers to expand capabilities and to meet new needs.
-
Computers: Algorithms written in C and other programming languages can be interpreted by computers, allowing the machines to follow the instructions. Computers execute algorithms and help solve problems.
Throughout this course, we will write code that addresses the needs of all three audiences. Code with a specific syntax can be utilized by a computer, but code written just for a machine often misses the point.
-
When code lacks clarity, an author often will miss a detail that leads to errors.
-
When code is not easy to read, an author may find it difficult and time consuming to locate errors. On the other hand, when code is clear and easy to read, finding problems often is reasonably straight forward.
Examples First
As you begin to program in C, you will encounter a reasonably large number of mechanics and details. If you have not programmed before, the steps may seem unintuitive and awkward. Further, programs in C require a specific syntax or format. Since the C environment may be new and different, it may take some time to become comfortable with the syntax (format) and process.
Don't panic, before long (perhaps a few days), many of these mechanics will become familiar, and you will be able to focus on more conceptual elements of problem solving with C.
Since the various rules and procedures may be unfamiliar, this module highlights working examples. Readings, such as this one, will involve some complete programs, and commentary will explain beginning elements of C and relevant procedures. Later modules will provide more complete discussions of imperative problem solving and the C programming language.
Example 1: quarts.c — A first program in C
As a first program in C, consider the following code that converts a number of quarts to liters. Commentary in the right column, next to the program, explains each program element.
Numerous blank lines are inserted for spacing, so the commentary generally is near the lines discussed. C allows white space (blank lines and spaces) to be inserted many places for readability. (White space may not be placed in the middle of numbers or names, but almost anywhere else.) The program, without extra blank lines, is available as the file quarts.c
A subsequent section explains how this program may be run.
/* A simple program to convert a number of quarts to liters */
Commentary for quarts.c
-
C allows programmers to include notes to clarify portions of code. These comments are not utilized when a computer runs a program, but they can help organize one's thoughts, clarify logic, and explain the algorithm.
C provides two mechanism for writing comments.
-
Comments may begin anywhere with the symbols
/*
, continuing until the symbols*/
, on the same or later lines. - Comments may begin with the symbols // and continue through the remainder of the line.
Both types of comments are represented in this example.
-
Comments may begin anywhere with the symbols
#include <stdio.h> // use C's standard I/O library
-
C makes use of libraries for many common operations, including the
stdio
library for input (reading from the keyboard) and output (printing). The statement#include <stdio.h>
instructs the machine to use the
stdio
operations.
int main () // beginning of main program
-
Each C program contains a driver function/procedure, called
main
. Here, main uses no input parameters (hence the parentheses with nothing between them followingmain
). In standard C, themain
function/procedure must return an integer as an error code (hence theint
beforemain
).
{
-
Braces
{
and}
are used in C to mark the beginning and ending of blocks. In this case, the braces indicate the statements for themain
procedure.
printf ("Program to convert quarts to liters\n"); // write opening statement
- Semicolons (;) are used to terminate every statement in C.
/* declaration of variables, with their types */ int quarts; /* int means integer (no decimal point) */ double liters; /* double means real number */
-
Variables may be declared globally or at the start of a C function. Here,
quarts
andliters
are declared within the main procedure as integer and real variables, respectively. The termdouble
specifies a real number, stored using double precision. (The termfloat
may be used for single precision, real numbers.)
quarts = 2; // specify number of quarts as 2
- The equal sign (=) is used for assignment. (We will see later that == is used to determine if two items are equal.)
liters = quarts / 1.056710; // arithmetic and assignment
- Arithmetic operations include +, –, *, and / for addition, subtraction, multiplication, and division. For integers, the division operation / yields the integer quotient, while the modulus operation % gives the remainder.
printf ("%d quarts = %lf liters\n", quarts, liters); // write text and new line
-
printf
is used for output. The first parameter is a string, which indicates how the output will be formatted.-
When printing text only, as in the first output line in this program,
the text of the string is enclosed in double quotes
" "
, and the characters are printed exactly as given. -
Within a format string, some symbols are used for special characters. For
example,
-
\n
stands for a new-line character, -
\t
stands for a tab character, -
\"
stands for a double quote character, and -
\\
stands for the backslash character itself.
-
-
When printing the value of a variable, the format string
for
printf
gives the type of data to be displayed:-
"%d"
stands for a (decimal) integer, -
"%f"
stands for a (floating point) real number, -
"%lf"
stands for a double precision (long) real number, -
"%c"
stands for a (single) character, -
"%s"
stands for a character string.
-
-
When printing text only, as in the first output line in this program,
the text of the string is enclosed in double quotes
return 0; // the program ran without errors }
- When the program runs normally, without error, the integer 0 is usually returned. This program then ends.
Developing and Running a C Program
Creating, refining, and running a C program requires three basic steps:
-
Editing: Use a simple text editor to create and edit a C program.
Sample command for program quarts.c (all typed within a terminal window):aquamacs quarts.c &
Notes on editing, compiling, and running a C program
- Use the aquamacs text editor for creating and editing your programs.
- Do not use a word processing package, such as Word, OpenOffice, or LibreOffice, because these packages insert extensive formatting and font information that will confuse the computer as it tries to follow the instructions in your program.
- The ampersand (&) allows editing to take place while the terminal window can still be used for other activities.
-
Compiling: Use a compiler to translate the C program to a machine language version.
Sample command using gcc to produce machine-language program quarts from quarts.cgcc -o quarts quarts.c
- Once the program has been written with the editor and saved, the program must be translated from C to machine language.
-
In some languages, such as Scheme, this work is done behind the
scenes, but in C the translation must be made explicit. The
translation is called compiling, and the utility used to
compile a program is called a compiler. A common compiler for
C is called
gcc
. -
To compile the program, the line
gcc -o quarts quarts.c
gcc
with the program we have edited (quarts.c
). The directive-o quarts
indicates we want the compiler to place our translated program in an output file calledquarts
. - No need to exit the editor before compiling with the gcc command in the terminal window.
-
Warning: Be sure the name of the output file (
quarts
) is different from the name of your original program (quarts.c
). If you use the same name for both, your original program will be overwritten and lost!
-
Running: Type the name of the program, perhaps preceded by ./ to indicate the program is located in the current directory.
Sample command for quarts./quarts
./
indicates
that this program may be found in your current directory.
Putting the steps together
The following interaction in a terminal window shows a sample session,
run on workstation perlis,
including writing, translating, and running quarts.c
.
perlis$ aquamacs quarts.c & perlis$ gcc -o quarts quarts.c perlis$ ./quarts This program converts quarts to liters 2 quarts = 1.892667 liters
This example uses the emacs editor to create and edit the file quarts.c, the gcc compiler to create the machine language version of the program, and the name of the program to run the program in a terminal window. This example also shows the output created by the program.
Example 2: temperature.c — Converting Fahrenheit to Celsius
Our second C program addresses the problem of converting a temperature in Fahrenheit to the corresponding temperature in Celsius. The solution, program temperature.c, utilizes many of the elements of the first example, quarts.c, reinforcing earlier comments, although a few elements are different.
/* program to convert a temperature in fahrenheit to a temperature in celsius */ #include <stdio.h> int main () { int fahrenheit; double celsius;
Notes for temperature.c
- The program opens with a comment explaining what the program does. As you work with progressively more programs through this course and beyond, you will find this type of header is useful in clarifying just what a program does — particularly a week or longer after you wrote it.
-
Variable declarations include
- fahrenheit as an int or integer (a number without a decimal point)
- celsius as a double or real number (a number with zero or more digits after a decimal point).
-
As with program quarts.c, variables in program
temperature.c are local
- The variables are declared locally within main.
- Although both fahrenheit and celsius can be used within main, neither could be used outside main.
- Declaring variables locally, within procedures, follows good programming practice, and thus is used throughout this course.
fahrenheit = 72; celsius = (fahrenheit - 32.0) * 5.0 / 9.0; printf (" %d degrees fahrenheit = %5.2lf degrees celsius\n", fahrenheit, celsius); return 0; }
- C recognizes arithmetic operations +, -, *, and / for addition, subtraction, multiplication, and division, respectively. (More about division in the next module.)
- In C, by default multiplication and division take precedence over addition and subtraction, just as in mathematics. Using parentheses overrides the default order of operations. Parentheses also can help clarify how various operations should go together and thus make a program relatively easy to read.
-
C allows statements, such as printf, to extend over multiple
lines.
- Each statement continues until a semicolon is encountered.
-
If desired, the computations for celsius similarly could be
written on several lines. Here is one possible alternative:
celsius = (fahrenheit - 32.0) * 5.0 / 9.0 ;
- However, a string (expressed in double quotes " ... ") is considered a single entity and thus cannot be formatted to extend over more than one line.
Compiling and running temperature.c
Following the same process used for quarts.c, the program temperature.c could be compiled and run on workstation perlis as follows:
perlis$ gcc -o temperature temperature.c perlis$ ./temperature 72 degrees fahrenheit = 22.22 degrees celsius
Example 3: temperature-acg.c — Temperature Conversion with Averaging
As another example, consider the problem of writing a program that starts with two temperatures in Fahrenheit, computes the average of the temperatures, determines the corresponding Celsius temperatures, and prints the result in a table. For example, one run of the program might yield:
Fahrenheit Celsius Temperature 1: 86.1 30.1 Temperature 2: 111.1 43.9 Average: 98.6 37.0
The following program temperature-avg.c addresses this problem, building on the two earlier programs (above).
/* program to convert two temperatures in fahrenheit and their average to temperatures in celsius */ #include <stdio.h> int main () { /* declare variables */ /* the fahrenheit and celsius temperatures may contain decimal points, so will be real numbers (e.g., doubles) */ double fahr1, fahr2; double cel1, cel2; /* initialization */ fahr1 = 86.1; fahr2 = 111.1;
Notes for temperature-avg.c
- Several variables of the same type may be declared on the same line; just separate the identifier names by commas
- Since the numbers may contain decimal points, each variable is identified as a double.
/* compute celsius equivalents */ cel1 = (fahr1 - 32.0) * 5.0 / 9.0; cel2 = (fahr2 - 32.0) * 5.0 / 9.0;
- Separate computations are written out for both Celsius temperatures. Later in the course, we'll see how to define a single function to perform such repeated computations.
/* computer average values */ double sum = fahr1 + fahr2; /* average computation split into two steps for variety */ double fahravg = sum / 2.0; double celavg = (fahravg - 32.0) * 5.0 / 9.0; /* print table of results */
- In this problem, two averages are needed: the average temperature in fahrenheit and the corresponding temperature in celsius.
- In each case, the computations might be done in one step, or a computation might be subdivided into several substeps. For this program, the average is subdivided into a sum and a division step.
- This section illustrates that a variable can be declared and initialized in the same line. Previously, variables were declared in one line, and values were stored in those variables later on. Often, there is little advantage to one of these approaches versus the other.
printf (" Fahrenheit Celsius\n"); //table title /* report results to 1 decimal place */ printf ("Temperature 1: %7.1lf %10.1lf\n", fahr1, cel1); printf ("Temperature 2: %7.1lf %10.1lf\n", fahr2, cel2); printf (" Average: %7.1lf %10.1lf\n", fahravg, celavg); /* tell operating system "no errors" */ return 0; }
-
In printing a table, one must worry about how much room to allocate for
each column. Here,
- spaces and words are written out for the first column.
- 7 characters are allocated for the first number (the temperature in fahrenheit). The "7" in "7.1lf" specifies this column width.
- each number is printed to 1 decimal place of accuracy. The ".1" in "7.1lf" and in "10.1" indicate the number of decimal places.
- 10 characters are allocated for the second number (the temperature in celsius". the "10" in "10.1lf" specifies this column width.
created created 18 July 2011 reformatted and revised 8 May 2016 typos corrected 28 August 2016 modest editing, reformatting 22 August 2017 Example 3 added 6 September 2017 use of Aquamacs 22 January 2018, 16 January 2022 |
![]() ![]() |
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |