1. Home
  2. Explore
  3. Computer Science
  4. C Programming Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

C Programming Fundamentals

C Programming Fundamentals: Study Notes

1. C and the Programming Process

C is a general-purpose programming language that has been used for many decades. Many later languages, including C++, share ideas and syntax with C, so learning C provides a useful foundation for studying programming more broadly.

A C program is a set of instructions that a computer carries out. C code is written in a form that people can read and work with, but the computer must first translate it into a form it can execute. This translation is performed by a compiler.

A basic C development setup has two parts:

  • A text editor or IDE for writing and organizing source code.

  • A C compiler for translating that code into an executable program.

An IDE, or integrated development environment, combines a text editor with tools for building, running, and managing programs. Code::Blocks is one example. An IDE is convenient, but C programs can also be written in a plain text editor and compiled separately.

Setting up a C environment

The exact setup depends on the operating system.

  • Windows: Code::Blocks can be installed with the MinGW setup package, which includes the IDE and a GCC compiler. During the first launch, the GNU GCC compiler can be selected as the default compiler.

  • macOS: The Xcode Command Line Tools provide a C compiler. The compiler can be checked from Terminal with cc -v. If the tools are missing, xcode-select --install installs them. Code::Blocks can then be installed as an IDE.

  • Linux: A C compiler and an editor or IDE can be installed using the operating system’s package-management tools.

The compiler and IDE serve different purposes: the IDE helps manage source code and development tasks, while the compiler translates C code into a program the computer can run.


2. C Projects, Source Files, and Program Execution

A C project groups the files and settings needed to build a program. In Code::Blocks, a basic starting point is a console application, which runs in a text-based console window. A project typically contains a source folder and a file such as main.c.

The main function

Execution of a standard C program begins in the main function. A simplified program may look like this:

#include <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    return 0;
}

The braces mark the body of a function. Instructions inside main are executed when the program starts. In the example, printf displays text.

The #include line makes declarations from a library available to the program. For example, <stdio.h> provides declarations for standard input/output functions such as printf and scanf.

Building and running

Writing code and executing it are distinct stages:

  1. Build or compile: The compiler checks and translates the source code.

  2. Run: The resulting executable is started by the operating system.

An IDE may offer a combined Build and Run command that performs both stages. Compilation errors must be corrected before a program can be built successfully.

A console window displays output produced by a program. If a program does not print anything, the console may appear empty even though the program ran.

Instructions, order, and semicolons

C statements are generally executed in order, from top to bottom. Changing the order can change the program’s output and behavior.

Most C statements end with a semicolon. It marks the end of a statement, allowing the compiler to distinguish one instruction from the next.

For example, two print statements execute in sequence:

printf("First line\n");
printf("Second line\n");

The newline escape sequence \n moves subsequent output to a new line.


3. Variables and Data Types

A variable is a named storage location used to hold information while a program runs. Variables make it easier to reuse and update data. If a value is used repeatedly, it can be stored once in a variable rather than typed directly into every statement that needs it.

For example, a program can store a person’s name and age in variables, then use those variables when printing a story. Changing the value in one place updates every later use of that variable.

A variable declaration specifies its type and its name. It may also assign an initial value:

int age = 35;

Here, int is the type and age is the variable name. The equals sign assigns the initial value.

Common C data types

Integers: int

An integer represents a whole number, without a fractional part.

int age = 40;

Integer literals are written without quotation marks. The value 40 is an integer, while 40.0 is a floating-point value.

Floating-point numbers: double and float

A floating-point type represents numbers with a fractional or decimal part.

double gpa = 3.7;
float temperature = 21.5f;

double generally provides more precision than float and is a common choice for decimal values. A floating-point value can also represent a whole-number amount with a decimal point, such as 3.0.

Characters: char

A character variable stores a single character. Character literals use single quotation marks:

char grade = 'A';

A single char cannot hold a whole word or phrase.

Strings and character arrays

