⚡ C Programming Complete Tutorial
Clear definitions · Syntax explained · Real code examples
CHAPTER 1
C Intro & Get Started
📖 Definition: C is a general-purpose, procedural programming language developed by Dennis Ritchie in 1972 at Bell Labs. It is a mid-level language that combines high-level language features with low-level memory manipulation capabilities.
Why Learn C? C is the foundation of many modern languages (C++, C#, Java, Python). It gives you direct control over memory, making it ideal for operating systems, embedded systems, game engines, and performance-critical applications.
📝 Basic Program Structure:
#include <stdio.h>
int main() {
// Your code here
return 0;
}
▶ Example: Hello World
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}Output: Hello, World!
💡 To compile:
To run:
gcc program.c -o programTo run:
./program (Linux/Mac) or program.exe (Windows)CHAPTER 2
Syntax & Output
📖 Definition: Syntax refers to the set of rules that defines the structure of a C program. Every C program follows a specific format with headers, main function, statements, and comments.
📝 Output Functions Syntax:
printf("format string", arguments);
▶ Output Examples
#include <stdio.h>
int main() {
// Single line comment
/* Multi-line
comment */
printf("Plain text\n");
printf("Number: %d\n", 42); // %d for integers
printf("Float: %.2f\n", 3.14159); // %f for float, .2 for 2 decimals
printf("Char: %c\n", 'A'); // %c for character
printf("String: %s\n", "Hello"); // %s for string
printf("Pointer: %p\n", &main); // %p for memory address
return 0;
}Plain text
Number: 42
Float: 3.14
Char: A
String: Hello
Pointer: 0x10xxxxx
Number: 42
Float: 3.14
Char: A
String: Hello
Pointer: 0x10xxxxx
CHAPTER 3
Variables & Data Types
📖 Definition: A variable is a named storage location in memory that holds a value. Variables must be declared with a data type before use. Data types define the type of data a variable can store and the operations that can be performed on it.
📝 Variable Declaration Syntax:
data_type variable_name; data_type variable_name = initial_value;
▶ Variables Example
#include <stdio.h>
int main() {
// Declaration and initialization
int age = 25;
float price = 19.99f;
double pi = 3.14159265359;
char grade = 'A';
// Variable naming rules: letters, digits, underscore, cannot start with digit
int student_age = 20; // snake_case
int _counter = 0; // underscore allowed
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("PI: %.10lf\n", pi);
printf("Grade: %c\n", grade);
printf("Size of int: %lu bytes\n", sizeof(int));
return 0;
}CHAPTER 4
Constants & Type Conversion
📖 Definition: Constants are fixed values that cannot be changed during program execution. Type conversion is the process of converting one data type to another.
📝 Constants Syntax:
#define CONSTANT_NAME value // Preprocessor constant const data_type name = value; // const keyword📝 Type Casting Syntax:
(target_type) expression
▶ Constants & Type Conversion
#include <stdio.h>
#define PI 3.14159
#define MAX_STUDENTS 100
int main() {
const int DAYS_IN_WEEK = 7;
// Implicit conversion (automatic)
int x = 10;
double y = x; // int to double
// Explicit casting (manual)
int a = 5, b = 2;
float result = (float)a / b; // 2.5, not 2
// Character to integer
char ch = 'B';
int ascii = (int)ch; // 66
printf("PI: %f\n", PI);
printf("Days: %d\n", DAYS_IN_WEEK);
printf("Division: %.1f\n", result);
printf("ASCII of B: %d\n", ascii);
return 0;
}CHAPTER 5
Operators & Booleans
📖 Definition: Operators are symbols that perform operations on operands. C has arithmetic, relational, logical, assignment, bitwise, and ternary operators.
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + – * / % ++ — | a + b, a++ |
| Relational | == != > < >= <= | a > b |
| Logical | && || ! | (a > 5 && b < 10) |
| Assignment | = += -= *= /= | a += 5 (a = a + 5) |
| Ternary | ? : | condition ? value1 : value2 |
▶ Operators Example
#include <stdio.h>
#include <stdbool.h>
int main() {
int a = 10, b = 3;
// Arithmetic
printf("a + b = %d\n", a + b); // 13
printf("a - b = %d\n", a - b); // 7
printf("a * b = %d\n", a * b); // 30
printf("a / b = %d\n", a / b); // 3 (integer division)
printf("a %% b = %d\n", a % b); // 1 (remainder)
// Increment/Decrement
int count = 5;
printf("count++ = %d\n", count++); // 5 (post-increment)
printf("count = %d\n", count); // 6
// Logical operators
bool result = (a > 5 && b < 5);
printf("AND result: %d\n", result); // 1 (true)
// Ternary operator
int max = (a > b) ? a : b;
printf("Max: %d\n", max); // 10
return 0;
}CHAPTER 6
If/Else & Switch Statements
📖 Definition: Conditional statements control the flow of program execution based on conditions. if-else executes different code blocks based on boolean conditions. switch is used for multi-way branching based on a single expression.
📝 Syntax:
if (condition) {
// code if true
} else if (condition) {
// code for second condition
} else {
// code if all false
}
switch(expression) {
case value1: // code; break;
case value2: // code; break;
default: // code;
}
▶ Conditional Examples
#include <stdio.h>
int main() {
int score = 85;
// if-else ladder
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n"); // This executes
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
// Switch statement
int day = 3;
switch(day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}
// Nested if
int age = 18;
int hasID = 1;
if (age >= 18) {
if (hasID) {
printf("Access granted\n");
}
}
return 0;
}CHAPTER 7
Loops: while, for, do-while
📖 Definition: Loops repeatedly execute a block of code while a condition is true. While loops check condition before execution, do-while checks after (executes at least once), for loops are used when the number of iterations is known.
▶ Loop Examples
#include <stdio.h>
int main() {
// While loop - checks condition first
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
} // Output: 1 2 3 4 5
printf("\n");
// For loop - initialization; condition; increment
for (int j = 0; j < 5; j++) {
printf("%d ", j);
} // Output: 0 1 2 3 4
printf("\n");
// Do-while loop - executes at least once
int k = 10;
do {
printf("Executed once: %d\n", k);
k++;
} while (k < 10);
// Break and Continue
for (int x = 1; x <= 10; x++) {
if (x == 5) {
continue; // Skip 5
}
if (x > 8) {
break; // Stop after 8
}
printf("%d ", x); // 1 2 3 4 6 7 8
}
return 0;
}CHAPTER 8
Arrays
📖 Definition: An array is a collection of elements of the same data type stored in contiguous memory locations. Array indices start at 0.
📝 Array Syntax:
data_type array_name[size];
data_type array_name[] = {value1, value2, ...};
array_name[index] = value;
▶ Array Examples
#include <stdio.h>
int main() {
// One-dimensional array
int numbers[5] = {10, 20, 30, 40, 50};
numbers[2] = 35; // Modify element at index 2
printf("Element at index 2: %d\n", numbers[2]); // 35
// Loop through array
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
} // 10 20 35 40 50
printf("\n");
// Two-dimensional array (matrix)
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("matrix[1][2] = %d\n", matrix[1][2]); // 6
// Array size calculations
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]); // 5
printf("Array length: %d\n", length);
return 0;
}CHAPTER 9
Strings
📖 Definition: In C, a string is a null-terminated character array. The null character '\0' marks the end of the string.
▶ String Examples
#include <stdio.h>
#include <string.h>
int main() {
// Declaring strings
char str1[] = "Hello"; // Size determined automatically
char str2[20] = "World"; // Fixed size
char str3[10] = {'C', ' ', 'O', 'K', '\0'}; // Character array with null terminator
// String functions (from string.h)
char name[50];
strcpy(name, "Alice"); // Copy string
strcat(name, " Smith"); // Concatenate
printf("Length: %lu\n", strlen(name)); // 11 (without null)
printf("Name: %s\n", name);
// Compare strings
char pass1[] = "secret";
char pass2[] = "secret";
if (strcmp(pass1, pass2) == 0) {
printf("Passwords match\n");
}
// String input (safe)
char input[100];
printf("Enter text: ");
fgets(input, sizeof(input), stdin); // Safer than gets()
// Remove newline from fgets
input[strcspn(input, "\n")] = 0;
printf("You entered: %s\n", input);
return 0;
}CHAPTER 10
User Input (scanf & fgets)
📖 Definition: User input functions allow programs to read data from the keyboard. scanf reads formatted input, while fgets reads a line of text safely.
▶ User Input Examples
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
printf("Enter your age: ");
scanf("%d", &age); // & is address-of operator
printf("Enter your height (meters): ");
scanf("%f", &height);
getchar(); // Consume leftover newline
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Name: %sAge: %d, Height: %.2fm\n", name, age, height);
// Multiple inputs in one line
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum: %d\n", a + b);
return 0;
}CHAPTER 11
Pointers & Memory Address
📖 Definition: A pointer is a variable that stores the memory address of another variable. The & operator gets the address, and the * operator dereferences (accesses the value at the address).
📝 Pointer Syntax:
data_type *pointer_name = &variable; // Declaration and initialization *pointer_name = value; // Dereferencing to assign value
▶ Pointer Examples
#include <stdio.h>
int main() {
int var = 42;
int *ptr = &var; // ptr stores address of var
printf("Value of var: %d\n", var); // 42
printf("Address of var: %p\n", &var); // Memory address
printf("Value of ptr: %p\n", ptr); // Same address
printf("Dereferenced ptr: %d\n", *ptr); // 42
// Modify variable through pointer
*ptr = 100;
printf("New value of var: %d\n", var); // 100
// NULL pointer (good practice)
int *nullPtr = NULL;
if (nullPtr == NULL) {
printf("Pointer is NULL - don't dereference!\n");
}
// Pointer arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int *arrPtr = arr; // Points to first element
printf("First element: %d\n", *arrPtr); // 10
printf("Second element: %d\n", *(arrPtr + 1)); // 20
return 0;
}💡 Pointers are powerful but dangerous. Always initialize pointers and check for NULL before dereferencing!
CHAPTER 12
Functions & Parameters
📖 Definition: A function is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and enable modular programming.
▶ Function Examples
#include <stdio.h>
// Function declaration (prototype)
int add(int a, int b);
void swap(int *x, int *y);
int factorial(int n);
int main() {
int result = add(5, 3);
printf("Sum: %d\n", result); // 8
int a = 10, b = 20;
swap(&a, &b);
printf("Swapped: a=%d, b=%d\n", a, b); // a=20, b=10
printf("Factorial 5: %d\n", factorial(5)); // 120
return 0;
}
// Function definition (pass by value)
int add(int a, int b) {
return a + b;
}
// Pass by reference using pointers
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
// Recursive function
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}CHAPTER 13
Structures (struct)
📖 Definition: A structure is a user-defined data type that groups related variables of different data types together as a single unit.
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student s1 = {"Alice", 20, 3.8};
struct Student *ptr = &s1;
printf("Name: %s, Age: %d\n", s1.name, s1.age);
printf("Via pointer: %s\n", ptr->name); // Arrow operator
return 0;
}CHAPTER 14
File Handling
FILE *fptr = fopen("data.txt", "w");
if (fptr != NULL) {
fprintf(fptr, "Writing to file\n");
fclose(fptr);
}
fptr = fopen("data.txt", "r");
char buffer[100];
while (fgets(buffer, sizeof(buffer), fptr)) {
printf("%s", buffer);
}
fclose(fptr);CHAPTER 15
Dynamic Memory Allocation
int *arr = (int*)malloc(5 * sizeof(int));
if (arr != NULL) {
for (int i = 0; i < 5; i++) arr[i] = i * 10;
free(arr); // Always free allocated memory!
arr = NULL;
}✅ You've completed the C tutorial! Practice each concept with your own examples.