C Basics

First C Program

// Simple Hello World program
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
Note: Every C program must have a main() function as the entry point.

Data Types & Variables

// Basic data types
int age = 25; // Integer
float salary = 2500.50; // Single precision
double pi = 3.14159; // Double precision
char grade = 'A'; // Character

// Type modifiers
short int smallNumber; // Typically 2 bytes
long int bigNumber; // Typically 4+ bytes
unsigned int positive; // Only positive values

// Constants
const float TAX_RATE = 0.15;
#define PI 3.14159

Operators

// Arithmetic operators
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b;// 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1

// Relational operators
int result = (a == b); // 0 (false)
result = (a != b); // 1 (true)
result = (a > b); // 1 (true)

// Logical operators
int x = 1, y = 0;
result = (x && y); // 0 (false)
result = (x || y); // 1 (true)
result = !x; // 0 (false)

Basic I/O

#include <stdio.h>

int main() {
    int age;
    float height;
    char name[50];

    // Output
    printf("Enter your name: ");

    // Input
    scanf("%s", name);
    printf("Enter your age and height: ");
    scanf("%d %f", &age, &height);

    // Formatted output
    printf("Hello %s, you are %d years old and %.2f feet tall\n",
        name, age, height);

    return 0;
}

Control Flow

Conditional Statements

// if statement
if (score >= 90) {
    printf("Grade: A\n");
}

// if-else statement
if (temperature > 30) {
    printf("It's hot outside\n");
} else {
    printf("It's not too hot\n");
}

// if-else if ladder
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

// switch statement
switch (day) {
    case 1: printf("Monday\n"); break;
    case 2: printf("Tuesday\n"); break;
    // ... other cases
    default: printf("Invalid day\n");
}

Loops

// for loop
for (int i = 0; i < 10; i++) {
    printf("%d ", i);
}
printf("\n");

// while loop
int count = 0;
while (count < 5) {
    printf("Count: %d\n", count);
    count++;
}

// do-while loop
int num;
do {
    printf("Enter a positive number: ");
    scanf("%d", &num);
} while (num <= 0);

// break and continue
for (int i = 0; i < 10; i++) {
    if (i == 3) continue; // Skip 3
    if (i == 7) break; // Exit at 7
    printf("%d ", i);
}

Arrays & Strings

Arrays

// Array declaration and initialization
int numbers[5]; // Uninitialized array
int primes[5] = {2, 3, 5, 7, 11};
int values[] = {1, 2, 3, 4, 5}; // Size automatically set to 5

// Accessing array elements
primes[0] = 2; // First element
primes[4] = 11; // Last element (5 elements, index 0-4)

// Multi-dimensional arrays
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Accessing 2D array
int value = matrix[1][2]; // value = 6

// Array traversal
for (int i = 0; i < 5; i++) {
    printf("%d ", primes[i]);
}

Strings

#include <string.h>

// String declaration and initialization
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char name[] = "John Doe"; // Automatically null-terminated
char input[100];

// String input/output
printf("Enter your name: ");
scanf("%s", input); // Reads until whitespace
printf("Hello, %s!\n", input);

// String functions
int length = strlen(name);
strcpy(input, name); // Copy name to input
strcat(greeting, " "); // Concatenate
strcat(greeting, name);

int result = strcmp(name, "John");
// result == 0 if equal, <0 if name < "John", >0 if name > "John"

Functions

Function Basics

#include <stdio.h>

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

int main() {
    int result = add(5, 3);
    printf("5 + 3 = %d\n", result);
    printMessage();
    return 0;
}

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

void printMessage() {
    printf("Hello from function!\n");
}

Parameter Passing

// Pass by value (default)
void swapByValue(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

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

int main() {
    int x = 5, y = 10;
    
    // This won't change x and y
    swapByValue(x, y);
    printf("After swapByValue: x=%d, y=%d\n", x, y);
    
    // This will change x and y
    swapByReference(&x, &y);
    printf("After swapByReference: x=%d, y=%d\n", x, y);
    
    return 0;
}

Pointers

Pointer Basics

int var = 10;

// Pointer declaration and initialization
int *ptr; // Pointer to integer
ptr = &var; // Stores address of var

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

// Changing value through pointer
*ptr = 20;
printf("New value of var: %d\n", var);

// Pointer arithmetic
ptr++; // Moves to next integer (4 bytes on most systems)
printf("Value of ptr after increment: %p\n", ptr);

// Pointer to pointer
int **pptr = &ptr;
printf("Value of pptr: %p\n", pptr);
printf("Value pointed by pptr: %p\n", *pptr);
printf("Value pointed by *pptr: %d\n", **pptr);

Pointers & Arrays

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

// Array name is a pointer to first element
int *ptr = arr; // Equivalent to &arr[0]

// Accessing array elements using pointers
printf("First element: %d\n", *ptr);
printf("Second element: %d\n", *(ptr + 1));
printf("Third element: %d\n", *(ptr + 2));

// Array indexing vs pointer arithmetic
printf("arr[2] = %d\n", arr[2]);
printf("*(arr + 2) = %d\n", *(arr + 2));

// Pointer to array
int (*parr)[5] = &arr;
printf("First element via parr: %d\n", (*parr)[0]);

// Array of pointers
int *ptrArr[5];
for (int i = 0; i < 5; i++) {
    ptrArr[i] = &arr[i];
}

Structures & Unions

Structures

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

// Declaring structure variables
struct Student student1;
struct Student student2 = {"John Doe", 20, 3.8};

// Accessing structure members
strcpy(student1.name, "Jane Smith");
student1.age = 21;
student1.gpa = 3.9;

printf("Student: %s, Age: %d, GPA: %.2f\n",
    student1.name, student1.age, student1.gpa);

// Pointers to structures
struct Student *ptr = &student1;
printf("Name via pointer: %s\n", (*ptr).name);
printf("Name via arrow: %s\n", ptr->name);

// typedef for structures
typedef struct Student Student;
Student student3; // Now we can use Student directly

Unions & Enums

// Union definition (shares memory space)
union Data {
    int i;
    float f;
    char str[20];
};

union Data data;

data.i = 10;
printf("data.i = %d\n", data.i);

data.f = 220.5;
printf("data.f = %.2f\n", data.f);

// Note: Only one member can contain a value at a time

// Enumeration definition
enum Weekday {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
};

enum Weekday today = WEDNESDAY;
printf("Today is day number %d\n", today);

// Typedef with enum
typedef enum Weekday Weekday;
Weekday tomorrow = THURSDAY;