Cheatsheet
the shortcut one shouldnt prefer
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
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.
scanf(): Used for input.
%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
if-else Statement
Nested if Statement
else if Ladder
Switch Case
Syntax
Use break to prevent fall-through behavior.
Looping Statements
for Loop
while Loop
do-while Loop
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 ANDOR (
|
): Bitwise ORXOR (
^
): Bitwise XORNOT (
~
): Bitwise NOTLeft 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
Example
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.
Pass by Reference: The address is passed.
Recursive Functions
Definition: Functions that call themselves.
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
Accessing Elements:
matrix[1][2]
Array as Function Argument
Passing Array to Function
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;
Passing Pointers to Functions
Example
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
Output
Using
gets()
andputs()
10. Structures in C
Defining a Structure
Accessing Structure Members
Dot Operator:
student.age = 20;
Pointer to Structure:
struct Student *ptr = &student; ptr->age = 21;
Nested Structures
Definition: Structures within structures.
Structure as Function Argument
Passing by Value
Passing by Reference
11. Memory Management in C
Dynamic Memory Allocation
malloc(): Allocates memory.
calloc(): Allocates memory and initializes to zero.
realloc(): Resizes memory.
free(): Frees allocated memory.
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
Modes:
"r"
,"w"
,"a"
,"r+"
,"w+"
,"a+"
Closing a File
Reading/Writing to Files
Writing:
fprintf(fptr, "Hello\n");
Reading:
fscanf(fptr, "%s", str);
Character Reading/Writing
Random Access in Files
fseek(): Set the file position to a specific location.
ftell(): Get the current position in the file.
rewind(): Move to the beginning of the file.
13. Preprocessor Directives
Common Directives
#define
: Macro definitions.#include
: Include a library.Conditional Compilation:
#ifdef
,#ifndef
,#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()
orfopen()
.
16. Advanced Topics
Command-Line Arguments
Main Function with Arguments
typedef
Definition: Create an alias for data types.
Bit Manipulation
Bitwise Operations:
&
,|
,^
,~
,<<
,>>
Use Cases: Efficient storage, cryptography, etc.
Function Pointers
Definition: Pointer that points to a function.
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
Basic Operations: Insertion, Deletion, Traversal
Last updated
Was this helpful?