C does not have a built-in string type in the same sense as some other languages. A string is represented as an array of characters ending with a special null character, written '\0'.

char name[] = "John";

The array must have room for all the characters and the terminating null character. For example, a four-letter name needs at least five character positions when stored as a C string.

A fixed-size character array can be declared when space is needed for input:

char name[20];

This provides room for up to 19 ordinary characters plus the null terminator.

Unlike a single numeric variable, an array cannot generally be assigned a new string using = after it has been declared. String-handling functions or explicit character copying are used instead.


4. Printing Output with printf

The printf function writes formatted output, typically to the console. It can display ordinary text, values stored in variables, or a mixture of both.

printf("Hello, world!\n");

Text to be printed is placed inside double quotation marks. Special characters can be included using escape sequences:

  • \n inserts a newline.

  • \" inserts a quotation mark inside a string.

Format specifiers

A format specifier is a placeholder in a printf format string. It identifies the kind of value that should appear at that position.

Common specifiers include:

  • %d for an integer.

  • %f for a floating-point value.

  • %c for a single character.

  • %s for a null-terminated string.

For example:

int count = 500;
printf("The count is %d.\n", count);

The %d placeholder is replaced by the value of count.

Multiple values can be printed in a single call. The order of the values after the format string must match the order of the placeholders:

char name[] = "Mina";
int age = 24;

printf("%s is %d years old.\n", name, age);

For a double, %f is used with printf. The default formatting may show more decimal places than needed. Precision can be controlled, for example, with %.2f to display two digits after the decimal point.


5. Working with Numbers

C supports arithmetic operations on numeric values:

  • Addition: +

  • Subtraction: -

  • Multiplication: *

  • Division: /

These operations can be used with literal values or variables.

double result = 5.0 + 4.5;

Integer and floating-point arithmetic

The types involved in an operation affect the result.

  • Operations involving integers commonly produce an integer result.

  • When an integer is combined with a floating-point value, the integer is converted to a floating-point value for the operation, and the result is floating-point.

  • Integer division discards the fractional part. For instance, dividing the integer 5 by the integer 4 produces the integer 1, not 1.25.

  • To obtain a fractional result, at least one operand should be floating-point, such as 5.0 / 4.

Mathematical functions

C’s math library provides functions for common calculations, including:

  • pow(x, y): raises x to the power of y.

  • sqrt(x): returns the square root of x.

  • ceil(x): rounds upward to the smallest integer-valued number not less than x.

  • floor(x): rounds downward to the greatest integer-valued number not greater than x.

These functions are declared in <math.h>. Some development environments also require linking the math library when building a program.


6. Comments and Constants

Comments

A comment is text in source code that the compiler ignores. Comments can explain code or temporarily disable a section during testing.

A block comment begins with /* and ends with */:

/* This is a comment.
   It can span multiple lines. */

Comments are useful for recording information that is not obvious from the code. They can also temporarily “comment out” code without deleting it. Comments should remain clear and purposeful so they help readers understand the program rather than clutter it.

Constants

A constant is a value that should not be changed during program execution. The const qualifier makes a declared variable read-only after initialization:

const int MAX_SCORE = 100;

An attempt to modify MAX_SCORE later in the program produces a compilation error.

Uppercase names are often used by convention for constants, especially when the name contains multiple words, as in MAX_SCORE. This naming style is a convention, not a requirement.

Literal values such as 77 or "Hello" are also fixed values in the source code, but the const qualifier is used when a named variable should not be reassigned.


7. Getting Input from the User

Programs can obtain information from the user, store it in variables, and then use it in calculations or output.

Using scanf

The scanf function reads formatted input. Its format string describes the expected input, and its remaining arguments identify where the input should be stored.

For basic values, the address-of operator & is generally needed:

int age;
scanf("%d", &age);

Common scanf specifiers include:

  • %d for an int.

  • %lf for a double.

  • %f for a float.

  • %c for a char.

  • %s for a sequence of non-whitespace characters.

For example, this pattern prompts for and reads an integer:

