🖥️ C Programming Guide

Master Procedural Programming

Introduction to C Programming

C is a powerful procedural programming language that forms the foundation of modern computing. This guide covers all fundamental concepts you need to master C programming.

1. Basic Structure of a C Program

Every C program follows a standard structure:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
Note: The main() function is the entry point of every C program. Execution always begins here.

2. Variables and Data Types

C is a statically-typed language. You must declare variables before using them.

Primitive Data Types

Type Size Description Example
int 4 bytes Integer numbers int age = 25;
float 4 bytes Single precision decimal float pi = 3.14;
double 8 bytes Double precision decimal double price = 99.99;
char 1 byte Single character char grade = 'A';

Variable Declaration and Initialization

int x;          // Declaration
x = 10;         // Assignment
int y = 20;     // Declaration + Initialization

const int MAX = 100;  // Constant (cannot be changed)

3. Operators

Arithmetic Operators

int a = 10, b = 3;
int sum = a + b;        // Addition: 13
int diff = a - b;       // Subtraction: 7
int product = a * b;    // Multiplication: 30
int quotient = a / b;   // Division: 3
int remainder = a % b;  // Modulus: 1

Comparison Operators

a == b    // Equal to
a != b    // Not equal to
a > b     // Greater than
a < b     // Less than
a >= b    // Greater than or equal to
a <= b    // Less than or equal to

Logical Operators

&&    // AND
||    // OR
!     // NOT

4. Control Structures

If-Else Statements

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");
}

Switch Statement

char grade = 'B';

switch(grade) {
    case 'A':
        printf("Excellent!\n");
        break;
    case 'B':
        printf("Good job!\n");
        break;
    case 'C':
        printf("Average\n");
        break;
    default:
        printf("Invalid grade\n");
}
Important: Always use break in switch cases to prevent fall-through behavior!

5. Loops

For Loop

// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
// Output: 1 2 3 4 5

While Loop

int count = 1;
while (count <= 5) {
    printf("%d ", count);
    count++;
}

Do-While Loop

int num = 1;
do {
    printf("%d ", num);
    num++;
} while (num <= 5);
Tip: Use do-while when you need to execute the loop body at least once, regardless of the condition.

6. Functions

Functions allow you to organize code into reusable blocks.

Function Declaration and Definition

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

// Function definition
int add(int a, int b) {
    return a + b;
}

// Function call
int main() {
    int result = add(5, 3);
    printf("Sum: %d\n", result);
    return 0;
}

Void Functions

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

int main() {
    greet("Alice");
    return 0;
}

Recursion

// Factorial using recursion
int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main() {
    printf("5! = %d\n", factorial(5));  // Output: 120
    return 0;
}

7. Arrays

One-Dimensional Arrays

// Declaration and initialization
int numbers[5] = {10, 20, 30, 40, 50};

// Accessing elements
printf("First element: %d\n", numbers[0]);

// Iterating through array
for (int i = 0; i < 5; i++) {
    printf("%d ", numbers[i]);
}

Two-Dimensional Arrays

int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Accessing elements
printf("Element at [1][2]: %d\n", matrix[1][2]);  // Output: 6

8. Pointers

Pointers are one of the most powerful features in C. They store memory addresses.

Basic Pointer Usage

int x = 10;
int *ptr = &x;  // ptr stores the address of x

printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Value stored in ptr: %p\n", ptr);
printf("Value pointed to by ptr: %d\n", *ptr);

Pointer Arithmetic

int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

printf("%d\n", *p);      // 10
printf("%d\n", *(p+1));  // 20
printf("%d\n", *(p+2));  // 30

Pointers and Functions

// Pass by reference using pointers
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);  // x = 10, y = 5
    return 0;
}
Important: Always initialize pointers before using them. Uninitialized pointers can cause segmentation faults!

9. Strings

In C, strings are arrays of characters terminated by a null character '\0'.

#include <string.h>

char name[20] = "Alice";
char greeting[50];

// String functions
strcpy(greeting, "Hello");       // Copy string
strcat(greeting, " World");      // Concatenate
int len = strlen(greeting);      // Get length
int cmp = strcmp("abc", "abc");  // Compare strings (0 if equal)

10. Structures

Structures allow you to group related data together.

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

int main() {
    struct Student s1;
    
    strcpy(s1.name, "John");
    s1.age = 20;
    s1.gpa = 3.8;
    
    printf("Name: %s\n", s1.name);
    printf("Age: %d\n", s1.age);
    printf("GPA: %.2f\n", s1.gpa);
    
    return 0;
}

11. Dynamic Memory Allocation

#include <stdlib.h>

int *arr;
int n = 5;

// Allocate memory
arr = (int*)malloc(n * sizeof(int));

if (arr == NULL) {
    printf("Memory allocation failed!\n");
    return 1;
}

// Use the array
for (int i = 0; i < n; i++) {
    arr[i] = i * 10;
}

// Free memory when done
free(arr);
Important: Always free dynamically allocated memory to prevent memory leaks!

12. File I/O

Writing to a File

FILE *file = fopen("output.txt", "w");

if (file == NULL) {
    printf("Error opening file!\n");
    return 1;
}

fprintf(file, "Hello, File!\n");
fprintf(file, "Line 2\n");

fclose(file);

Reading from a File

FILE *file = fopen("input.txt", "r");
char buffer[100];

if (file == NULL) {
    printf("Error opening file!\n");
    return 1;
}

while (fgets(buffer, 100, file) != NULL) {
    printf("%s", buffer);
}

fclose(file);

Key Takeaways