C Programming Essentials
Cheatsheet Content
UNIT 1: Basics of C 1. History and Characteristics Developed by Dennis Ritchie at Bell Labs (1972). Characteristics: Middle-level, structured, portable, fast, memory management. 2. Tokens in C Smallest individual units in a C program. Types: Keywords, Identifiers, Constants, Strings, Operators, Special Symbols. 3. Constants and Variables Constants: Fixed values during execution (e.g., `5`, `'A'`, `"hello"`). Declared with `const` or as literals. Variables: Memory locations to store data, whose values can change during execution (e.g., `int age = 30;`). 4. Operators (Unary, Binary, Ternary) Unary: Operates on one operand (e.g., `++a`, `--b`, `-c`). Binary: Operates on two operands (e.g., `a + b`, `x * y`, `p || q`). Ternary: Operates on three operands (e.g., `condition ? expr1 : expr2`). Only the conditional operator `?:` is ternary. 5. Operator Precedence and Associativity Precedence: Order in which different operators are evaluated (e.g., `*` before `+`). Associativity: Order in which operators of the same precedence are evaluated (e.g., left-to-right for `+`, right-to-left for assignment `=`). 6. Type Casting (Implicit & Explicit) Implicit (Coercion): Automatic conversion by compiler (e.g., `int` to `float`). Explicit: Manual conversion by programmer (e.g., `(int)3.14`). 7. Formatted Input/Output (`scanf()`, `printf()`) `printf("Format string", args...)`: Prints formatted output to console. `%d` for `int`, `%f` for `float`, `%c` for `char`, `%s` for `string`. `scanf("Format string", &args...)`: Reads formatted input from console. Requires address-of operator `&` for variables. 8. Arithmetic, Logical, Relational, Assignment Operators Arithmetic: `+`, `-`, `*`, `/`, `%` (modulus). Logical: `&&` (AND), `||` (OR), `!` (NOT). Relational: `==` (equal), `!=` (not equal), ` `, ` =`. Assignment: `=`, `+=`, `-=`, `*=`, `/=`, `%=`. 9. Special Operators (`sizeof`, `,`) `sizeof`: Returns size of a variable or type in bytes (e.g., `sizeof(int)`). `,` (comma): Evaluates expressions from left to right, returns value of rightmost expression. 10. Program: Calculate Simple Interest #include <stdio.h> int main() { float principal, rate, time, si; printf("Enter P, R, T: "); scanf("%f %f %f", &principal, &rate, &time); si = (principal * rate * time) / 100; printf("Simple Interest = %.2f\n", si); return 0; } UNIT 2: Decision Control and Looping Statements 1. `if-else`, `if-else if-else`, Nested `if` `if (condition) { ... }`: Executes block if condition is true. `if (cond1) { ... } else if (cond2) { ... } else { ... }`: Multiple conditions. Nested `if`: `if (cond1) { if (cond2) { ... } }`: An `if` statement inside another `if`. 2. `switch-case` Statement Allows multi-way branching based on value of an expression. switch (expression) { case value1: /* code */ break; case value2: /* code */ break; default: /* code */ } `break` statement is crucial to exit `switch` after a match. 3. Entry-Controlled vs. Exit-Controlled Loops Entry-Controlled (`for`, `while`): Condition checked BEFORE loop body execution. If false initially, body never runs. Exit-Controlled (`do-while`): Condition checked AFTER loop body execution. Body executes AT LEAST ONCE. 4. Program: Print Even Numbers (1-100) using `while` #include <stdio.h> int main() { int i = 2; while (i 5. Drawbacks of `goto` statement Makes code hard to read, understand, and debug (spaghetti code). Breaks structured programming principles. Generally avoided in modern C programming. 6. Program: Multiplication Table using `for` loop #include <stdio.h> int main() { int num, i; printf("Enter a number: "); scanf("%d", &num); for (i = 1; i 7. `break` and `continue` statements `break`: Terminates the innermost loop (or `switch`) and transfers control to the statement immediately following the loop/switch. `continue`: Skips the rest of the current iteration of the loop and proceeds to the next iteration. 8. Program: Check if a number is prime #include <stdio.h> int main() { int n, i, isPrime = 1; printf("Enter a positive integer: "); scanf("%d", &n); if (n == 0 || n == 1) isPrime = 0; else { for (i = 2; i 9. Program: Factorial using `do-while` loop #include <stdio.h> int main() { int n, i = 1; long long factorial = 1; printf("Enter a number: "); scanf("%d", &n); if (n 10. Nested Loop Structure A loop (inner loop) placed inside another loop (outer loop). Inner loop executes completely for each iteration of the outer loop. Used for tasks like matrix operations, pattern printing. UNIT 3: Subscripted Variables / Arrays 1. Different Types of Arrays One-Dimensional (1D): A list of elements of the same type (e.g., `int arr[5];`). Multi-Dimensional (2D, 3D): Arrays of arrays (e.g., `int matrix[3][3];`). 2. Program: Find Largest Number in a 1D Array #include <stdio.h> int main() { int arr[5] = {10, 30, 5, 45, 20}; int max = arr[0]; for (int i = 1; i max) max = arr[i]; } printf("Largest element: %d\n", max); return 0; } 3. Initialization of 2D Arrays `int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};` Can omit first dimension: `int matrix[][3] = {{1,2,3}, {4,5,6}};` 4. String Handling Functions Strings are character arrays terminated by `\0`. `strlen()`: Length of string. `strcpy()`: Copies a string. `strcat()`: Concatenates strings. `strcmp()`: Compares strings. `strchr()`: Finds first occurrence of a character. `strstr()`: Finds first occurrence of a substring. 5. Program: Count Vowels, Consonants, Digits, Spaces in a String #include <stdio.h> #include <string.h> #include <ctype.h> // For isalpha, isdigit int main() { char str[] = "Hello World 123"; int vowels=0, cons=0, digits=0, spaces=0; for (int i = 0; str[i] != '\0'; ++i) { char ch = tolower(str[i]); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels++; else if (isalpha(ch)) cons++; else if (isdigit(ch)) digits++; else if (isspace(ch)) spaces++; } printf("Vowels: %d, Consonants: %d, Digits: %d, Spaces: %d\n", vowels, cons, digits, spaces); return 0; } 6. Program: Reverse a String (without library functions) #include <stdio.h> #include <string.h> // For strlen int main() { char str[] = "hello"; int len = strlen(str); for (int i = 0; i 7. Substring Extraction (without string operations) Manually iterate through the string from a start index for a given length. 8. Program: Add two 3x3 matrices #include <stdio.h> int main() { int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}; int C[3][3]; for (int i = 0; i 9. Character Arrays vs. Strings Character Array: An array of `char` type (e.g., `char arr[] = {'H', 'i'};`). String: A character array terminated by a null character `\0` (e.g., `char str[] = "Hi";`). All C string functions expect null-terminated strings. 10. Program: Concatenate two strings (without `strcat()`) #include <stdio.h> #include <string.h> int main() { char s1[50] = "Hello "; char s2[] = "World"; int i, j; for (i = 0; s1[i] != '\0'; ++i); // Find end of s1 for (j = 0; s2[j] != '\0'; ++j, ++i) { s1[i] = s2[j]; } s1[i] = '\0'; // Null-terminate the combined string printf("Concatenated string: %s\n", s1); return 0; } UNIT 4: User Defined Functions 1. Define a Function, Modularity Function: A block of code that performs a specific task. Modularity: Breaking down a program into smaller, manageable functions. Improves readability, reusability, and maintainability. 2. Function Prototype, Call, Return Value Prototype: Declaration of a function (name, return type, parameters) before its definition or call (e.g., `int add(int, int);`). Call: Invoking a function (e.g., `sum = add(a, b);`). Return Value: A value sent back by the function to the caller using `return` statement. 3. Call by Value vs. Call by Reference Call by Value: A copy of the argument's value is passed to the function. Changes inside the function do not affect the original variable. Call by Reference: The memory address (pointer) of the argument is passed. Changes inside the function directly affect the original variable. 4. Storage Classes (auto, extern, static, register) `auto`: Default for local variables. Scope within block, lifetime within block. `extern`: Declares a global variable defined elsewhere. `static`: Preserves value between function calls (for local variables). Retains value in memory for whole program (for global variables). `register`: Suggests storing variable in CPU register for faster access (compiler may ignore). 5. Recursion: Factorial Program A function calling itself. Must have a base case to stop recursion. long long factorial(int n) { if (n == 0) return 1; // Base case else return n * factorial(n - 1); // Recursive call } 6. Recursion vs. Iteration Recursion: Elegant for problems with recursive structure (e.g., tree traversal, factorial). Can be less efficient (overhead of function calls), potential for stack overflow. Iteration: Uses loops. Generally more efficient (less overhead), easier to understand for simple repetitive tasks. 7. Function Signature The function's name and its parameter list (types and order of parameters). Example: For `int func(int a, float b);`, the signature is `func(int, float)`. Return type is NOT part of the signature. 8. Program: Swap Two Numbers using Functions #include <stdio.h> void swap(int *a, int *b) { // Call by reference int temp = *a; *a = *b; *b = temp; } int main() { int x = 10, y = 20; printf("Before swap: x=%d, y=%d\n", x, y); swap(&x, &y); // Pass addresses printf("After swap: x=%d, y=%d\n", x, y); return 0; } 9. Scope and Lifetime of Variables Scope: Region of code where a variable is accessible (local, global, block). Lifetime: Period during which a variable exists in memory (e.g., local variables exist only during function execution, static/global throughout program). 10. Types of User-Defined Functions No arguments, no return value. No arguments, with return value. With arguments, no return value. With arguments, with return value. UNIT 5: Pointers in C 1. Pointers: Declaration and Initialization Pointer: A variable that stores the memory address of another variable. Declaration: `dataType *pointerName;` (e.g., `int *ptr;`). Initialization: `ptr = &variable;` (e.g., `ptr = #`). `*`: Dereference operator (access value at address). `&`: Address-of operator (get address of variable). 2. Program: Swap Two Numbers using Pointers (Same as Unit 4, Q8 - demonstrates call by reference using pointers) 3. Pointer Arithmetic Increment/Decrement: `ptr++` moves pointer to next memory location of its data type. Addition/Subtraction: `ptr + n` moves `n` elements forward. Subtraction of Pointers: `ptr1 - ptr2` gives number of elements between them (must be same type). 4. Program: Display Elements of an Array using Pointers #include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; int *ptr = arr; // ptr points to arr[0] for (int i = 0; i 5. Explain Pointer to Pointer A pointer that stores the address of another pointer. Declaration: `int **ptr_to_ptr;` Used for dynamic 2D arrays or passing pointer by reference. 6. Dynamic Memory Allocation (`malloc`, `calloc`, `realloc`, `free`) `malloc(size)`: Allocates `size` bytes of uninitialized memory. Returns `void*`. `calloc(num, size)`: Allocates memory for `num` elements of `size` bytes each, initializes to zero. Returns `void*`. `realloc(ptr, newSize)`: Changes size of previously allocated memory block. `free(ptr)`: Releases allocated memory pointed to by `ptr`. Prevents memory leaks. 7. Program: Find Length of a String using Pointers #include <stdio.h> int main() { char str[] = "example"; char *ptr = str; int count = 0; while (*ptr != '\0') { count++; ptr++; } printf("Length of string: %d\n", count); return 0; } 8. Explain Array of Pointers An array where each element is a pointer. `int *ptr_arr[5];` // An array of 5 integer pointers. Can store addresses of different variables or strings (e.g., `char *names[]`). 9. Pointer to Function A pointer that stores the memory address of a function. Declaration: `returnType (*pointerName)(parameterList);` Used for callback functions, function tables. 10. Program: Create a Structure using Pointer to Structure #include <stdio.h> #include <stdlib.h> struct Student { int id; char name[20]; }; int main() { struct Student *sPtr; sPtr = (struct Student *) malloc(sizeof(struct Student)); if (sPtr == NULL) return 1; sPtr->id = 101; // Access members using -> operator sprintf(sPtr->name, "Alice"); printf("ID: %d, Name: %s\n", sPtr->id, sPtr->name); free(sPtr); // Free allocated memory return 0; }