printf("Enter your age: ");
scanf("%d", &age);

The ampersand in &age supplies the address of the variable so that scanf can store the input there. Character arrays used with %s are an exception: the array name itself refers to the array’s starting location, so an ampersand is not normally used.

A leading space in a character format, such as " %c", tells scanf to skip whitespace left over from earlier input. This can prevent a newline from being read as the character.

Reading strings and whitespace

With %s, scanf stops reading at whitespace. Thus, input such as John Smith is read only as John.

For a line of text that may include spaces, fgets is usually a more suitable choice:

char name[20];

printf("Enter your name: ");
fgets(name, sizeof name, stdin);

fgets reads at most the specified capacity minus one characters and adds a null terminator. It can also retain a newline if the user presses Enter and there is room for it. Programs often remove that newline when they need to work with the text without it.

Input should be bounded to the available array size. Otherwise, a program can overwrite memory beyond the array. Input handling also needs to account for invalid or unexpected input; a simple example that assumes valid numeric input may not handle a word entered where a number is expected.


8. Small Input-Based Programs

A basic calculator

A basic calculator can:

  1. Prompt for two numbers.

  2. Read them into numeric variables.

  3. Perform an arithmetic operation.

  4. Print the result.

Using double values allows the calculator to handle decimal numbers. The operator can be stored in a char, such as '+', '-', '*', or '/'.

The scanf format for reading a double is %lf, while printf uses %f to display a double. This difference is important: the format specifiers depend on whether the function is reading or printing.

A minimal calculator may still need additional safeguards. For instance, it should validate input and check that the divisor is not zero before dividing.

A Mad Libs-style program

A Mad Libs program collects words from the user and inserts them into a story. It illustrates how input, variables, and formatted output work together.

The program can use character arrays for words such as a color, a plural noun, and a name, then print those values in a prepared sentence. If scanf("%s", ...) is used, each input stops at the first space. A full name therefore requires a line-reading approach such as fgets, or separate variables for first and last names.


9. Arrays

An array is a group of values of the same type stored under one name. It is useful when a program needs to manage many related values without declaring a separate variable for every value.

An array can be initialized with a list of values:

int lucky_numbers[] = {4, 8, 15, 16, 23, 42};

Array elements are separated by commas. The compiler can determine the number of elements from the initializer.

An array can also be declared with a fixed capacity without initializing every element:

int numbers[10];

This reserves space for 10 integers. When an array is not initialized, its elements should not be assumed to contain meaningful values.

Indexing

Each array element is accessed using an index in square brackets. In C, indexing begins at zero:

  • The first element is at index 0.

  • The second element is at index 1.

  • The last element of an array with six elements is at index 5.

For example, lucky_numbers[0] refers to 4, and lucky_numbers[2] refers to 15.

An element can be read or assigned individually:

lucky_numbers[1] = 200;

C does not automatically prevent access outside an array’s valid index range. Accessing an invalid index can cause undefined behavior, so array bounds must be tracked carefully.

A C string is a character array with a null terminator. This is why strings and general arrays share similar indexing behavior, even though C provides convenient string literals and string functions.


10. Functions, Parameters, and Return Values

A function is a named block of code designed to perform a particular task. Functions help organize programs, reduce repeated code, and separate a program into manageable parts.

The main function is the program’s entry point. Other functions must be called to execute their bodies.

void say_hi(void)
{
    printf("Hello!\n");
}

This function has a void return type, meaning it does not return a value. It can be called from main:

say_hi();

Defining a function does not execute it; calling the function does. When a function call occurs, control moves to the function’s body, executes its statements, and then returns to the point after the call.

Parameters

A parameter is a named input specified in a function definition. The values supplied when calling the function are called arguments.

void say_hi(char name[])
{
    printf("Hello, %s!\n", name);
}

The function can be called with different arguments:

say_hi("Mina");
say_hi("Omar");

A function may accept multiple parameters of different types. The number, order, and types of arguments in a call must match the function’s declaration.

