All courses
C Programming
C Programming

A full, structured course for first-year computer engineering. It starts with how the machine runs your code, then teaches C in order, from data types and operators through problem solving, functions, pointers, structs, memory and files. Fourteen lectures, Ghana-flavoured examples, and a live console. Open to complete beginners.

01
Machine
02
Start
03
Types
04
In / Out
05
Operators
06
Planning
07
Decisions
08
Loops
09
Functions
10
Arrays
11
Pointers
12
Structs
13
Memory
14
Lab
Start here
Why a C course begins with the machine

C is the language that sits closest to the hardware. To really understand why C behaves the way it does (why 7 / 2 is 3, why a variable has a limit, why scanf needs an &) you need a simple picture of what is going on inside the computer. This first part gives you that picture. You will come back to it in every later topic.

This is also Chapter 1 of your NCE 131 notes, so it doubles as revision for class.

Foundations
Input, process, output

Every computer, from a phone to a server, does the same three things. It takes input, does some processing, and produces output. It also stores data to use later.

Think of a chop bar. Customers give their orders (input). The kitchen cooks (processing). The food is served (output). The storeroom holds ingredients for later (storage). Every part of a computer maps onto one of these jobs.

Foundations
Everything is bits and bytes

Inside the machine, every value is held by tiny switches that are either off (0) or on (1). One 0 or 1 is a bit. Eight bits make a byte.

UnitSizeHolds
Bit1 switch0 or 1
Byte8 bits256 values (0 to 255), enough for one character like 'A'
Word16, 32 or 64 bitswhat the CPU handles in one go
KB / MB / GB1024 of the one belowtext, photos, whole programs

With n bits you can make 2 to the power n different values. That is why a byte (8 bits) holds 2^8 = 256 values. This is the reason every C type has a size and a limit.

Number systems
Decimal, binary and hexadecimal

We count in decimal (base 10, digits 0 to 9). Computers work in binary (base 2, digits 0 and 1). Programmers often write binary as hexadecimal (base 16, digits 0 to 9 then A to F) because one hex digit is exactly four bits.

Each position is worth the base raised to a power. For the binary number 1101:

Working
1101 = 1*8 + 1*4 + 0*2 + 1*1 = 13

In C you write hex with a 0x prefix, so 255 is 0xFF. Memory addresses are almost always shown in hex, like 0x7ffe5a3c.

Number systems
Converting by hand

Decimal to binary: divide by 2 again and again, and read the remainders from bottom to top. For 13:

Working
13 / 2 = 6 r 1
 6 / 2 = 3 r 0
 3 / 2 = 1 r 1
 1 / 2 = 0 r 1   ->  read up: 1101

Binary to decimal: add up the place values where there is a 1, as in the slide before. Binary to hex: group the bits in fours from the right and convert each group.

You will convert small numbers like these in Assignment 1. Practise a few by hand now and check them in the Lab console with printf("%d", 0xFF);
Architecture
Inside the machine: four blocks and a bus

Every microcomputer has four building blocks joined by a shared set of wires called the system bus.

CPU
the brain. Runs instructions, does arithmetic and logic.
Memory
holds the running program and its data (RAM).
Input / Output
brings data in and sends results out (keyboard, screen, sensors).
System bus
the wires that carry addresses, data and control signals between the blocks.

The big idea (the stored-program concept) is that instructions are stored in memory as numbers, just like data. The CPU fetches them one after another and carries them out. This is the fetch, decode, execute cycle: fetch the next instruction, work out what it means, do it, repeat.

Memory
RAM and storage are not the same

People mix these up. RAM is fast working memory that forgets everything when the power goes off. Storage (an SSD or hard disk) is slower but keeps your files when the machine is off.

A program runs in RAM. When you save a file, it goes to storage. You need both: RAM for speed while working, storage to keep things permanently. This is why an unsaved program is lost when the power cuts, something every Ghanaian student knows well.

Architecture
Microprocessor vs microcontroller

Two words that sound the same but are not. A microprocessor is only the CPU and needs separate memory and I/O chips. A microcontroller puts the CPU, memory and I/O on one chip, so it is a tiny complete computer.

MicroprocessorMicrocontroller
On the chipCPU onlyCPU + memory + I/O
Used forgeneral computingone dedicated job
ExamplesIntel Core i5, Apple M-seriesATmega328P (Arduino Uno), ESP32
Found inlaptops, phones, serversmicrowaves, cars, Arduino boards
The Arduino and Electronics course on this site runs C on a microcontroller. Same language, different machine.
Build pipeline
How your code becomes a running program

You write C in a text file ending in .c. The CPU cannot run that text directly. The compiler (gcc) reads your file, checks it, pulls in the library code you asked for, and builds an executable, the real program the machine runs.

