Master the fundamentals of C with clear explanations and hands-on examples
0 / 11 topics completed
01
Introduction to C
C is a powerful, general-purpose programming language developed by Dennis Ritchie at Bell Labs in 1972.
It is one of the most influential languages ever created — the foundation for UNIX, Linux, Windows, and countless other systems.
C combines the efficiency of assembly language with the readability of high-level languages.
Why Learn C?
Foundation of Modern Computing – C influenced C++, Java, Python, and many other languages
Systems Programming – Used for operating systems, embedded systems, and compilers
High Performance – Minimal runtime overhead, direct memory access
Portable – C compilers exist for virtually every platform
Essential for DSA – The language of choice for understanding data structures at a low level
Your first C program is the classic "Hello, World!":
Every C program needs a main() function — it's the entry point. #include <stdio.h> gives access to input/output functions like printf. return 0; signals successful execution.
02
Installation & Setup
To write and run C code, you need a C compiler and a text editor or IDE.
The most common compilers are GCC (GNU Compiler Collection) and Clang.
Installing a Compiler
Linux – Install via package manager: sudo apt install gcc
macOS – Install Xcode Command Line Tools: xcode-select --install
Windows – Download MinGW-w64 or use Visual Studio with the "Desktop development with C++" workload
Bash
# Verify your compiler installation
gcc --version
clang --version
Choosing an IDE
VS Code – Lightweight with C/C++ extension pack (recommended)
Code::Blocks – Free, beginner-friendly IDE
CLion – Full-featured C/C++ IDE by JetBrains
Bash
# Compile and run a C program
gcc hello.c -o hello # compiles to executable
./hello # runs the executable
✅
C is a compiled language: you write .c source files, compile them to a machine-executable binary with gcc, and run the binary directly on your operating system.
03
Variables & Data Types
In C, every variable must have a declared type. C is statically typed — once you declare a variable's type, it cannot hold a different type of value.
C
#include<stdio.h>intmain() {
int age = 25; // Whole numberfloat height = 5.7f; // Decimal number (single precision)double pi = 3.14159; // Decimal number (double precision)char grade = 'A'; // Single characterchar name[] = "Alice"; // String (character array)printf("%d\n", age);
printf("%.1f\n", height);
printf("%c\n", grade);
printf("%s\n", name);
return0;
}
Output
25
5.7
A
Alice
Type
Size
Format Specifier
Description
int
4 bytes
%d
Whole number
float
4 bytes
%f
Single precision decimal
double
8 bytes
%lf
Double precision decimal
char
1 byte
%c
Single ASCII character
void
—
—
No type (for functions)
💡
C does not have a built-in string type. Strings are represented as character arrays (char name[]) terminated by a null character \0. C also supports unsigned variants (unsigned int) and short/long modifiers.
Practice: Variables & Data Types
Create variables of different types and print them:
Create an int variable score with value 95
Create a float variable gpa with value 3.85
Create a char array city[] with value "New York"
Print each variable using printf with the correct format specifier
C uses printf() for output and scanf() for input. Both are defined in the <stdio.h> header and use format specifiers to handle different data types.
printf — Displaying Output
printf("format string", variables) prints formatted text. Common specifiers: %d (int), %f (float), %c (char), %s (string), %lf (double).
C
#include<stdio.h>intmain() {
char name[] = "Alice";
int age = 25;
printf("My name is %s and I am %d years old.\n", name, age);
printf("Name: %s | Age: %d\n", name, age);
return0;
}
Output
My name is Alice and I am 25 years old.
Name: Alice | Age: 25
scanf — Reading User Input
scanf("format", &variable) reads input from the console. The & operator gives the memory address of the variable (required for non-array types).
C
#include<stdio.h>intmain() {
char name[50];
int age;
printf("What is your name? ");
scanf("%s", name);
printf("How old are you? ");
scanf("%d", &age);
printf("Hello, %s! In 10 years you will be %d.\n", name, age + 10);
return0;
}
⚠️
scanf("%s", name) reads only until the first whitespace — it won't read a full name like "John Doe". Use fgets(name, sizeof(name), stdin) to read an entire line including spaces. Always use & before non-array variables in scanf.
Practice: Input & Output
Write a program that asks the user for their name and favorite color, then prints a greeting.
Include <stdio.h>
Ask for name and favorite color using scanf
Print: "Hello {name}, your favorite color is {color}!"
C
#include<stdio.h>intmain() {
char name[50];
char color[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your favorite color: ");
scanf("%s", color);
printf("Hello %s, your favorite color is %s!\n", name, color);
return0;
}
05
Operators
Operators perform operations on variables and values. C supports arithmetic, assignment, comparison, logical, and bitwise operators.
Category
Operators
Example
Arithmetic
+ - * / %
10 + 5 → 15
Assignment
= += -= *= /= %=
x += 5
Comparison
== != < > <= >=
10 > 5 → 1 (true)
Logical
&& || !
1 && 0 → 0
Increment/Decrement
++ --
i++
Bitwise
& | ^ ~ << >>
5 & 3 → 1
C
#include<stdio.h>intmain() {
int a = 10, b = 5;
// Arithmeticint sum = a + b;
int product = a * b;
int remainder = a % b;
// Comparison & Logicalint isGreater = a > b;
int bothPositive = (a > 0) && (b > 0);
printf("Sum: %d\n", sum);
printf("Product: %d\n", product);
printf("Remainder: %d\n", remainder);
printf("Is a > b? %d\n", isGreater);
printf("Both positive? %d\n", bothPositive);
return0;
}
Output
Sum: 15
Product: 50
Remainder: 0
Is a > b? 1
Both positive? 1
Practice: Operators
Calculate the area and perimeter of a rectangle with width 8 and length 12.
Create int variables width and length
Calculate area = width * length
Calculate perimeter = 2 * (width + length)
Print both results using printf
C
#include<stdio.h>intmain() {
int width = 8;
int length = 12;
int area = width * length;
int perimeter = 2 * (width + length);
printf("Area: %d\n", area);
printf("Perimeter: %d\n", perimeter);
return0;
}
06
Conditional Statements
Conditionals let your program make decisions. C supports if, else if, else, and switch statements.
In C, conditions evaluate to 0 (false) or non-zero (true).
while checks the condition first; do-while runs the body at least once.
C
#include<stdio.h>intmain() {
// while loopint count = 0;
while (count < 5) {
printf("While: %d\n", count);
count++;
}
// do-while loopint num = 0;
do {
printf("Do-while: %d\n", num);
num++;
} while (num < 5);
return0;
}
⚠️
Always ensure your loop condition eventually becomes 0 (false) to avoid infinite loops. Use break to exit early and continue to skip the current iteration.
Practice: Loops
Write two programs:
Use a for loop to print all even numbers from 2 to 20
Use a while loop to calculate the sum of numbers from 1 to 100
C
#include<stdio.h>intmain() {
// Even numbers 2-20for (int i = 2; i <= 20; i += 2) {
printf("%d\n", i);
}
// Sum of 1 to 100int sum = 0;
int n = 1;
while (n <= 100) {
sum += n;
n++;
}
printf("Sum: %d\n", sum);
return0;
}
08
Functions
Functions (also called procedures) are reusable blocks of code. They help you avoid repetition and organize your program into logical pieces.
In C, every function has a return type, a name, and parameters.
C
#include<stdio.h>// Function declaration (prototype)intadd(int a, int b);
voidgreet(char name[]);
// Function definitionsintadd(int a, int b) {
return a + b;
}
voidgreet(char name[]) {
printf("Hello, %s!\n", name);
}
intmain() {
int sum = add(10, 5);
printf("Sum: %d\n", sum);
greet("Alice");
return0;
}
Output
Sum: 15
Hello, Alice!
Function Prototypes
In C, you must declare a function before you call it. A prototype tells the compiler about the function's return type and parameters. You can then define the function later in the file (or in another file).
Practice: Functions
Write a function int square(int n) that returns n * n
Write a function int isEven(int n) that returns 1 if n is even, 0 otherwise
Call both functions from main() and print the results
Create an array of 5 integers and calculate their sum using a for loop
Write code to count how many vowels are in a given string
C
#include<stdio.h>#include<string.h>intmain() {
// Sum of arrayint nums[] = {10, 20, 30, 40, 50};
int sum = 0;
int len = sizeof(nums) / sizeof(nums[0]);
for (int i = 0; i < len; i++) {
sum += nums[i];
}
printf("Sum: %d\n", sum);
// Count vowelschar str[] = "hello world";
int vowels = 0;
for (int i = 0; i < strlen(str); i++) {
char c = str[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
printf("Vowels: %d\n", vowels);
return0;
}
10
Pointers Basics
A pointer is a variable that stores the memory address of another variable. Pointers are one of C's most powerful features — they give you direct access to memory and enable dynamic memory allocation.
Pointer Syntax
int *ptr; — declares a pointer to an integer
&variable — gets the memory address of a variable
*ptr — dereferences a pointer (accesses the value at the address)
C
#include<stdio.h>intmain() {
int x = 42;
int *ptr = &x; // ptr stores the address of xprintf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Value of ptr: %p\n", ptr);
printf("Value at ptr: %d\n", *ptr); // dereference// Modify x through the pointer
*ptr = 100;
printf("New value of x: %d\n", x);
return0;
}
Output
Value of x: 42
Address of x: 0x16f0a3c1c
Value of ptr: 0x16f0a3c1c
Value at ptr: 42
New value of x: 100
Pointers and Arrays
Array names are essentially pointers to the first element. arr[i] is equivalent to *(arr + i).
C
#include<stdio.h>intmain() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // p points to arr[0]printf("First element: %d\n", *p);
printf("Second element: %d\n", *(p + 1));
printf("Third element: %d\n", *(p + 2));
// Loop using pointer arithmeticfor (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, *(p + i));
}
return0;
}
⚠️
Always make sure a pointer points to a valid memory address before dereferencing it. Dangling pointers (pointers to freed or invalid memory) and NULL pointer dereferencing are common sources of bugs and crashes in C.
Practice: Pointers
Declare an int variable and a pointer to it
Use the pointer to change the variable's value
Print the variable's value before and after the change
C
#include<stdio.h>intmain() {
int num = 50;
int *ptr = #
printf("Before: %d\n", num);
*ptr = 500;
printf("After: %d\n", num);
printf("Via pointer: %d\n", *ptr);
return0;
}
11
Structures (struct)
A struct (short for structure) is a user-defined data type that groups related variables of different types together under one name.
Structures are C's way of creating custom data types before C++ introduced classes.
C
#include<stdio.h>#include<string.h>// Define a structstructStudent {
char name[50];
int age;
float gpa;
};
intmain() {
// Create a struct variablestructStudent student1;
// Assign valuesstrcpy(student1.name, "Alice");
student1.age = 20;
student1.gpa = 3.85f;
// Access members using dot operatorprintf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("GPA: %.2f\n", student1.gpa);
return0;
}
Output
Name: Alice
Age: 20
GPA: 3.85
typedef — Creating Type Aliases
The typedef keyword lets you create an alias for a struct, so you don't have to type struct every time.
Use the dot operator (.) to access struct members. For pointers to structs, use the arrow operator (→): ptr->name is equivalent to (*ptr).name. Structs can also contain pointers as members — this is the foundation for linked lists and other dynamic data structures.
Practice: Structures
Define a Rectangle struct with width and height (both int). Write a function that takes a Rectangle and returns its area. Create a rectangle and print its area.
C
#include<stdio.h>typedef struct {
int width;
int height;
} Rectangle;
intgetArea(Rectangle r) {
return r.width * r.height;
}
intmain() {
Rectangle rect = {10, 5};
printf("Area: %d\n", getArea(rect));
return0;
}
12
C Learning Playground
Ready to practice what you've learned? Use our interactive C editor to write, compile, and run your code directly in the browser.
Interactive C Editor
Test pointers, structs, and loops with real-time output.