Return types and return statements

A function can return information to the code that called it. Its return type specifies the type of value it returns. The return statement sends that value back and ends execution of that function.

double cube(double number)
{
    return number * number * number;
}

A returned value can be used in an expression or passed directly to another function:

printf("%.2f\n", cube(3.0));

A function declared as void does not return a value. A function declared with a non-void return type should return a value of the appropriate type along every path that reaches the end.

Function declarations and prototypes

A function must be declared before it is used, so the compiler knows its return type and parameters. One option is to define the function before main. Another is to place a function prototype above main and the full definition later:

double cube(double number);

int main(void)
{
    printf("%.2f\n", cube(3.0));
    return 0;
}

double cube(double number)
{
    return number * number * number;
}

The prototype gives the function’s signature—its return type, name, and parameter types—without providing its body.


11. Conditional Logic: if, else, and Comparison Operators

An if statement allows a program to make a decision. It evaluates a condition and executes one block of code if the condition is true. An else block provides an alternative when the condition is false.

if (num1 > num2) {
    result = num1;
} else {
    result = num2;
}

An else if branch checks an additional condition when earlier conditions were false. This can be used to compare several cases in sequence.

Comparison operators

Common comparison operators include:

  • > greater than

  • < less than

  • >= greater than or equal to

  • <= less than or equal to

  • == equal to

  • != not equal to

The double equals sign, ==, tests equality. A single equals sign, =, assigns a value.

Logical operators

Logical operators combine or modify conditions:

  • && means logical AND. Both conditions must be true for the combined condition to be true.

  • || means logical OR. At least one condition must be true.

  • ! means logical NOT. It reverses a condition’s truth value.

For example, a function that finds the largest of three numbers can check whether the first number is at least as large as both others:

if (num1 >= num2 && num1 >= num3) {
    result = num1;
} else if (num2 >= num1 && num2 >= num3) {
    result = num2;
} else {
    result = num3;
}

Conditions can be combined to express more complex decision rules. Parentheses can make complicated conditions easier to read.


12. switch Statements

A switch statement compares one expression against a set of possible constant values. It is often clearer than a long sequence of if and else if branches when checking one value against several alternatives.

switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
        printf("Good\n");
        break;
    case 'F':
        printf("Failing\n");
        break;
    default:
        printf("Unknown grade\n");
        break;
}

Each case identifies a possible value. The break statement exits the switch after the matching case runs. Without a break, execution continues into the following case; this behavior is called fall-through and is usually unintended in beginner examples.

The optional default branch runs when no case matches. A switch is particularly suitable for checking a single integer or character value against several alternatives. It does not replace if statements for every situation; if is more flexible for ranges and compound conditions.


13. Structures

A structure, declared with struct, groups related values that may have different types. This makes it possible to represent a real-world entity with several attributes, such as a student’s name, major, age, and GPA.

struct Student {
    char name[50];
    char major[50];
    int age;
    double gpa;
};

The structure definition describes the fields that every Student value contains. It acts as a template; it does not by itself create a particular student.

A variable of that structure type can be declared as follows:

struct Student student1;

Individual fields are accessed with the dot operator:

student1.age = 22;
student1.gpa = 3.2;

Character arrays cannot be assigned to directly with = after declaration. A string-copy function such as strcpy, declared in <string.h>, can copy text into a character array, provided that the destination array has enough room:

strcpy(student1.name, "Jim");
strcpy(student1.major, "Business");

Structures allow multiple records of the same form to be created, each with its own field values. For example, student1 and student2 can each contain a name, major, age, and GPA. Structure values can be passed to functions, stored in arrays, and used in other parts of a program.


14. while and do-while Loops

A loop repeats a block of code while a condition is true.

while loop

A while loop checks its condition before each iteration:

int index = 1;

while (index <= 5) {
    printf("%d\n", index);
    index++;
}

