Part 2. Introduction to C programming

As we go along this series, I'll introduce new concepts a bit at a time. Rather than tell you everything all at once, I'll give you enough information to get started, and we'll add to that knowledge later. This should help you to learn as you go.

Anatomy of a C program

When you learn any new programming language, you usually start by understanding how to put your program together. How do you write your statements? How does the compiler understand your statements? So let's start by examining the anatomy of a simple C program, and go from there.

Here is a short C program that prints out the message Hello world to the user:

#include <stdio.h>

int
main()
{
   /* say hello to the user */
   puts("Hello world");
   return 0;
}

C programs start with "include" statements. These statements tell the compiler to insert other files when you compile the program. In this case, the first line #include <stdio.h> tells the compiler to include the file stdio.h when you compile. This file name is inside angle brackets because it is located in a standard directory for the C compiler.

The #include statement is also called a directive.

The program itself is defined by the main function. Every C program must have a main function; that is the program itself. C uses functions everywhere, and we will learn more about functions at a later time. For now, you need to know that to define a function (like main) you need to tell the compiler what kind of value it returns (in this case, an int or integer value). You also indicate it is a function by adding the parentheses.

What makes up the main function? That's everything inside the curly braces.

The first line of our program is actually a comment, so the compiler ignores it. In C, you can use comments to make your code easier to read. The compiler will ignore everything inside a comment. You can use comments to remind yourself what your program does, or to explain a particular algorithm; when you come back to your code later, you will be able to remember what it does. Begin a comment with /* and end it with */. Everything in between those two markers is your comment.

You can also create a comment with // and the compiler will ignore the rest of that line. Use whatever style comments that suits you.

The next line puts("Hello world"); is a statement that calls a function. That function, puts, will put a string to the screen. The argument to the function is the string value Hello world. You tell C that it is a string by enclosing it in double quotes.

End your statement with a semicolon. The semicolon tells the C compiler that your statement is finished, and anything else is a different statement. Don't forget your semicolons.

And the last line return 0; tells the main function to exit, and return the value zero to the operating system. Returning values like this from main can be useful. FreeDOS uses the return value to tell batch files about the success or any failure in the program. Usuallyi, zero indicates a successful return. Any other value (1, 2, 3, …) indicates something went wrong.

You should know that in C, white space is not really important. Unless it is inside a string, the compiler treats spaces, tabs, and newline characters the same. You could just as easily written the entire main function on one line, and that would have been valid. But while the compiler would understand a program written this way, you might not—at least, the next time you come back to the program. So use white space wisely.

I prefer to put the curly braces for a function on their own lines. And I like to put a few spaces before each statement, so I can see that they are part of the function. This will be important later on when we learn about loops, and this spacing can make your code much more readable.

Our first program

Now that we've learned how to put a program together, let's do something a little more meaningful. Computers are very good at calculating numbers, so let's write a simple program that divides one number by another.

As we get started with this program, let's talk about variable types. Variables store values. C supports several different types of variables. The most common that you might use are:

int Integer values. These are whole numbers like 0, 1, 2, 3, … or even negative numbers like -1, -2, …
char Character values. These are very similar to integers, but they are usually can't store values as large as int can. Typically, char is used to keep individual characters, or letters.
float Floating point numbers. Any number that requires a decimal point. Numbers like 1.1 or 4.5 are floating point. And numbers with a zero are also floating point, such as 0.0 or 4.0.
double Double precision floating point numbers. As you might guess from the name, these are similar to float but can store numbers about twice as big (or small).

Variables make it easy to store information. An important thing to remember is that every variable must have a name. Variable names are made up of any combination of uppercase or lowercase letters (A to Z, or a to z), or numbers (0 to 9), or an underscore (_). But you may not start a variable name with a number. And I recommend that you avoid starting your own variable names with an underscore, as that is usually only done with "system" variables.

For example, the following variable names are all valid:

Try to make your variable names meaningful. Avoid single-letter variable names; while short names like i or n are valid names, your program code may be difficult to understand when you come back to it later and try to figure out what the variable j was supposed to mean.

To tell the compiler about a variable that you want to use, write the variable's type and its name at the start of your program. To define an integer variable called top you would write int top;.

Anywhere in your program, you can assign a value to your variable by writing its name, then an equal sign, and the value you want to store. So top = 25; would put the value 25 into the variable top.

You can do change the values in variables by doing operations on them. The arithmetic operators are the most common, and include:

+ Add two values
Subtract one value from another
* Multiply two numbers together
/ Divide one number by another

Let's write our program to divide two numbers.

#include <stdio.h>

int
main()
{
   int top;
   int bottom;

   int result;
   int remain;

   top = 25;
   bottom = 5;

   result = top / bottom;
   remain = top - (result * bottom);

   puts("using arithmetic:");
   printf("%d / %d = %d rem %d\n", top, bottom, result, remain);

   remain = top % bottom;

   puts("using modulo:");
   printf("%d / %d = %d rem %d\n", top, bottom, result, remain);

   return 0;
}

This program introduces two new topics: the formatted print statement (printf) and the modulo operator (%).

Modulo is similar to division, except the modulo divides two numbers and gives you the remainder. So the statement result = 25 / 5; would store the value 5, and result = 25 % 5; would store the value 0, because 25 divided by 5 is 5 with nothing left over.

Let's change that up a bit. Here's another program that mixes integers with floating point values:

#include <stdio.h>

int
main()
{
   int radius = 16;

   int perim;
   int area;

   perim = 2 * 3.141 * radius;

   area = 3.141 * radius * radius;

   printf("perimeter of circle (r=%d) is %d\n", radius, perim);
   printf("     area of circle (r=%d) is %d\n", radius, area);

   return 0;
}

You only get an approximation when floating point values are truncated to integers. So let's update the program to use float instead:

#include <stdio.h>

int
main()
{
   float radius = 16.0;

   float perim;
   float area;

   perim = 2.0 * 3.141 * radius;

   area = 3.141 * radius * radius;

   printf("perimeter of circle (r=%f) is %f\n", radius, perim);
   printf("     area of circle (r=%f) is %f\n", radius, area);

   return 0;
}

If you need to reference the same value all the time, you may want to use a constant instead. The value of pi is a value that you might use several times in a program. Let's define it as a constant using #define:

#include <stdio.h>

#define PI 3.1415926535

int
main()
{
   float radius = 16.0;

   float perim;
   float area;

   perim = 2.0 * PI * radius;

   area = PI * radius * radius;

   printf("perimeter of circle (r=%f) is %f\n", radius, perim);
   printf("     area of circle (r=%f) is %f\n", radius, area);

   return 0;
}

Finally, we should update this program to read input from the user. Just like printf is a function to print information to the user, we can use scanf to read or scan information from the user. When you use scanf, you need to put the & in front of the variable name. We'll talk about that much later in the programming series, when we talk about pointers and addresses—but for now, just know that you need that & in front of the variable name to use scanf.

#include <stdio.h>

#define PI 3.1415926535

int
main()
{
   float radius;

   float perim;
   float area;

   puts("enter the radius:");
   scanf("%f", &radius);

   perim = 2.0 * PI * radius;

   area = PI * radius * radius;

   printf("perimeter of circle (r=%f) is %f\n", radius, perim);
   printf("     area of circle (r=%f) is %f\n", radius, area);

   return 0;
}

REVIEW

Anatomy of a C program:

/* comment to describe the program */

#include <stdio.h>
/* other #include statements here as needed */

/* definitions */

int
main()
{
   /* variable declarations */

   /* program statements */
}

Common variable types:

intInteger values
charCharacter values
floatFloating point numbers
doubleDouble precision floating point numbers

Arithmetic operators:

+Addition
Subtraction
*Multiplication
/Division
%Modulo (remainder after division of two ints

Common printf conversions:

%d, %iint Signed decimal number
%uint Unsigned decimal number
%oint Unsigned octal number (no leading zero)
%x, %Xint Unsigned hexadecimal number (no lading 0x or 0X)
%cint Single character
%schar * String of characters
%fdouble Floating point number
%e, %Edouble Floating point number using []mmm.ddd
%g, %Gdouble Floating point number, like %e or %E if the exponent is not too large or small, otherwise like like %f
%pvoid * Print value as a pointer
%%Prints a percent sign (%)

Common escape characters:

\nNew line (use this whenever you need to make a new line)
\aMake a beep ("alert")
\bBackspace
\fNew page ("form feed")
\tTab
\vVertical tab
\\Prints a backslash character (\)
\"Prints a double quote (")
\'Prints a single quote (')
\?Prints a question mark (?)

PRACTICE

Now that you've learned about the basics of writing C programs, let's practice that with a few exercises:

Practice program 1.

Write a program that calculates the volume of a sphere. Ask the user to enter the radius. The formula to calculate the volume of a sphere is:

𝒱 = 4/3 π 𝓇³

Practice program 2.

Write a program that converts Fahrenheit to Celsius. Ask the user to enter the temperature in Fahrenheit. The formula to convert Fahrenheit to Celsius is:

𝒞 = (ℱ − 32) × 5/9

Need help? Check out the sample solutions.