C Programming Documentation
Comprehensive guide to C programming language
What is C Programming?
C is a general-purpose programming language created by Dennis Ritchie at Bell Laboratories in 1972. It is a structured, procedural language that has influenced many other programming languages and is still widely used today for system programming, embedded systems, and application development.
History of C
- 1972: C was developed by Dennis Ritchie at Bell Labs
- 1978: Brian Kernighan and Dennis Ritchie published "The C Programming Language" (K&R C)
- 1989: ANSI C standard (X3.159-1989) was published
- 1999: ISO C standard (C99) was published
- 2011: ISO C standard (C11) was published
- 2018: ISO C standard (C18) was published
Features of C
- Fast and Efficient: C programs are known for their speed and efficiency
- Close to Hardware: Provides low-level access to memory and system resources
- Portable: C code can be compiled on various platforms with minimal changes
- Extensible: Rich set of libraries and functions
- Structured: Supports structured programming concepts
- Flexible: Can be used for both low-level and high-level programming
Applications of C
- Operating Systems (Unix, Linux, Windows)
- Embedded Systems
- Database Systems
- Game Development
- Scientific Computing
- Network Drivers
- Robotics
Setting Up C Development Environment
# Install MinGW-w64 (Minimalist GNU for Windows)
# Download from: https://www.mingw-w64.org/downloads/
# Add MinGW-w64 bin directory to PATH
# Example: C:\mingw64\bin
# Verify installation
gcc --version
Alternatively, you can use an IDE like Code::Blocks, Dev-C++, or Visual Studio with C support.
# Install GCC (GNU Compiler Collection)
sudo apt-get update
sudo apt-get install build-essential
# Verify installation
gcc --version
# Install text editor (optional)
sudo apt-get install vim
sudo apt-get install code
# Install Xcode Command Line Tools
xcode-select --install
# Install Homebrew (package manager)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install GCC
brew install gcc
# Verify installation
gcc --version
Your First C Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
# Compile the program
gcc hello.c -o hello
# Run the program
./hello
Data Types in C
C provides several built-in data types to store different kinds of data:
| Data Type | Size (bytes) | Range | Description |
|---|---|---|---|
| char | 1 | -128 to 127 | Single character |
| unsigned char | 1 | 0 to 255 | Single character (positive only) |
| short | 2 | -32,768 to 32,767 | Short integer |
| unsigned short | 2 | 0 to 65,535 | Short integer (positive only) |
| int | 4 | -2,147,483,648 to 2,147,483,647 | Integer |
| unsigned int | 4 | 0 to 4,294,967,295 | Integer (positive only) |
| long | 4 or 8 | System dependent | Long integer |
| unsigned long | 4 or 8 | System dependent | Long integer (positive only) |
| float | 4 | ±3.4e±38 (7 digits) | Single-precision floating point |
| double | 8 | ±1.7e±308 (15 digits) | Double-precision floating point |
| long double | 10 or more | System dependent | Extended-precision floating point |
Variables in C
Variables are named storage locations in memory. Before using a variable, you must declare it with its type and optionally initialize it.
#include <stdio.h>
int main() {
// Variable declaration and initialization
int age = 25;
float salary = 50000.50;
char grade = 'A';
double pi = 3.14159265359;
// Multiple variable declaration
int x, y, z;
float a, b;
// Declaration with initialization
int count = 0;
float temperature = 98.6;
char initial = 'J';
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);
printf("Pi: %.10f\n", pi);
return 0;
}
Constants
#include <stdio.h>
#define PI 3.14159265359
#define MAX_SIZE 100
int main() {
const int MAX_AGE = 120;
const float GRAVITY = 9.8;
float radius = 5.0;
float area = PI * radius * radius;
printf("Area of circle: %.2f\n", area);
printf("Maximum age: %d\n", MAX_AGE);
printf("Gravity constant: %.1f\n", GRAVITY);
return 0;
}
Operators in C
C provides a rich set of operators to manipulate variables and values.
| Operator Type | Operators | Description |
|---|---|---|
| Arithmetic | + - * / % ++ -- | Mathematical operations |
| Relational | == != > < >= <= | Comparison operations |
| Logical | && || ! | Boolean operations |
| Assignment | = += -= *= /= %= | Assignment operations |
| Bitwise | & | ^ ~ << >> | Bit-level operations |
#include <stdio.h>
int main() {
int a = 10, b = 3;
// Arithmetic operators
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
// Relational operators
printf("a == b: %d\n", a == b);
printf("a != b: %d\n", a != b);
printf("a > b: %d\n", a > b);
// Logical operators
int x = 1, y = 0;
printf("x && y: %d\n", x && y);
printf("x || y: %d\n", x || y);
printf("!x: %d\n", !x);
// Assignment operators
a += 5;
printf("a after += 5: %d\n", a);
// Bitwise operators
unsigned int p = 60, q = 13;
printf("p & q: %u\n", p & q);
printf("p | q: %u\n", p | q);
return 0;
}
Control Structures in C
Control structures determine the flow of execution in a program.
if-else Statements
#include <stdio.h>
int main() {
int age = 18;
// Simple if statement
if (age >= 18) {
printf("You are eligible to vote.\n");
}
// if-else statement
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
// if-else if-else statement
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
switch Statement
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Loops
#include <stdio.h>
int main() {
// for loop
printf("For loop: ");
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
// while loop
printf("While loop: ");
int j = 1;
while (j <= 5) {
printf("%d ", j);
j++;
}
printf("\n");
// do-while loop
printf("Do-while loop: ");
int k = 1;
do {
printf("%d ", k);
k++;
} while (k <= 5);
printf("\n");
// Loop control statements
printf("Loop with break and continue: ");
for (int i = 1; i <= 10; i++) {
if (i == 5) continue;
if (i == 8) break;
printf("%d ", i);
}
printf("\n");
return 0;
}
Functions in C
Functions are blocks of code that perform specific tasks and help in code organization and reuse.
#include <stdio.h>
// Function declaration (prototype)
int add(int a, int b);
void greet();
// Function definition
int add(int a, int b) {
return a + b;
}
void greet() {
printf("Hello, World!\n");
}
// Function with no return value and parameters
void printDetails(char name[], int age) {
printf("Name: %s\n", name);
printf("Age: %d\n", age);
}
// Recursive function
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
// Calling functions
greet();
int sum = add(5, 3);
printf("Sum: %d\n", sum);
printDetails("John", 25);
int fact = factorial(5);
printf("Factorial of 5: %d\n", fact);
return 0;
}
Function Parameters and Return Types
#include <stdio.h>
// Different return types
float calculateArea(float radius) {
return 3.14159 * radius * radius;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
float radius = 5.0;
float area = calculateArea(radius);
printf("Area: %.2f\n", area);
int x = 10, y = 20;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After swap: x=%d, y=%d\n", x, y);
return 0;
}
Arrays in C
Arrays are collections of elements of the same data type stored in contiguous memory locations.
#include <stdio.h>
int main() {
// One-dimensional array
int numbers[5] = {1, 2, 3, 4, 5};
printf("Array elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Two-dimensional array
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("2D Array:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Strings in C
#include <stdio.h>
#include <string.h>
int main() {
// String declaration
char greeting[] = "Hello, World!";
char name[50];
// String functions
printf("String: %s\n", greeting);
printf("Length: %zu\n", strlen(greeting));
// String copy
strcpy(name, "John Doe");
printf("Name: %s\n", name);
// String concatenation
strcat(name, " - Programmer");
printf("Full name: %s\n", name);
// String comparison
char str1[] = "apple";
char str2[] = "banana";
if (strcmp(str1, str2) < 0) {
printf("%s comes before %s\n", str1, str2);
} else {
printf("%s comes after %s\n", str1, str2);
}
return 0;
}
Pointers in C
Pointers are variables that store memory addresses of other variables.
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value pointed by ptr: %d\n", *ptr);
// Modifying value through pointer
*ptr = 20;
printf("New value of num: %d\n", num);
// Pointer arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int *arrPtr = arr;
printf("Array elements using pointer: ");
for (int i = 0; i < 5; i++) {
printf("%d ", *(arrPtr + i));
}
printf("\n");
return 0;
}
Pointers and Functions
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
int main() {
int x = 10, y = 20;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After swap: x=%d, y=%d\n", x, y);
int numbers[] = {1, 2, 3, 4, 5};
printf("Array: ");
printArray(numbers, 5);
return 0;
}
Structures in C
Structures allow you to combine data items of different kinds.
#include <stdio.h>
#include <string.h>
// Structure definition
struct Person {
char name[50];
int age;
float height;
};
// typedef with structure
typedef struct {
char street[100];
char city[50];
int zip;
} Address;
int main() {
// Structure variable declaration and initialization
struct Person person1;
strcpy(person1.name, "John Doe");
person1.age = 25;
person1.height = 5.8;
printf("Person: %s, %d years, %.1f feet\n",
person1.name, person1.age, person1.height);
// Structure pointer
struct Person *personPtr = &person1;
printf("Using pointer: %s\n", personPtr->name);
// Array of structures
struct Person people[3] = {
{"Alice", 30, 5.6},
{"Bob", 35, 5.9},
{"Charlie", 28, 5.7}
};
printf("\nPeople array:\n");
for (int i = 0; i < 3; i++) {
printf("%s, %d years\n", people[i].name, people[i].age);
}
return 0;
}
Unions in C
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 3.14;
printf("data.f: %.2f\n", data.f);
strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str);
printf("Size of union: %zu bytes\n", sizeof(union Data));
return 0;
}
File Handling in C
C provides functions for reading from and writing to files.
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
// Writing to a file
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(file, "Hello, File Handling!\n");
fprintf(file, "This is a test file.\n");
fclose(file);
// Reading from a file
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
printf("File contents:\n");
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
Binary File Operations
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student students[3] = {
{1, "Alice", 85.5},
{2, "Bob", 92.0},
{3, "Charlie", 78.5}
};
FILE *file;
// Write binary data
file = fopen("students.dat", "wb");
if (file != NULL) {
fwrite(students, sizeof(struct Student), 3, file);
fclose(file);
}
// Read binary data
struct Student readStudents[3];
file = fopen("students.dat", "rb");
if (file != NULL) {
fread(readStudents, sizeof(struct Student), 3, file);
fclose(file);
printf("Student data:\n");
for (int i = 0; i < 3; i++) {
printf("ID: %d, Name: %s, Marks: %.1f\n",
readStudents[i].id, readStudents[i].name, readStudents[i].marks);
}
}
return 0;
}
Dynamic Memory Allocation
C provides functions for dynamic memory allocation and deallocation.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
// Memory allocation using malloc
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Store values in allocated memory
for (int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
// Print the values
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
// Free allocated memory
free(ptr);
// Using calloc (initializes to zero)
int *ptr2 = (int*)calloc(5, sizeof(int));
printf("Calloc initialized array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", ptr2[i]);
}
printf("\n");
// Using realloc
ptr2 = (int*)realloc(ptr2, 10 * sizeof(int));
for (int i = 5; i < 10; i++) {
ptr2[i] = i + 1;
}
printf("After realloc: ");
for (int i = 0; i < 10; i++) {
printf("%d ", ptr2[i]);
}
printf("\n");
free(ptr2);
return 0;
}
Memory Management Best Practices
#include <stdio.h>
#include <stdlib.h>
void safeMemoryAllocation() {
int *ptr = NULL;
// Always check if allocation was successful
ptr = (int*)malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return;
}
// Use the allocated memory
for (int i = 0; i < 5; i++) {
ptr[i] = (i + 1) * 10;
}
// Print values
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
// Free memory and set pointer to NULL
free(ptr);
ptr = NULL;
}
int main() {
safeMemoryAllocation();
return 0;
}