The process is:

  1. Check whether the condition is true.

  2. If it is true, execute the loop body.

  3. Update the relevant values.

  4. Check the condition again.

  5. Stop when the condition becomes false.

If the condition is false before the first check, the body does not run.

do-while loop

A do-while loop executes the body before checking its condition. Therefore, its body runs at least once:

do {
    printf("%d\n", index);
    index++;
} while (index <= 5);

A semicolon follows the condition of a do-while loop. This loop is useful when an operation must happen at least once, such as prompting for input before checking whether the user should be prompted again.

Infinite loops

An infinite loop occurs when a loop’s condition never becomes false. A common cause is failing to update the variable that the condition depends on. For example, if index is never incremented in while (index <= 5), the condition remains true and the program keeps looping.

Infinite loops are sometimes intentional, but accidental ones can make a program appear frozen or consume resources. Loop variables and exit conditions should be checked carefully.


15. A Guessing Game: Combining Loops, Conditions, and Variables

A number-guessing game demonstrates how variables, input, loops, and conditional logic work together.

A basic version stores a secret number and repeatedly asks for a guess until the user enters the correct value:

int secret_number = 5;
int guess;

while (guess != secret_number) {
    printf("Enter a number: ");
    scanf("%d", &guess);
}

printf("You win!\n");

In a complete program, guess should be initialized or assigned before it is tested. The loop continues while the guess does not equal the secret number. After the correct guess, the condition becomes false and the program continues after the loop.

Limiting the number of guesses

A guess limit can be added using additional variables:

  • A guess count tracks how many attempts have been made.

  • A guess limit stores the maximum number of attempts.

  • A flag can track whether the user has run out of guesses.

The program increments the guess count each time an attempt is made. It then checks whether the count has reached the limit and whether the guess is correct. The final outcome depends on which condition ends the loop: a correct guess means a win, while reaching the limit without guessing correctly means a loss.

A flag represented as 0 or 1 can work, but C also provides the Boolean type through <stdbool.h>, using bool, true, and false.


16. for Loops and Array Traversal

A for loop is especially useful when the number of iterations is known or when a counting variable is needed. Its header contains three parts:

for (initialization; condition; update) {
    /* repeated statements */
}
  • Initialization: Runs once before the loop begins.

  • Condition: Checked before each iteration.

  • Update: Runs after each iteration.

For example:

for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}

This loop initializes i, repeats while the condition is true, and increments i after each iteration. The expression i++ increases i by one. Similar shorthand includes i-- to decrease by one.

A for loop can perform the same tasks as a while loop. Its main advantage is that initialization, continuation condition, and update are grouped in one place.

Traversing an array

Since array indices begin at zero, a loop that visits each element of an array with six elements can use indices from 0 through 5:

int lucky_numbers[] = {4, 8, 15, 16, 23, 42};

for (int i = 0; i < 6; i++) {
    printf("%d\n", lucky_numbers[i]);
}

The condition uses i < 6, not i <= 6, because index 6 would be beyond the end of a six-element array. In general, an array of length nnn has valid indices from 000 through n−1n - 1n−1.


17. Two-Dimensional Arrays and Nested Loops

A two-dimensional array is an array whose elements are themselves arrays. It can be thought of as a grid of rows and columns. A declaration and initialization can look like this:

int nums[3][2] = {
    {1, 2},
    {3, 4},
    {5, 6}
};

This array has three rows and two columns. An element requires two indices:

nums[0][0]   /* first row, first column */
nums[1][1]   /* second row, second column */

Both indices begin at zero. The first index selects the inner array, or row; the second selects an element within that row.

A nested loop is a loop inside another loop. It is useful for processing every element in a two-dimensional array:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        printf("%d ", nums[i][j]);
    }
    printf("\n");
}

For each value of i, the inner loop runs through all values of j. The outer loop selects each row; the inner loop visits every column in that row. Nested loops are commonly used with grids, tables, and other multidimensional data.


18. Memory Addresses and Pointers

