> For the complete documentation index, see [llms.txt](https://cs.d19.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cs.d19.in/cheatsheet.md).

# Cheatsheet

### 1. Introduction to C Programming

C is a general-purpose programming language developed in the 1970s by Dennis Ritchie. It is widely used for system programming, developing operating systems, embedded systems, and more due to its powerful low-level capabilities.

#### Features of C

* **Simple and Efficient**: Basic and understandable syntax that is easy to write and compile.
* **Low-Level Access**: Provides low-level manipulation of data, which is ideal for system programming.
* **Rich Library Support**: Provides a variety of inbuilt functions.
* **Portable**: Code can be compiled and run on different platforms without modifications.
* **Structured Programming**: Supports modularity through functions and block-structured programming.

#### Basic Structure of a C Program

```c
#include <stdio.h> // Header files

int main() {
    // Statements
    return 0;
}
```

* **Header Files**: Include libraries like `<stdio.h>`, `<stdlib.h>`, etc.
* **Main Function**: The entry point of any C program (`int main()`).
* **Statements**: C statements end with a semicolon (`;`).

### 2. Data Types and Variables

#### Primary Data Types

* **int**: Integer data type (`int age = 20;`).
* **float**: Single-precision floating-point (`float price = 12.99;`).
* **double**: Double-precision floating-point (`double distance = 123.456;`).
* **char**: Character data type (`char letter = 'A';`).

#### Derived Data Types

* **Arrays**: Collection of elements of the same type (`int arr[5] = {1, 2, 3, 4, 5};`).
* **Pointers**: Stores the memory address of another variable (`int *ptr = &age;`).
* **Structures**: Group of variables of different types (`struct { int id; char name[20]; } person;`).
* **Unions**: Like structures but share memory (`union { int i; float f; } u;`).
* **Enums**: Enumeration constants (`enum Days { MON, TUE, WED };`).

#### Variable Declaration

* **Syntax**: `data_type variable_name;`
* **Example**: `int a = 10;`

#### Constants

* Use `const` keyword: `const float PI = 3.14159;`
* Preprocessor Directive: `#define MAX 100`

### 3. Input and Output in C

#### Standard Input/Output Functions

* **printf()**: Used for output.

  ```c
  printf("Hello, %s!\n", name);
  ```
* **scanf()**: Used for input.

  ```c
  scanf("%d", &age);
  ```

  * `%d` for integers
  * `%f` for floats
  * `%c` for characters
  * `%s` for strings

#### Escape Sequences

* : Newline
* : Tab
* **\\**: Backslash
* **"**: Double quote

### 4. Control Flow

#### Conditional Statements

* **if Statement**

  ```c
  if (a > b) {
      printf("a is greater than b\n");
  }
  ```
* **if-else Statement**

  ```c
  if (a > b) {
      printf("a is greater\n");
  } else {
      printf("b is greater\n");
  }
  ```
* **Nested if Statement**

  ```c
  if (a > b) {
      if (a > c) {
          printf("a is largest\n");
      }
  }
  ```
* **else if Ladder**

  ```c
  if (a == 10) {
      // code
  } else if (a == 20) {
      // code
  } else {
      // default code
  }
  ```

#### Switch Case

* **Syntax**

  ```c
  switch (expression) {
      case value1:
          // code
          break;
      case value2:
          // code
          break;
      default:
          // default code
  }
  ```
* Use **break** to prevent fall-through behavior.

#### Looping Statements

* **for Loop**

  ```c
  for (int i = 0; i < 10; i++) {
      printf("%d\n", i);
  }
  ```
* **while Loop**

  ```c
  int i = 0;
  while (i < 10) {
      printf("%d\n", i);
      i++;
  }
  ```
* **do-while Loop**

  ```c
  int i = 0;
  do {
      printf("%d\n", i);
      i++;
  } while (i < 10);
  ```

#### Control Statements

* **break**: Exit the loop.
* **continue**: Skip to the next iteration of the loop.
* **return**: Exit from a function.

### 5. Operators in C

#### Arithmetic Operators

* **Addition (`+`)**: `a + b`
* **Subtraction (`-`)**: `a - b`
* **Multiplication (`*`)**: `a * b`
* **Division (`/`)**: `a / b`
* **Modulus (`%`)**: `a % b`

#### Relational Operators

* **Equal (`==`)**: `a == b`
* **Not Equal (`!=`)**: `a != b`
* **Greater Than (`>`)**: `a > b`
* **Less Than (`<`)**: `a < b`
* **Greater Than or Equal To (`>=`)**: `a >= b`
* **Less Than or Equal To (`<=`)**: `a <= b`

#### Logical Operators

* **AND (`&&`)**: `(a > b) && (a < c)`
* **OR (`||`)**: `(a > b) || (a < c)`
* **NOT (`!`)**: `!(a > b)`

#### Bitwise Operators

* **AND (`&`)**: Bitwise AND
* **OR (`|`)**: Bitwise OR
* **XOR (`^`)**: Bitwise XOR
* **NOT (`~`)**: Bitwise NOT
* **Left Shift (`<<`)**: `a << 1`
* **Right Shift (`>>`)**: `a >> 1`

#### Assignment Operators

* `=`: Assign value to a variable (`a = 5;`)
* `+=`: Add and assign (`a += 5;`)
* `-=`: Subtract and assign (`a -= 5;`)
* `*=`: Multiply and assign (`a *= 5;`)
* `/=`: Divide and assign (`a /= 5;`)
* `%=`: Modulus and assign (`a %= 5;`)

#### Miscellaneous Operators

* **Sizeof**: Returns the size of a data type (`sizeof(int)`)
* **Conditional (Ternary) Operator**: `condition ? value_if_true : value_if_false`

### 6. Functions in C

#### Types of Functions

* **Library Functions**: Predefined functions like `printf()`, `scanf()`, etc.
* **User-defined Functions**: Functions created by the programmer.
* **Recursive Functions**: Functions that call themselves (`factorial()` example).

#### Syntax of a Function

```c
return_type function_name(parameter_list) {
    // Function body
    return value;
}
```

* **Example**

  ```c
  int add(int x, int y) {
      return x + y;
  }
  ```

#### Function Declaration

* **Prototype**: `int add(int, int);`
* **Definition**: Implementation of function.
* **Calling**: `result = add(5, 10);`

#### Passing Arguments

* **Pass by Value**: The actual value is passed.

  ```c
  void func(int x) { x = 10; } // Changes will not reflect in main()
  ```
* **Pass by Reference**: The address is passed.

  ```c
  void func(int *x) { *x = 10; } // Changes will reflect in main()
  ```

#### Recursive Functions

* **Definition**: Functions that call themselves.

  ```c
  int factorial(int n) {
      if (n == 0) return 1;
      return n * factorial(n - 1);
  }
  ```

### 7. Arrays in C

#### Declaring and Initializing Arrays

* **Declaration**: `int arr[10];`
* **Initialization**: `int arr[5] = {1, 2, 3, 4, 5};`
* **Access Elements**: `arr[0] = 10;`

#### Multi-Dimensional Arrays

* **2D Arrays**

  ```c
  int matrix[3][3] = {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
  };
  ```
* **Accessing Elements**: `matrix[1][2]`

#### Array as Function Argument

* **Passing Array to Function**

  ```c
  void printArray(int arr[], int size) {
      for(int i = 0; i < size; i++) {
          printf("%d ", arr[i]);
      }
  }
  ```

### 8. Pointers in C

#### Basics of Pointers

* **Declaration**: `int *ptr;`
* **Assigning Address**: `ptr = &variable;`
* **Dereferencing Pointer**: Access value using `*ptr`

#### Pointer Arithmetic

* **Increment**: `ptr++`
* **Decrement**: `ptr--`

#### Null Pointer

* **Definition**: Points to nothing (`int *ptr = NULL;`)

#### Void Pointer

* **Definition**: Generic pointer (`void *ptr;`)

#### Pointer to Pointer

* **Declaration**: `int **ptr;`

  ```c
  int a = 10;
  int *p = &a;
  int **pp = &p;
  ```

#### Passing Pointers to Functions

* **Example**

  ```c
  void increment(int *n) {
      (*n)++;
  }
  ```

### 9. Strings in C

#### Declaring Strings

* **Character Array**: `char str[20] = "Hello";`
* **Using Pointers**: `char *str = "Hello";`

#### Common String Functions

* **`strlen(str)`**: Get length of a string.
* **`strcpy(dest, src)`**: Copy string.
* **`strcat(str1, str2)`**: Concatenate strings.
* **`strcmp(str1, str2)`**: Compare strings.

#### Reading and Writing Strings

* **Input**

  ```c
  char name[20];
  scanf("%s", name); // Stops at whitespace
  ```
* **Output**

  ```c
  printf("%s", name);
  ```
* **Using `gets()` and `puts()`**

  ```c
  char str[50];
  gets(str); // Reads string with spaces
  puts(str); // Prints string
  ```

### 10. Structures in C

#### Defining a Structure

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

#### Accessing Structure Members

* **Dot Operator**: `student.age = 20;`
* **Pointer to Structure**: `struct Student *ptr = &student; ptr->age = 21;`

#### Nested Structures

* **Definition**: Structures within structures.

  ```c
  struct Address {
      char city[50];
      char state[50];
  };
  struct Person {
      char name[50];
      struct Address address;
  };
  ```

#### Structure as Function Argument

* **Passing by Value**

  ```c
  void printStudent(struct Student s) {
      printf("%s %d %.2f\n", s.name, s.age, s.gpa);
  }
  ```
* **Passing by Reference**

  ```c
  void updateAge(struct Student *s) {
      s->age = 21;
  }
  ```

### 11. Memory Management in C

#### Dynamic Memory Allocation

* **malloc()**: Allocates memory.

  ```c
  int *ptr = (int *)malloc(5 * sizeof(int));
  ```
* **calloc()**: Allocates memory and initializes to zero.

  ```c
  int *ptr = (int *)calloc(5, sizeof(int));
  ```
* **realloc()**: Resizes memory.

  ```c
  ptr = realloc(ptr, 10 * sizeof(int));
  ```
* **free()**: Frees allocated memory.

  ```c
  free(ptr);
  ```

#### Common Errors in Memory Management

* **Memory Leak**: Forgetting to `free()` allocated memory.
* **Dangling Pointer**: Using a pointer after `free()` has been called.
* **Double Free Error**: Calling `free()` on the same pointer twice.

### 12. File Handling in C

#### File Operations

* **Opening a File**

  ```c
  FILE *fptr = fopen("filename.txt", "r");
  ```

  * Modes: `"r"`, `"w"`, `"a"`, `"r+"`, `"w+"`, `"a+"`
* **Closing a File**

  ```c
  fclose(fptr);
  ```

#### Reading/Writing to Files

* **Writing**: `fprintf(fptr, "Hello\n");`
* **Reading**: `fscanf(fptr, "%s", str);`
* **Character Reading/Writing**

  ```c
  char ch = fgetc(fptr);
  fputc('A', fptr);
  ```

#### Random Access in Files

* **fseek()**: Set the file position to a specific location.

  ```c
  fseek(fptr, 0, SEEK_SET); // Move to the beginning of the file
  ```
* **ftell()**: Get the current position in the file.

  ```c
  long pos = ftell(fptr);
  ```
* **rewind()**: Move to the beginning of the file.

  ```c
  rewind(fptr);
  ```

### 13. Preprocessor Directives

#### Common Directives

* **`#define`**: Macro definitions.

  ```c
  #define PI 3.14159
  ```
* **`#include`**: Include a library.

  ```c
  #include <stdio.h>
  ```
* **Conditional Compilation**: `#ifdef`, `#ifndef`, `#endif`

  ```c
  #ifdef DEBUG
  printf("Debugging is enabled\n");
  #endif
  ```

### 14. Debugging and Common Errors

#### Compilation Errors

* **Syntax Errors**: Missing semicolons, unmatched braces.
* **Data Type Mismatch**: Using incorrect format specifiers in `printf()`/`scanf()`.

#### Logical Errors

* **Infinite Loops**: Incorrect loop conditions.
* **Incorrect Arithmetic**: Misplaced parentheses can lead to unexpected results.

#### Debugging Tips

* Use **printf()** to display variable values.
* Use **gdb** (GNU Debugger) for interactive debugging.

#### Common Runtime Errors

* **Segmentation Fault**: Accessing restricted memory (often due to invalid pointers).
* **Stack Overflow**: Excessive memory usage (e.g., too many recursive calls).

### 15. Best Practices in C Programming

* **Comment Your Code**: Use `//` or `/* */` for multi-line comments.
* **Use Meaningful Names**: Variables should have descriptive names.
* **Avoid Global Variables**: They make code harder to debug.
* **Break Down Functions**: Each function should perform one task.
* **Memory Management**: Always `free()` dynamically allocated memory.
* **Code Readability**: Proper indentation and spacing make the code readable.
* **Error Handling**: Always check return values for functions like `malloc()` or `fopen()`.

### 16. Advanced Topics

#### Command-Line Arguments

* **Main Function with Arguments**

  ```c
  int main(int argc, char *argv[]) {
      printf("Number of arguments: %d\n", argc);
      return 0;
  }
  ```

#### typedef

* **Definition**: Create an alias for data types.

  ```c
  typedef unsigned long ulong;
  ulong num = 100000;
  ```

#### Bit Manipulation

* **Bitwise Operations**: `&`, `|`, `^`, `~`, `<<`, `>>`
* **Use Cases**: Efficient storage, cryptography, etc.

#### Function Pointers

* **Definition**: Pointer that points to a function.

  ```c
  void (*funcPtr)(int) = &function_name;
  ```
* **Use Cases**: Callback mechanisms, dynamic function calls.

#### Macros vs. Functions

* **Macros**: `#define SQUARE(x) ((x) * (x))`
* **Functions**: `int square(int x) { return x * x; }`
* **Difference**: Macros are faster but lack type safety.

#### Linked Lists

* **Definition**: A linear data structure where elements are linked using pointers.
* **Node Structure**

  ```c
  struct Node {
      int data;
      struct Node *next;
  };
  ```
* **Basic Operations**: Insertion, Deletion, Traversal

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.d19.in/cheatsheet.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
