C Tutorial for Beginners

Introduction

C is a multi-platform, imperative procedural programming language with a static type system. It supports structured programming, lexical variable scope, and recursion. C programs are compiled, providing low-level access to memory, and programming constructs that map efficiently to machine instructions. This makes C fast, lightweight, and popular for writing applications that once would have been coded in assembly language. It is also useful for controlling small embedded devices with limited resources.

C is an excellent first programming language to learn as it requires a programmer to pay attention to and familiarize themselves with data types, memory management, and other low level concepts that may be abstracted away by higher level languages. As a multi-platform language, C programs may be written and compiled in many different environments with minimal or no changes to the source code required for cross-platform compatibility.

What do I need to start?

If you want to write C programs you need three things:

  • Access to a computer.
  • A text editor.
  • A compiler.

Text editors come installed in all operating systems. Windows has Notepad. Linux has Vi, Emacs, Nano, and usually Mousepad. Other free alternatives you can download include Notepad++ and Visual Studio Code.

Compilers are programs that translate C code that you write into binary machine language programs that can be executed by your computer. Compilers come pre-installed on most flavors of Linux but if you have Windows you are going to have to download and install your own. Mingw is free. After you install it you will have to add the Mingw bin subdirectory to your PATH environment variable. To do this on Windows 10: type Advanced System Settings in the Windows search bar, select it, and then select the Environment Variables button. Highlight the Path variable, click Edit, select New, and type the path to the Mingw bin subdirectory. This allows your command line to recognise the compiler commands we will use to create our programs.

Hello World!

We are going to write our first C program. The first program that one traditionally writes in a new language is a program to print a variation on the phrase "Hello World!" This is essentially as simple as a program gets while still producing some sort of output so it serves as a good template for other programs.

Create a file with a .c extension. hello.c is a good example. Now open it in your text editor and you will see a blank file. Type the following into the file:


#include <stdio.h>

int main()
{
  printf("Hello World!\n");
}
          

The above code can be broken down as follows:

  • The include line imports the stdio C library into our program to give us input and output functionality.
  • int main() defines the main function of our program. The main function is always the first to be called when a C program executes.
  • The open curly brace indicate the beginning of the main() function.
  • The printf line prints the phrase contained within the double quotes (and the \n creates a newline). printf is a function of the stdio library we imported earlier.
  • The final closing curly brace indicates the end of the main() function.

With the exception of the printf line and perhaps the import line, this is essentially the boilerplate that you will use for all of your C programs.

In order to run your program you will need to navigate to the directory containing the file using Windows Command Prompt or a Linux terminal. Type:

gcc hello.c -o hello.exe

Where hello.c is the name of your text file you wish to input into the compiler and hello.exe is the name of the program you wish the compiler to output. If using Windows you will want to end this in .exe. If you are using Linux then you can end the output file without an extension, i.e. hello.

To run the file in Windows type:

hello.exe

To run the file in Linux type:

./hello

If everything went right, and you see the text "Hello World!", then you just successfully executed your first C program! Congratulations! If something went wrong, then you may have your first bug (which you should find and correct), or your compiler may not be working properly (which you should troubleshoot using Google).

Variables & Data Types

When you declare a variable in C you give it a type and a name and the operating system sets aside enough memory to hold a value of that type. e.g.


int number;
          

In this example, int is the data type and number is the variable name.

There are two main types of primitive variables in C: numeric and character. Numeric variables may be type integer (int) for whole numbers, and type real (float) for numbers with a fractional or decimal point value. Character variables (char) can represent any ASCII character, including letters and the numbers 0-9. When assigning a value for a char variable we enclose it in single quotes. This distinguishes, for example, the integer 8 from the character '8'.

int num1 = 12;
float num2 = 3.14;
char character = 'B';
          

Variables can be given a value on the same line in which they are declared, or they may be assigned values later. Variable values may also be changed at any given time.

int num1;
float num2;
char c;
      
num1 = 34;
num2 = 2.72;
c = 'z';
          

A variable has a type-name, a type, a range of possible values, and a placeholder for use in printf statements.

Type-NameTypeRangePlaceholder
intNumeric - Integer-32,768 to 32,768%i or %d
shortNumeric - Integer-32,768 to 32,768%i or %d
longNumeric - Integer-2,147,483,648 to 2,147,483,648%ld
floatNumeric - Real1.2 X 10-38 to 3.4 X 1038%f
doubleNumeric - Real2.2 X 10-308 to 1.8 X 10308%lf
charCharacterAll ASCII characters%c

The placeholder is used to include variables in printf statements. For example, say you have an integer called num and you wish to include it in a printf statement:


int num = 13;

printf("Num is equal to %i.\n", num);

Output: Num is equal to 13.
          

You may include as many placeholders as you wish in a printf string, as long as you list the variables in the correct order in the printf arguments after the string itself.


int num1 = 13;
float num2 = 3.14;

printf("num1 is %i and num2 is %f.\n", num1, num2);

Output: num1 is 13 and num2 is 3.14.
          
Mathematical Operators

C uses various mathematical operators in order to carry out calculations on variables and other values. These mathematical operators are listed below.

OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (division remainder)

The mathematical operators may be used between operands (or values) to calculate solutions.

int a, b, c;
a = 2;
b = 3;
c = a + b;
printf("%i\n", c);

Output: 5
          

The order of operations is P-E-M-D-A-S, i.e. parentheses, exponents, multiplication, division, addition and subtraction. Thus you can use parentheses to control the order in which operands and operators are calculated.

int a = 3 + 4 * 2;
int b  = (3 + 4) * 2;

printf("a is %i. b is %i.\n", a, b);

Output: a is 11. b is 14.
          

The modulus operator gives the remainder left over after integer division.


int a = 7 % 2;
int b = 19 % 8;

printf("a is %i. b is %i.\n");

Output: a is 1. b is 3.
          

There are three ways to increment/decrement a variable in C. The first is to simply assign the variable an equation containing itself.


a = a + 1;
          

The second is to use the += operator (this also works with -=, *=, /=, and %=).


a += 1;
          

The final method is to use ++ or -- operators. These increment or decrement a variable's value by one, respectively.


a++;
          

All three of the above examples increment the variable a by 1.