When a program creates a variable, its value is stored in the computer’s memory. The variable name gives the program a convenient way to refer to that value, while the value’s memory address identifies where it is stored.

The address-of operator, &, obtains the address of a variable. The %p format specifier displays a pointer value:

int age = 30;
printf("%p\n", (void *)&age);

Memory addresses are commonly displayed in hexadecimal form. They can differ between program runs, computers, and execution environments.

A pointer is a variable that stores a memory address. A pointer’s declared type indicates the kind of object it is intended to point to:

int *p_age = &age;
double *p_gpa;
char *p_grade;

Here, p_age can point to an int, p_gpa to a double, and p_grade to a char. The asterisk in a declaration indicates a pointer type. It is not the same operation as multiplication, although it uses the same symbol.

An ampersand is used to obtain the address of an ordinary variable. The pointer stores that address, allowing the program to refer to the variable indirectly.


19. Dereferencing Pointers

Dereferencing a pointer means accessing the value stored at the address held by that pointer. The unary * operator is used for dereferencing.

int age = 30;
int *p_age = &age;

printf("%d\n", *p_age);

The expression p_age is the address of age; the expression *p_age is the integer value stored at that address. In this example, dereferencing the pointer produces 30.

The type of a dereferenced pointer is the type of the object it points to. Therefore, an int * dereferences to an int, while a double * dereferences to a double.

Pointers must refer to valid objects before they are dereferenced. Dereferencing an uninitialized pointer or an invalid address can cause undefined behavior. Pointers are useful in C for indirect access to data, modifying values through functions, working with arrays and dynamically allocated memory, and representing relationships between data.


20. Reading and Writing Files

C programs can create files, write information to them, add information to existing files, and read information back. File operations commonly use the FILE type and functions declared in <stdio.h>.

Opening a file

fopen opens a file and returns a file pointer:

FILE *file_pointer = fopen("employees.txt", "w");

The first argument is the file name or path. The second argument is the file mode, which specifies the intended operation.

Common modes include:

  • "r": read an existing file.

  • "w": write to a file, creating it if needed and replacing existing contents.

  • "a": append to a file, creating it if needed and writing at the end.

If no path is supplied, the file is typically created or searched for relative to the program’s working directory. The exact working directory depends on how the program is launched.

A robust program checks whether fopen succeeded before using the returned pointer, since the operation can fail.

Writing and appending

fprintf writes formatted text to a file. It is similar to printf, but it receives a file pointer as its first argument:

fprintf(file_pointer, "Jim, sales\n");
fprintf(file_pointer, "Pam, reception\n");

With "w" mode, existing contents are replaced. With "a" mode, new text is added to the end of the file. A newline should be included when each entry is intended to appear on a separate line.

Files should be closed after use:

fclose(file_pointer);

Closing a file releases resources and ensures that buffered output is flushed to the file.

Reading lines with fgets

A file opened in "r" mode can be read with fgets. It reads up to a specified number of characters, stops at a newline or the size limit, and stores the result in a character array:

char line[255];

while (fgets(line, sizeof line, file_pointer) != NULL) {
    printf("%s", line);
}

Each successful call reads the next part of the file, so repeated calls progress through successive lines. The function returns NULL when no further line can be read, which makes it suitable as the condition of a reading loop.

As with user input, the buffer size limits how much text can be read at once. The program should also check that the file opened successfully and close it when reading is complete.


Key Relationships to Remember

  • A compiler translates C source code into an executable program; building and running are separate stages.

  • The main function is the standard entry point for execution.

  • Variables store values, and their data types determine what those values represent.

  • printf displays formatted output; scanf reads formatted input.

  • Arrays store multiple values of the same type, with indices beginning at zero.

  • Functions organize reusable tasks, accept parameters, and can return values.

  • Conditionals select behavior based on tests; loops repeat behavior while conditions hold.

  • Structures group related fields that can have different types.

  • Pointers store memory addresses, and dereferencing accesses the value at an address.

  • File functions provide ways to create, write, append, read, and close files.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent