C Programming Essentials
Cheatsheet Content
UNIT 1: Basics of C History & Characteristics of C: Developed by Dennis Ritchie at Bell Labs. Known for efficiency, portability, and low-level memory access. Tokens in C7: Keywords: Reserved words (e.g., int , if , while ). Identifiers: User-defined names (variables, functions). Constants: Fixed values (e.g., 10 , 3.14 , 'a' ). Strings: Sequence of characters in double quotes (e.g., "hello" ). Operators: Symbols performing operations (e.g., + , - , = ). Special Symbols: (e.g., {} , () , ; ). Defining Variables & Constants: Variable: int age = 20; , float salary; Constant: const float PI = 3.14; , #define MAX 100 Binary, Unary, Ternary Operators: Binary: Operate on two operands (e.g., + , - , * , / , % ). Unary: Operate on one operand (e.g., ++ , -- , ! , sizeof ). Ternary: Operates on three operands (conditional operator ? : ). Operator Precedence & Associativity: Determines the order of evaluation in expressions. E.g., * and / have higher precedence than + and - . Type Casting: Converting one data type to another. Implicit: Automatic conversion (e.g., int to float ). Explicit: Manual conversion using cast operator (e.g., (float)sum / count; ). Formatted Input/Output: printf("Value: %d\n", var); - Output. scanf("%d", &var); - Input. Arithmetic, Logical, Relational, Assignment Operators: Arithmetic: + , - , * , / , % . Logical: && (AND), || (OR), ! (NOT). Relational: == , != , , > , , >= . Assignment: = , += , -= , *= , /= , %= . Special Operators: sizeof : Returns the size of a variable or type. & : Address-of operator. * : Pointer dereference operator. , : Comma operator (evaluates expressions from left to right). Simple Interest Program: #include <stdio.h> int main() { float p, r, t, si; printf("Enter P, R, T: "); scanf("%f %f %f", &p, &r, &t); si = (p * r * t) / 100; printf("Simple Interest = %.2f\n", si); return 0; } UNIT 2: Decision Control & Looping Statements If-else, if-else-if ladder, nested-if: if-else : Executes code block based on a condition. if (condition) { // code if true } else { // code if false } if-else-if ladder : Multiple conditions checked sequentially. if (cond1) { ... } else if (cond2) { ... } else { ... } Nested-if : if statement inside another if statement. switch-case for Simple Calculator: #include <stdio.h> int main() { char op; double n1, n2; printf("Enter operator (+, -, *, /): "); scanf(" %c", &op); printf("Enter two operands: "); scanf("%lf %lf", &n1, &n2); switch (op) { case '+': printf("%.1lf + %.1lf = %.1lf\n", n1, n2, n1 + n2); break; case '-': printf("%.1lf - %.1lf = %.1lf\n", n1, n2, n1 - n2); break; case '*': printf("%.1lf * %.1lf = %.1lf\n", n1, n2, n1 * n2); break; case '/': printf("%.1lf / %.1lf = %.1lf\n", n1, n2, n1 / n2); break; default: printf("Error! Invalid operator.\n"); } return 0; } Entry-controlled vs. Exit-controlled loops: Entry-controlled: Condition checked before loop body execution ( for , while ). May not execute even once. Exit-controlled: Condition checked after loop body execution ( do-while ). Always executes at least once. Print Numbers between 1 and 100 using while : #include <stdio.h> int main() { int i = 1; while (i Drawbacks of goto statement: Makes code hard to read, debug, and maintain (spaghetti code). Generally avoided. Multiplication Table using for loop: #include <stdio.h> int main() { int num, i; printf("Enter an integer: "); scanf("%d", &num); for (i = 1; i break and continue : break : Terminates the loop or switch statement immediately. continue : Skips the current iteration and proceeds to the next iteration of the loop. Check if a number is prime: #include <stdio.h> int main() { int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d", &n); if (n == 0 || n == 1) flag = 1; for (i = 2; i Factorial using do-while loop: #include <stdio.h> int main() { int n, fact = 1; printf("Enter a non-negative integer: "); scanf("%d", &n); if (n Nested loop example (e.g., printing a pattern): #include <stdio.h> int main() { for (int i = 1; i UNIT 3: Subscripted Variables / Arrays Different Types of Arrays: One-dimensional array: int arr[5]; Two-dimensional array: int matrix[3][3]; Multi-dimensional arrays: int tensor[2][2][2]; Find Largest Number in a 1D Array: #include <stdio.h> int main() { int arr[] = {10, 324, 45, 90, 980}; int n = sizeof(arr) / sizeof(arr[0]); int max = arr[0]; for (int i = 1; i max) { max = arr[i]; } } printf("Largest element = %d\n", max); return 0; } Initialization of 2D Arrays: int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; int matrix[2][3] = {1, 2, 3, 4, 5, 6}; String Handling Functions: strlen() : Returns length of string. strcpy() : Copies one string to another. strcat() : Concatenates two strings. strcmp() : Compares two strings. strchr() : Finds first occurrence of a character. strstr() : Finds first occurrence of a substring. Count Vowels, Consonants, Digits, Spaces: #include <stdio.h> #include <string.h> #include <ctype.h> int main() { char s[] = "Hello World 123"; int v=0, c=0, d=0, sp=0; for (int i = 0; s[i] != '\0'; i++) { char ch = tolower(s[i]); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') v++; else if (ch >= 'a' && ch = '0' && ch Reverse a string without using library functions: #include <stdio.h> #include <string.h> int main() { char str[] = "hello", temp; int i, j; int len = strlen(str); for (i = 0, j = len - 1; i Substring extraction using string ops: #include <stdio.h> #include <string.h> void substring(char s[], char sub[], int pos, int len) { int c = 0; while (c Compare two strings: #include <stdio.h> #include <string.h> int main() { char s1[] = "hello", s2[] = "world"; int result = strcmp(s1, s2); if (result == 0) printf("Strings are equal\n"); else if (result Concatenate two strings: #include <stdio.h> #include <string.h> int main() { char s1[50] = "Hello ", s2[] = "World"; strcat(s1, s2); printf("Concatenated string: %s\n", s1); // Hello World return 0; } UNIT 4: User Defined Functions Advantages of Module Programming: Code Reusability. Easier to debug. Better organization and readability. Reduces code size. Function Prototype, Definition, Call: Prototype: Declares function signature (return type, name, parameters). E.g., int add(int, int); Definition: Contains the actual code of the function. int add(int a, int b) { return a + b; } Call: Invoking the function. E.g., int sum = add(5, 3); Program to find square of a number using function: #include <stdio.h> int square(int num) { return num * num; } int main() { int n = 5; printf("Square of %d is %d\n", n, square(n)); return 0; } Storage classes ( auto , static , extern , register ): auto : Default for local variables. Stored in stack. static : Retains value between function calls. Local scope, global lifetime. extern : Declares a global variable defined elsewhere. register : Suggests storing variable in CPU registers for faster access (compiler may ignore). Recursion: A function calling itself. Find factorial using recursion: #include <stdio.h> long int factorial(int n) { if (n >= 1) return n * factorial(n - 1); else return 1; } int main() { int num = 5; printf("Factorial of %d = %ld\n", num, factorial(num)); return 0; } Recursion vs. Iteration: Feature Recursion Iteration Complexity More complex, higher overhead Less complex, efficient Code Size Shorter, more elegant for certain problems Longer code Memory Uses more memory (stack for function calls) Uses less memory Termination Base case Loop condition Function Signature: The function's return type, name, and parameter list. E.g., int sum(int a, int b) . Swap two numbers using functions: Call by Value: // Won't swap void swap(int x, int y) { int temp = x; x = y; y = temp; } Call by Reference: // Swaps void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // Call: swap(&a, &b); Scope and Lifetime of Variables: Scope: Region of code where a variable is accessible. (e.g., local, global, file, block). Lifetime: Duration for which a variable exists in memory. 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 What is a Pointer? A variable that stores the memory address of another variable. Declaration: int *ptr; Initialization: int var = 10; ptr = &var; Swap two numbers using pointers: (See Call by Reference example above). Pointer Arithmetic: Operations on pointers. ptr++ : Increments pointer to point to the next memory location of its data type. ptr-- : Decrements pointer. ptr + N : Adds N times the size of the data type to the pointer. ptr - N : Subtracts N times the size of the data type from the pointer. Subtraction of two pointers of same type gives number of elements between them. 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 Pointer to Pointer (Double Pointer): A pointer that stores the address of another pointer. Declaration: int **pptr; Example: int var = 10; int *ptr = &var; int **pptr = &ptr; printf("Value: %d\n", **pptr); // 10 Dynamic Memory Allocation ( malloc , calloc , realloc , free ): malloc() : Allocates a block of memory of specified size. Returns void* . int *arr = (int *)malloc(5 * sizeof(int)); calloc() : Allocates memory for an array, initializes all bits to zero. int *arr = (int *)calloc(5, sizeof(int)); realloc() : Changes the size of previously allocated memory block. arr = (int *)realloc(arr, 10 * sizeof(int)); free() : Deallocates dynamically allocated memory. free(arr); Find length of a string using pointers: #include <stdio.h> int stringLength(char *s) { int count = 0; while (*s != '\0') { count++; s++; } return count; } int main() { char str[] = "hello"; printf("Length of string: %d\n", stringLength(str)); // 5 return 0; } Array of Pointers: An array where each element is a pointer. Example: An array of strings. char *names[] = {"Alice", "Bob", "Charlie"}; Function Pointer: A pointer that stores the address of a function. Declaration: return_type (*ptr_name)(param_type1, ...); Example: int add(int a, int b) { return a + b; } int (*func_ptr)(int, int) = &add; int result = func_ptr(10, 20); // 30 Structure using pointer to structure: Declaration: struct Point { int x, y; }; struct Point p1; struct Point *ptr = &p1; Accessing members: Use -> operator. ptr->x = 10; (equivalent to (*ptr).x = 10; )