1
You write and save hello.c
2
The compiler checks every line. A mistake stops it here with an error.
3
If it is clean, it builds an executable file.
4
You run the executable, and the CPU fetches and executes its instructions.
An error stops the build. A warning builds but is telling you something is probably wrong. Read both, and fix the first error first. The rest often disappear.
Intro
What C is, and why it is worth the effort

C was created in the 1970s and almost everything came after it. Operating systems, other languages, the firmware in your phone, all lean on C. It is strict and honest: it does exactly what you tell it, not what you meant. That is frustrating for a week, and then it makes you a real programmer, because you learn how the machine actually thinks.

Everything in this course is in order. Do not jump ahead. The people who struggle are the ones who skipped the basics and met pointers unprepared.

Get started
Three ways to run C
1
Use the Lab console on this site. Type code, press Run, see output. Nothing to install, works on your phone.
2
An online compiler like programiz.com, good for saving your work.
3
On a laptop, install Code::Blocks. It includes the gcc compiler, which is the setup your lecturer recommends.
Open the Lab tab now and run your first program before you read on. Reading about code is not the same as running it.
First program
Hello, and what each line means
C
#include <stdio.h>

int main(void)
{
    printf("Hello, Ghana\n");
    return 0;
}
#include <stdio.h>
bring in the standard input/output library so you can use printf
int main(void)
where the program starts. Every C program has exactly one main
{ }
the braces hold the body of main. Code runs top to bottom inside them
printf(...)
print text to the screen. \n means go to a new line
return 0;
end main and tell the system the program finished with no error
Syntax
The rules C will not bend on
  • Most statements end with a semicolon ;. A missing semicolon is the number one beginner error.
  • C is case sensitive. printf works, Printf does not.
  • Code bodies go inside braces { }.
  • Spaces and blank lines are for you, not the compiler. Use them to keep code readable.
  • Every program needs exactly one main.
Comments
Notes to yourself that the compiler ignores

Comments explain your code. The compiler skips them. Use them to say why, not just what.

C
// this is a single line comment

/* this is a
   multi line comment */

int fee = 200;   // tuition balance in cedis

Your lecturer requires a comment at the top of every program with your name, index number and what the program does. Get in the habit now.

Practice
Write a program that prints your name, your index number and your programme, each on its own line.
Put a comment at the top with your details, like the assignment asks.
Variables
A named box that holds a value

A variable is a named place in memory that holds a value you can read and change. You make one by writing its type then a name.

C
int age;          // make a box for a whole number
age = 19;         // put 19 in it

double price = 15.50;   // make and fill in one line
Variables
Naming rules

C is picky about names. A name may use letters, digits and the underscore, but:

  • it cannot start with a digit (2ndScore is invalid)
  • it cannot contain spaces or dashes (my-name and mtn balance are invalid)
  • it cannot be a C keyword (float as a name is invalid)
  • it is case sensitive, so age and Age are different boxes
Use names that say what they hold: totalFee, not x. Your future self and your marker will thank you. This is exactly what Assignment 2 Q1 checks.
Data types
The main types you need
TypeHoldsExamplePrint with
intwhole numbers42, -7%d
floatdecimals3.14%f
doubledecimals, more exact3.14159%lf
charone character'A'%c

For most work you use int and double. Reach for the others when you have a reason.

Characters
A char is a small number

A char holds one character, written in single quotes like 'A'. Here is the surprise: the computer stores it as a number using the ASCII code. 'A' is really 65, 'a' is 97, '0' is 48.

C
char grade = 'B';
printf("%c\n", grade);   // prints B
printf("%d\n", grade);   // prints 66, the ASCII code

This is why you can do maths on characters, like 'A' + 1 giving 'B'.

Numbers
int, float and double

Whole numbers go in an int. Numbers with a decimal point go in a float or a double. A double is the same idea as a float but keeps more digits, so it is more accurate. Prefer double unless you have a reason not to.

Decimal precision
Controlling how many decimals print

By default C prints a lot of decimals. Use %.2f to fix it, where the 2 is the number of places. This matters when printing money.

C
double price = 15.5;
printf("GHS %.2f\n", price);   // GHS 15.50
printf("GHS %.0f\n", price);   // GHS 16  (rounded, no decimals)
Memory size
sizeof, and why types have limits

From Chapter 1, every type takes up a fixed number of bytes, and more bytes means a bigger range. The sizeof operator tells you the size on your machine.

C
printf("int is %zu bytes\n", sizeof(int));     // usually 4
printf("double is %zu bytes\n", sizeof(double)); // usually 8

A 4 byte int holds about plus or minus 2 billion. Go past that and it overflows and wraps around, which is a real bug to watch for with big numbers.

Extended types
Bigger, smaller and unsigned

You can stretch or shrink the whole-number types:

  • long and long long hold bigger whole numbers
  • short holds smaller ones and saves memory
  • unsigned drops negatives, so an unsigned int goes from 0 upward only (good for counts and ages)

You will not need these often at first, but you will see them in real code and in the notes.

Constants
Values that must not change

Some values should never change while the program runs, like a fixed fee or pi. Mark them as constants so you cannot change them by accident.

C
#define BOOKING_FEE 2.00    // no type, no equals, no semicolon
const double PI = 3.14159;  // the typed way

double total = fare + BOOKING_FEE;

Assignment 2 Q5 asks you to use #define for a booking fee. This is why.

Type conversion
Mixing int and double, and the cast

When you mix types, C converts them. Mixing an int with a double promotes the int to a double automatically. But divide two ints and you get an int, which loses the fraction.

C
int bill = 100, people = 3;
printf("%d\n", bill / people);          // 33, the remainder is lost

double share = (double) bill / people;   // 33.33, the cast fixes it

Putting (double) in front forces C to treat the value as a decimal before dividing. This is called a type cast, and it is the fix for the integer-division surprise.

Practice
Declare a sensible variable, with the right type, for each: the number of students in your class, the price of a bag of rice, a grade letter, and pi to many decimals.
This is Assignment 2 Q2. Choose int, double or char for each and give it a clear name.
Output
printf and format specifiers

A format specifier is a slot in the text that gets replaced by a value. List the values after the text, in order.

C
int age = 19;
double fee = 2450.5;
char grade = 'B';
printf("Age: %d, Fee: GHS %.2f, Grade: %c\n", age, fee, grade);
%d
a whole number (int)
%.2f
a decimal to 2 places
%c
a single character
%s
a string of text (later topic)
Output
Escape characters

Some characters inside the text are special. They start with a backslash.

WriteYou get
\na new line
\ta tab, lines things up in columns
%%a real percent sign
\\a real backslash

So printf("%d%%\n", 75); prints 75% and then a new line.

Output
Printing money and tidy tables

Combine width and precision to line up a receipt. The \t tab keeps the colons in a column.

C
printf("Passengers : %d\n", 3);
printf("Fare each  : GHS %.2f\n", 15.50);
printf("Total      : GHS %.2f\n", 48.50);
Input
scanf reads what the user types

scanf looks like printf with one extra thing: an & before each variable.

C
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d\n", age);
Input
The & and why it is there

The & means the address of. You are telling scanf where the variable lives in memory (remember memory addresses from Chapter 1) so it can go there and write the value in.

The rule for now: scanf needs an & before each variable, printf does not. You will understand the full story in the Pointers topic. Forgetting the & is one of the most common bugs, and Assignment 2 Q4 has it on purpose.

Input
Reading several values, and the char trap

You can read more than one value at once. For a character after a number, put a space before %c so it skips the leftover Enter key.

C
int passengers;
double fare;
scanf("%d %lf", &passengers, &fare);   // read an int and a double

char grade;
scanf(" %c", &grade);                  // the space before %c matters
Match the specifier to the type: %d for int, %lf for double in scanf, %c for char. A mismatch reads garbage.
Worked example
A bus fare receipt

Putting input, a constant, maths and formatted output together.

C
#include <stdio.h>
#define BOOKING_FEE 2.00

int main(void)
{
    int passengers;
    double fare;
    printf("Passengers: ");
    scanf("%d", &passengers);
    printf("Fare each (GHS): ");
    scanf("%lf", &fare);

    double total = passengers * fare + BOOKING_FEE;
    printf("Total: GHS %.2f\n", total);
    return 0;
}
Practice
Read two whole numbers and print their sum, difference and product, each on its own line, neatly labelled.
Then read a price and a quantity and print the total cost to 2 decimal places.
Basics
Expressions, operands and operators

An expression is any piece of code that works out to a single value, like price + tax. It is built from operands (the values, like price) and operators (the symbols that act on them, like +).

Most operators take two operands, one on each side, like a + b. These are binary operators. A few take one, like the minus in -x. Those are unary. From Chapter 1, it is the CPU's ALU that actually does this work.

Arithmetic
The five arithmetic operators
OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23, not 3.5
%remainder7 % 21

Use * for multiply, never x. Writing 3x is an error.

Arithmetic
Integer division, the famous trap

In maths 7 / 2 is 3.5. In C it is 3. The rule: when both operands are whole numbers, C does integer division and throws away the fraction. It does not round, it chops. So 9 / 4 is 2 and 1 / 2 is 0.

C
int bill = 100, people = 3;
printf("Each pays %d\n", bill / people);  // 33, the GHS 1 left over is lost

To keep the fraction, at least one value must be a double. Make one a double or cast it with (double), as in the Types topic.

Arithmetic
The remainder operator %

% gives what is left after integer division. 7 % 2 is 1. It only works on whole numbers. It is more useful than it looks:

  • even or odd: n % 2 == 0 means n is even
  • last digit: 4721 % 10 is 1
  • splitting units: 125 minutes is 125 / 60 = 2 hours and 125 % 60 = 5 minutes
C
int total = 4000, h, m, s;
h = total / 3600;
m = (total % 3600) / 60;
s = total % 60;
printf("%d h %d min %d s\n", h, m, s);   // 1 h 6 min 40 s
Assignment
Storing values, the short way

= stores a value in a variable. The compound operators do an operation and store the result in one step.

C
int x = 10;
x += 5;   // x = x + 5  -> 15
x -= 2;   // 13
x *= 2;   // 26
x %= 5;   // 1  (remainder of 26 / 5)
Assignment
Increment and decrement

++ adds one, -- takes one away. The position matters. i++ uses the old value then adds one. ++i adds one first, then uses it.

C
int i = 4;
int j = i++ + 2;   // uses i as 4, so j = 6, then i becomes 5
printf("%d %d\n", i, j);   // 5 6
This exact example is in Assignment 3 Section B. Trace it slowly: read i first, then add 1 to i.
Comparing
Relational operators

These compare two values and produce 1 for true or 0 for false.

OperatorTrue when
==the two are equal
!=they are not equal
< > <= >=less, greater, less-or-equal, greater-or-equal
The biggest beginner bug in C: = assigns, == compares. if (x = 5) sets x to 5 and is always true. You almost always want ==.
Logic
Logical operators

These combine true/false conditions.

  • && (and): true only if both sides are true
  • || (or): true if either side is true
  • ! (not): flips true to false
C
int age = 20, hasID = 1;
if (age >= 18 && hasID) {
    printf("Allowed\n");
}
Order
Precedence and brackets

C does multiply and divide before add and subtract, like in maths. Do not memorise the whole table. Use brackets to make your meaning clear and correct.

C
int a = 2 + 3 * 4;     // 14, the * happens first
int b = (2 + 3) * 4;   // 20, brackets win
Booleans
True and false in C

C has no separate true or false by default. 0 means false and any other number means true. So if (count) runs whenever count is not zero. If you want the actual words, include and use bool, true and false.

Practice
Work out each by hand, then check in the Lab: a / b, a % b, a + b * 2, (a + b) * 2, (double) a / 2, given int a = 7, b = 3;.
Then write a program that reads a number and says whether it is odd or even.
Why plan
Think before you type

Storing and printing data is half the job. A program becomes useful when it decides and calculates. The students who struggle usually start typing before they know the steps. So we plan first.

An algorithm is just an ordered list of steps that solves a problem, written in plain language before any C. Three tools help: the IPO table, pseudocode and the flowchart.

IPO
Input, Process, Output

Start by asking three questions. What does the program need (input)? What must it do with it (process)? What does it give back (output)?

Example: a final score is 40% of coursework plus 60% of exam. Pass if 50 or more.

InputProcessOutput
coursework mark, exam markfinal = 0.4*cw + 0.6*exam; compare to 50Pass or Fail
Pseudocode
Steps in plain words

Pseudocode writes the steps in short English using a few standard words: INPUT, OUTPUT, SET, IF, ELSE, WHILE. No C syntax, no semicolons, just the logic.

Pseudocode
START
    INPUT coursework, exam
    SET final = 0.4 * coursework + 0.6 * exam
    IF final >= 50 THEN
        OUTPUT "Pass"
    ELSE
        OUTPUT "Fail"
    END IF
END
Flowcharts
The standard symbols

A flowchart draws the same logic. Each shape has a fixed meaning, and arrows show the order.

Flowchart symbols
Start/End terminator Input/Output parallelogram Process rectangle Decision diamond arrow (flow)
Flowcharts
The pass or fail flowchart

Here is the pass/fail algorithm as a flowchart. Follow the arrows. The diamond is the decision, and the two paths join again at the end.

Flowchart: pass or fail
START INPUT cw, exam final = 0.4*cw + 0.6*exam final >= 50 ? yes no OUTPUT Pass OUTPUT Fail END
Desk check
Trace tables: run it by hand

A trace table (or desk check) means pretending to be the computer and writing down the value of every variable after each line. It finds bugs before you ever compile.

Trace this, following each line:

C
int n = 5;
n += 3;   // n = 8
n *= 2;   // n = 16
n--;      // n = 15
n %= 4;   // n = 3
Linen
int n = 5;5
n += 3;8
n *= 2;16
n--;15
n %= 4;3
From plan to code
Turning the algorithm into C

Once the pseudocode is right, the C almost writes itself.

C
#include <stdio.h>

int main(void)
{
    double coursework, exam, final;
    printf("Coursework and exam marks: ");
    scanf("%lf %lf", &coursework, &exam);

    final = 0.4 * coursework + 0.6 * exam;
    if (final >= 50)
        printf("Pass (%.1f)\n", final);
    else
        printf("Fail (%.1f)\n", final);
    return 0;
}
Practice
For a program that reads a price and quantity, applies a 10% discount, and prints the total: write the IPO table, the pseudocode, and draw the flowchart.
Then desk-check it with price 25, quantity 4. This is the shape of Assignment 3 Section C.
Foundations
Three ways a program flows

This is Chapter 4 of your notes. Every program ever written, however large, is built from just three patterns of flow.

PatternMeansEveryday example
Sequencedo steps one after anotherwake, bath, dress, go to class
Selectionchoose steps based on a conditionif it is raining, take an umbrella
Repetitionrepeat steps while a condition holdsthe trotro mate keeps calling Circle while seats are empty

Chapters 2 and 3 only used sequence. This topic adds selection (decisions). The next adds repetition (loops).

Conditions
True and false in C

Every decision rests on a condition, a question that is true or false, like balance > 0 or choice == 2. The rule in C: 0 is false, and anything that is not 0 is true. A comparison produces 1 for true and 0 for false.

C
int age = 20;
printf("%d\n", age >= 18);   // prints 1 (true)
printf("%d\n", age < 18);    // prints 0 (false)
if
Do something only when true

An if runs a block only when its condition is true. If it is false, the block is skipped and the program carries on. Here is the classic MoMo low-balance check from your notes.

C
#include <stdio.h>

int main(void)
{
    float balance;
    printf("Enter your MoMo balance (GHS): ");
    scanf("%f", &balance);

    if (balance < 10.0) {
        printf("Warning: your balance is low.\n");
    }
    printf("Thank you for using MoMo.\n");
    return 0;
}

Run it both ways. The warning only shows when the balance is under 10, but the thank you always prints, because it sits outside the if block.

if-else
Choosing between two paths

A plain if does something or nothing. if-else does one thing when true and a different thing when false. Exactly one block runs, never both. Stack them into an else-if ladder for several bands, like a grader.

C
int score = 72;

if (score >= 80) {
    printf("A\n");
} else if (score >= 70) {
    printf("B\n");
} else if (score >= 50) {
    printf("Pass\n");
} else {
    printf("Fail\n");
}
switch
Menu-driven choices

When you check one value against a few fixed options, switch is cleaner than a long if chain. Each break stops it. default runs if nothing matched. This is how you build a menu.

C
#include <stdio.h>

int main(void)
{
    int choice;
    printf("1 Airtime  2 Data  3 Transfer\nChoose: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1: printf("Buying airtime\n"); break;
        case 2: printf("Buying data\n");    break;
        case 3: printf("Sending transfer\n"); break;
        default: printf("Unknown option\n");
    }
    return 0;
}
Ternary
A one line choice

For a quick either/or, the ternary operator is short. Read it as condition ? value-if-true : value-if-false.

C
int age = 20;
char *status = (age >= 18) ? "adult" : "minor";
printf("%s\n", status);
Style
Braces and indentation

A decision controls one statement. To control several, wrap them in a block with braces { }. A good habit: always use braces, even for one line. It prevents a whole class of bugs. And indent everything inside a block by four spaces. The compiler ignores indentation, but your reader does not, and your course marks down code that is not indented.

Bugs
Decision mistakes that waste hours
Five to watch: = instead of ==; a semicolon right after if (...) which ends the if immediately so the block always runs; missing braces so only the first line is controlled; forgetting break in a switch so cases run together; and comparing decimals with == where tiny rounding makes them unequal.
Practice
Read three numbers and print the largest, using if and else.
Then build the menu from the switch example and respond to each option. This is the Week 5 lab.
while
Repeat while a condition is true

A while loop runs its body again and again, as long as the condition stays true. Something inside must eventually make it false, or it never stops.

C
int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;              // this line ends the loop
}
// 1 2 3 4 5
do-while
Run at least once

A do-while checks the condition at the bottom, so the body always runs at least once. Good for menus and for asking again until the input is valid.

C
int n;
do {
    printf("Enter a positive number: ");
    scanf("%d", &n);
} while (n <= 0);
for
The counting loop

A for loop packs the setup, the condition and the step into one line. Use it when you know how many times to repeat.

C
for (int i = 0; i < 5; i++) {
    printf("%d ", i);
}
int i = 0
start, runs once
i < 5
checked before each pass, stops when false
i++
runs after each pass
break / continue
Leaving early and skipping

break leaves the loop immediately. continue skips to the next pass.

C
for (int i = 1; i <= 10; i++) {
    if (i == 5) break;        // stop at 5
    if (i % 2 == 0) continue; // skip even numbers
    printf("%d ", i);
}
// 1 3
Nested loops
A loop inside a loop

Loops can hold loops. This prints a triangle, a classic lab exercise.

C
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        printf("*");
    }
    printf("\n");
}
Bugs
The three loop traps
An infinite loop because you forgot to update the counter. An off-by-one from <= where you wanted <. And a stray semicolon right after for(...) which makes the body empty.
Practice
Print the times table of a number the user enters, from 1 to 12.
Then compute n factorial with a loop. Then sum the numbers from 1 to n.
Why
Write once, use many times

A function is a named block of code that does one job. You run it by writing its name with parentheses. Functions keep programs short, readable, and easy to fix, because the work lives in one place.

C
int add(int a, int b) {
    return a + b;
}

int total = add(3, 4);   // total is 7
Parameters and return
Inputs and the value handed back

The values in the parentheses of the definition are parameters, the inputs. return hands a value back to whoever called the function. The int in front of the name is the type of that returned value.

A function that does not return anything uses void as its return type.

Declaration
Tell C about a function before you use it

C reads top to bottom, so it must know a function before you call it. Either define the function above main, or put a prototype (the first line with a semicolon) above main and the full code below.

C
#include <stdio.h>

int add(int a, int b);     // prototype

int main(void) {
    printf("%d\n", add(5, 6));
    return 0;
}

int add(int a, int b) {    // definition
    return a + b;
}
Scope
Where a variable lives

A variable made inside a function is local: it exists only inside that function and vanishes when the function ends. That is good, because two functions can both use a variable named i without clashing. A variable declared outside all functions is global and is visible everywhere, but use globals sparingly.

Pass by value
C gives the function a copy

When you pass a variable to a function, C copies it. Changing the copy does not touch your original.

C
void tryChange(int x) { x = 100; }   // only the copy changes

int main(void) {
    int a = 5;
    tryChange(a);
    printf("%d\n", a);   // still 5
}
Pass by reference
Passing the address to change the original

To let a function change your variable, pass its address with &. The function takes a pointer. This is how a working swap is written. You will meet pointers fully in the next topic.

C
void swap(int *a, int *b) {
    int t = *a; *a = *b; *b = t;
}
int main(void) {
    int x = 3, y = 7;
    swap(&x, &y);
    printf("%d %d\n", x, y);   // 7 3
}
Recursion
A function that calls itself

Recursion solves a problem by calling itself on a smaller version. It must have a base case that stops it, or it runs forever and crashes.

C
int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);   // calls itself
}
Math functions
The math.h library

Common maths lives in . Include it and you get square roots, powers and more. On most compilers you link it with -lm when building.

C
#include <math.h>

double r = sqrt(49);     // 7.0
double p = pow(2, 10);   // 1024.0
double up = ceil(3.1);   // 4.0
double dn = floor(3.9);  // 3.0
Good to know
Inline functions and function pointers

Two advanced ideas you will see later, mentioned so the names are not a surprise. An inline function asks the compiler to paste a tiny function in place for speed. A function pointer stores a function in a variable so you can pass it around, like choosing which operation to run at runtime. You do not need these yet.

Practice
Write int isPrime(int n) that returns 1 if n is prime, else 0.
Then write int power(int base, int exp) with a loop, and check it against pow from math.h.
Arrays
A list of values under one name

An array holds many values of the same type. You reach each one by its index, and indexes start at 0. So a size 5 array has indexes 0 to 4.

C
int marks[5];              // 5 ints: marks[0] to marks[4]
marks[0] = 70;
int scores[3] = {90, 80, 75};   // make and fill at once
printf("%d\n", scores[1]);      // 80
Traverse
Walk through with a loop

A for loop is the natural way to visit every element, for example to total marks.

C
int scores[5] = {70, 85, 60, 90, 55};
int total = 0;
for (int i = 0; i < 5; i++) {
    total += scores[i];
}
printf("Average: %d\n", total / 5);
Bounds
C does not check the edges
In a size 5 array, marks[5] is out of range (the last valid index is 4). C will not warn you. It reads or writes the wrong memory and causes a bug that is hard to find. Always stay inside the array.
2D arrays
A grid of rows and columns

A two dimensional array is a table. Good for matrices and seating charts.

C
int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
printf("%d\n", grid[1][2]);   // 6
Strings
Text is an array of characters

A string in C is a char array that ends with a hidden null character '\0'. The word "Hi" is really 'H' 'i' '\0'. That null is how C knows where the text stops.

C
char name[20] = "Kwame";
printf("%s\n", name);   // %s prints a string
User input
Reading words and whole lines

scanf("%s", name) reads one word and stops at the first space, so it cannot read a full name with a space. For a whole line, fgets is safer.

C
char name[30];
printf("Enter your name: ");
fgets(name, 30, stdin);   // reads the whole line, up to 29 characters
string.h
Tools for working with text
FunctionDoes
strlen(s)length of the string
strcpy(a, b)copy b into a
strcmp(a, b)compare, returns 0 if equal
strcat(a, b)join b onto the end of a
You cannot compare strings with == or copy them with =. Use strcmp to compare and strcpy to copy. This catches almost everyone once.
Practice
Read 5 numbers into an array and print them in reverse order.
Then read a word and count how many vowels it contains.
The hard one
What a pointer really is

Picture memory as a long street of numbered houses. Every variable lives in a house, and each house has an address. A pointer is simply a variable that stores an address instead of a normal value.

That is the whole idea. A pointer does not hold 19, it holds where 19 lives. Everything else about pointers follows from that one sentence.

& and *
Address of, and value at

&x is the address of x. If a pointer p holds that address, then *p is the value sitting there.

C
int x = 19;
int *p = &x;        // p holds the address of x

printf("%d\n", x);    // 19   the value
printf("%d\n", *p);   // 19   follow p to the value
*p = 25;              // change x through the pointer
printf("%d\n", x);    // 25
int *p
p is a pointer to an int
p = &x
store the address of x in p
*p
go to that address and use the value
*p = 25
go there and change it, so x becomes 25
Vocabulary
The words to keep straight
Address
where a variable lives in memory. Get it with &.
Pointer
a variable that stores an address.
Dereference
following a pointer to its value, with *.
NULL
a pointer that points at nothing on purpose, and is safe to check for.
The real use
Pass by reference, done right

This is why pointers matter. Because C copies arguments, a plain function cannot change your variable. Pass the address and it can. This is the working swap from the Functions topic.

C
void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}
int main(void) {
    int x = 3, y = 7;
    swap(&x, &y);              // pass the addresses
    printf("%d %d\n", x, y);   // 7 3
}
Arrays
Pointers and arrays are close cousins

The name of an array is the address of its first element. So arr acts like &arr[0], and you can step through with pointer maths.

C
int arr[3] = {10, 20, 30};
printf("%d\n", *arr);         // 10, first element
printf("%d\n", *(arr + 1));   // 20, next one
Crashes
NULL pointers and segmentation faults

A pointer that points nowhere should be set to NULL. If you use a pointer before pointing it somewhere, or you dereference NULL, the program crashes with a segmentation fault. That message means you touched memory you were not allowed to.

Bugs
The three pointer traps
Using a pointer you never pointed anywhere, dereferencing NULL, and mixing up p (the address) with *p (the value). Most crashes come from these three.
Practice
Write swap(int *a, int *b) and use it.
Then write void minMax(int arr[], int n, int *min, int *max) that returns both the smallest and largest through pointers.
struct
Grouping related data

A struct bundles related values into one unit. Instead of three loose variables for a student, you make one Student that holds all three. Reach a member with a dot.

C
struct Student {
    char name[30];
    int id;
    double gpa;
};

struct Student s;
s.id = 101;
s.gpa = 3.8;
printf("%d %.1f\n", s.id, s.gpa);
typedef
A cleaner name

Writing struct Student every time is tiring. typedef lets you write just Student.

C
typedef struct {
    char name[30];
    int id;
    double gpa;
} Student;

Student s;      // no need for the word struct
s.id = 101;
Arrays of structs
A whole class at once

One struct is a student. An array of structs is the class.

C
Student class[3];
class[0].id = 1;
class[1].id = 2;
for (int i = 0; i < 3; i++) {
    printf("ID: %d\n", class[i].id);
}
Structs and pointers
The arrow operator

When you have a pointer to a struct, use -> to reach a member. p->gpa is the short way to write (*p).gpa.

C
Student s;
Student *p = &s;
p->id = 55;        // same as (*p).id = 55
p->gpa = 3.9;
Nested structures
A struct inside a struct

A member of a struct can be another struct. Here a Date lives inside a Student.

C
typedef struct { int day, month, year; } Date;
typedef struct {
    char name[30];
    Date born;
} Student;

Student s;
s.born.year = 2006;   // reach the nested member
Unions
One space, one value at a time

A union looks like a struct, but all its members share the same memory, so it holds only one of them at a time. It saves space when a value could be one of several types. You will not need it often, but you should recognise it.

C
union Value {
    int i;
    float f;
};
union Value v;
v.i = 10;   // using it as an int
enum
Named constants that read well

An enum gives names to a set of related whole numbers, so your code reads in words instead of magic numbers.

C
enum Day { MON, TUE, WED, THU, FRI };
enum Day today = WED;   // WED is really 2

if (today == WED) printf("Midweek\n");
Good to know
Struct padding

If you check sizeof a struct, it may be bigger than the sum of its members. The compiler adds hidden gaps (padding) so each member sits at an address the CPU reads quickly. It is normal and you rarely need to worry about it, but now it will not surprise you.

Practice
Make a Student struct, fill one from user input, and print it back.
Then store 3 students in an array and print the one with the highest GPA.
Stack and heap
Two kinds of memory

Variables you declare normally live on the stack: C creates and frees them for you as functions run. When you do not know how much memory you need until the program runs, you ask for it from the heap, and then you must give it back yourself.

malloc and free
Asking for memory at runtime

malloc asks for a block of memory and gives you a pointer to it. free gives it back. They live in .

C
#include <stdlib.h>

int *nums = malloc(5 * sizeof(int));  // room for 5 ints
if (nums == NULL) { return 1; }       // always check it worked
nums[0] = 10;
free(nums);                           // give it back when done

Related tools: calloc also clears the memory to zero, and realloc resizes a block you already have.

Memory leaks
Forgetting to give it back
Every malloc needs a matching free. If you keep asking for memory and never free it, your program slowly eats all the memory and eventually crashes. This is a memory leak, and your course uses tools like Valgrind to catch them.
Files
Open, use, close

To keep data after the program closes, write it to a file. Open with fopen, giving a mode, and always close with fclose.

ModeMeans
"r"read an existing file
"w"write, creating or erasing the file
"a"append, adding to the end
Always check that fopen did not return NULL before using the file. It may not exist, or may be locked.
Writing
Saving data to a file
C
FILE *f = fopen("students.txt", "w");
if (f == NULL) { printf("Cannot open file\n"); return 1; }
fprintf(f, "Kwame 101 3.8\n");   // like printf, but into the file
fclose(f);
Reading
Loading data back
C
FILE *f = fopen("students.txt", "r");
if (f == NULL) { printf("Cannot open file\n"); return 1; }
char name[30]; int id; double gpa;
fscanf(f, "%s %d %lf", name, &id, &gpa);   // read one record
printf("%s %d %.1f\n", name, id, gpa);
fclose(f);
Practice
Save three student records to a file, then write a second program that reads them back and prints them.
Remember to check fopen and to close the file.
Run it
The live C console

Type C below and press Run. It compiles with real gcc and shows the output, including the errors. Tap a button to load an example, change it, and run again. Needs an internet connection.

C Console
GCC via Wandbox
Program input (optional, one value per line)
Ready
Output
Your output will appear here after you run the code.
Decode the compiler
Common errors and what they mean

When gcc stops, read the first error, not the last. Fixing the first often clears the rest.

MessageMeaningFix
expected ';'missing semicolonadd ; at the end of the line above
undefined reference to mainno main, or misspelleduse int main(void)
implicit declarationused a function before declaring itadd the #include or a prototype
segmentation faulttouched memory you should notcheck pointers and array bounds
format '%d' expects intwrong specifier for the typematch %d, %lf, %c to the value
Practice
A ladder of exercises

Do these in order, in the console. Try before you look anything up.

  1. Print your name, index and programme on three lines.
  2. Read two numbers and print the larger.
  3. Convert a decimal number to binary on paper, then print 0xFF with %d to check your hex.
  4. Read seconds and print hours, minutes and seconds using / and %.
  5. Write the IPO table and pseudocode for a pass/fail grader, then code it.
  6. Print the even numbers from 1 to 20.
  7. Read 5 marks into an array and print the average.
  8. Write a function that returns n factorial.
  9. Swap two numbers using a function with pointers.
  10. Make a Student struct, read one in, and print it.
Where next
After this course

When this feels comfortable, the next steps are data structures (linked lists, stacks, queues), which are built on the pointers and structs you now know, and then one of two directions.

  • C++ and object oriented programming, which extends C.
  • Embedded C for microcontrollers, which is exactly what the Arduino and Electronics course on this site uses.
The Arduino course runs this same C on a real chip. If you enjoyed this, that is the natural next move.