0% found this document useful (0 votes)
15 views34 pages

C Notes

The document is a comprehensive study guide for C programming, covering topics from basic syntax to advanced concepts such as pointers, file handling, and memory management. It includes sections on data types, control flow, functions, arrays, and common algorithms, along with practical examples and code snippets. The notes are designed for learners to build a solid foundation in C programming, with a focus on both theoretical knowledge and practical application.

Uploaded by

Ash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views34 pages

C Notes

The document is a comprehensive study guide for C programming, covering topics from basic syntax to advanced concepts such as pointers, file handling, and memory management. It includes sections on data types, control flow, functions, arrays, and common algorithms, along with practical examples and code snippets. The notes are designed for learners to build a solid foundation in C programming, with a focus on both theoretical knowledge and practical application.

Uploaded by

Ash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 1


C
PROGRAMMING
Complete Study Notes
From Basics to Advanced

Syntax • Pointers • Arrays • Strings • Structures • File I/O • Memory

Prepared by

Mudit Bagra
Designed & Compiled with ♥ for C Learners

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 2

TABLE OF CONTENTS

Section Topic

01 Introduction to C Language

02 Installation & Setup

03 Basic Structure of a C Program

04 Data Types & Variables

05 Constants & Literals

06 Operators in C

07 Input & Output (scanf / printf)

08 Control Flow — if / else / switch

09 Loops — for, while, do-while

10 Functions

11 Arrays

12 Strings

13 Pointers

14 Structures & Unions

15 Enumerations (enum)

16 Storage Classes

17 Preprocessor Directives

18 File Handling

19 Dynamic Memory Allocation

20 Recursion

21 Command Line Arguments

22 Bitwise Operators

23 Common Algorithms in C

24 Error Handling & Debugging

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 3

25 Quick Reference Cheat Sheet

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 4

01 Introduction to C Language

What is C?
C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell Labs
around 1972. It is one of the most widely used languages and forms the foundation of many modern
languages.

Key Features of C
➤ Low-level access to memory via pointers
➤ High performance — close to hardware, used in OS development
➤ Portable — C code can run on different machines with little modification
➤ Structured programming — supports functions, loops, conditionals
➤ Rich set of built-in operators and functions
➤ Foundation for C++, Java, Python, and many other languages
➤ Used in embedded systems, operating systems, compilers

Applications of C
Domain Examples

Operating Systems Linux kernel, Windows core, Unix

Microcontrollers, Arduino, IoT


Embedded Systems devices

Compilers & Interpreters GCC, Python interpreter (CPython)

MySQL, PostgreSQL (core written in


Databases C)

Game Engines Quake engine, id Tech engine

Networking Network protocols, routers firmware

Scientific Computing Numerical simulations, HPC

Device Drivers Hardware interface programming

💡 NOTE: C is called the 'mother of all programming languages'. Learning C builds a rock-solid foundation.

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 5

02 Installation & Setup

Compilers & IDEs


Tool Platform / Notes

GCC (GNU Compiler Collection) Linux / macOS (built-in or brew)

MinGW / TDM-GCC Windows — install GCC on Windows

Turbo C++ 3.0 Classic IDE (for older courses)

Cross-platform IDE, beginner-


Code::Blocks friendly

Dev-C++ Windows, lightweight IDE

Visual Studio Code + GCC Modern, powerful with extensions

CLion (JetBrains) Professional cross-platform IDE

OnlineGDB / [Link] Browser-based, no install needed

Compiling & Running a C Program


// Step 1: Write your C file → hello.c

// Step 2: Compile using GCC


gcc hello.c -o hello

// Step 3: Run the output


./hello // Linux / macOS
[Link] // Windows

// With warnings enabled (recommended)


gcc -Wall -Wextra hello.c -o hello

// Check GCC version


gcc --version

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 6

03 Basic Structure of a C Program

Hello World — Anatomy


#include <stdio.h> // Preprocessor directive — includes standard I/O library

int main() { // main() — entry point of every C program


// This is a comment
printf("Hello, World!\n"); // Output function
return 0; // Return 0 = success to the OS
}

Program Structure Breakdown


Component Purpose

#include <stdio.h> Include standard input/output header

int main() Program entry point, returns int

{} Curly braces define a block/scope

printf("..."); Print output to screen

Signal successful program


return 0; termination

Single-line comment (ignored by


// comment compiler)

/* comment */ Multi-line comment block

Statement terminator — required


; after every statement

⚠️IMPORTANT: Every C statement must end with a semicolon (;). Missing it causes a compile error.

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 7

04 Data Types & Variables

Fundamental Data Types


Data Type Size (typical) Range / Example

int 4 bytes -2,147,483,648 to 2,147,483,647

short int 2 bytes -32,768 to 32,767

long int 4 or 8 bytes Larger integer range

unsigned int 4 bytes 0 to 4,294,967,295

float 4 bytes 3.4E-38 to 3.4E+38 (~6 decimals)

double 8 bytes 1.7E-308 to 1.7E+308 (~15 decimals)

char 1 byte Single character: 'A', '5', '@'

void 0 bytes No value / used for functions

_Bool 1 byte 0 (false) or 1 (true)

Declaring Variables
int age = 20;
float salary = 45000.75;
double pi = 3.14159265358979;
char grade = 'A';
char name[50] = "Mudit"; // string = char array

// Multiple declarations
int x, y, z;
int a = 1, b = 2, c = 3;

// Constants
const float G = 9.81;
#define MAX 100

// Check size
printf("%zu bytes\n", sizeof(int)); // → 4

Type Modifiers
Modifier Effect

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 8

Can hold negative and positive


signed values (default for int)

Only non-negative values (doubles


unsigned positive range)

Reduces size (e.g., short int = 2


short bytes)

Increases size (e.g., long int = 4-8


long bytes)

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 9

05 Constants & Literals

Types of Constants
Type Example Notes

Integer constant 42, -7, 0 Decimal, Octal (0X), Hex (0xFF)

Float constant 3.14, 2.5e10 Use f suffix for float: 3.14f

Character constant 'A', '\n', '\0' Single quotes, 1 character

String literal "Hello" Double quotes, null-terminated

const variable const int MAX=100; Cannot be changed after init

#define macro #define PI 3.14159 Preprocessor text substitution

Escape sequences '\n', '\t', '\\' Special characters in strings

Common Escape Sequences


Escape Sequence Meaning

\n Newline — move to next line

\t Horizontal tab

\r Carriage return

\\ Backslash character

\' Single quote

\" Double quote

\0 Null character (string terminator)

\a Alert / Bell

\b Backspace

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 10

06 Operators in C

Arithmetic Operators
Operator Operation & Example

+ Addition: 5 + 3 = 8

- Subtraction: 10 - 4 = 6

* Multiplication: 4 * 3 = 12

/ Division: 7 / 2 = 3 (integer division!)

% Modulus (remainder): 7 % 3 = 1

++ Increment: x++ (post) or ++x (pre)

-- Decrement: x-- (post) or --x (pre)

Relational & Logical Operators


Operator Meaning

== Equal to

!= Not equal to

> and < Greater than / Less than

>= and <= Greater/Less than or equal

&& Logical AND — both must be true

Logical OR — at least one must be


|| true

! Logical NOT — negates condition

Other Operators
Category Operator Description

Assignment =, +=, -=, *=, /=, %= Assign and update value

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 11

Conditional ? : Ternary: (cond) ? a : b

Comma , Evaluate multiple expressions

Sizeof sizeof() Size of type or variable in bytes

Address-of & Get memory address of variable

Dereference * Access value at pointer address

Arrow -> Access struct member via pointer

Dot . Access struct member directly

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 12

07 Input & Output — scanf / printf

printf — Formatted Output


#include <stdio.h>

int main() {
int age = 20;
float marks = 95.5;
char grade = 'A';
char name[] = "Mudit";

printf("Name: %s\n", name); // → Name: Mudit


printf("Age: %d\n", age); // → Age: 20
printf("Marks: %.2f\n", marks); // → Marks: 95.50
printf("Grade: %c\n", grade); // → Grade: A
return 0;
}

Format Specifiers
Specifier Data Type

%d or %i int (signed decimal integer)

%u unsigned int

%f float / double (decimal notation)

%e float / double (scientific notation)

%c char (single character)

%s string (char array)

%p pointer address

%x int (hexadecimal)

%o int (octal)

%ld long int

%lf double (in scanf)

%% Print literal % character

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 13

scanf — Formatted Input


int age;
float salary;
char name[50];

printf("Enter name: ");


scanf("%s", name); // reads one word (no spaces)

printf("Enter age: ");


scanf("%d", &age); // & = address-of operator

printf("Enter salary: ");


scanf("%f", &salary);

// Multiple values at once


scanf("%d %f", &age, &salary);

// Read string with spaces


fgets(name, sizeof(name), stdin);

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 14

08 Control Flow — if / else / switch

if / else if / else
int score = 85;

if (score >= 90) {


printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n"); // This prints
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}

// Ternary operator
int max = (a > b) ? a : b;

switch Statement
int day = 3;

switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break; // This prints
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
default: printf("Weekend\n"); break;
}

⚠️WARNING: Always use 'break' in switch cases. Without it, execution falls through to the next case!

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 15

09 Loops — for, while, do-while

for Loop
// Syntax: for (init; condition; update)
for (int i = 0; i < 5; i++) {
printf("%d ", i); // → 0 1 2 3 4
}

// Nested for loops (multiplication table)


for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%4d", i * j);
}
printf("\n");
}

while Loop
int n = 1;
while (n <= 5) {
printf("%d\n", n);
n++;
}

// Infinite loop (must break manually)


while (1) {
// loop body
if (condition) break;
}

do-while Loop
// Executes body at LEAST once before checking condition
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while (num <= 0);

printf("You entered: %d\n", num);

Loop Control
Statement Effect

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 16

break Exit the loop immediately

Skip rest of current iteration, go


continue to next

Jump to a labelled statement (use


goto label sparingly)

Exit the entire function (also exits


return loop)

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 17

10 Functions

Defining & Calling Functions


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

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

// Calling a function
int main() {
int result = add(5, 3);
printf("Sum = %d\n", result); // → Sum = 8
return 0;
}

Types of Function Arguments


// Call by Value — copy of argument passed
void doubleVal(int x) {
x = x * 2; // original unchanged
}

// Call by Reference — pointer passed


void doubleRef(int *x) {
*x = *x * 2; // original IS changed
}

int n = 5;
doubleVal(n); // n still 5
doubleRef(&n); // n becomes 10

Function Categories
Return Type Example

void — no return void printHello() { printf("Hi"); }

int — returns integer int square(int x) { return x*x; }

float avg(float a, float b) { return


float — returns float (a+b)/2; }

char* — returns string char* greet() { return "Hello"; }

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 18

int factorial(int n) { return


Recursive function n*factorial(n-1); }

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 19

11 Arrays

1D Arrays
// Declaration
int marks[5]; // uninitialized
int scores[5] = {90, 85, 78, 92, 88}; // initialized
int nums[] = {1, 2, 3, 4, 5}; // size auto-deduced

// Access (0-indexed)
printf("%d\n", scores[0]); // → 90
printf("%d\n", scores[4]); // → 88

// Modify
scores[2] = 95;

// Traverse with loop


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

// Size of array
int len = sizeof(scores) / sizeof(scores[0]); // → 5

2D Arrays (Matrix)
// 3 rows, 4 columns
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

// Access element (row 1, col 2)


printf("%d\n", matrix[1][2]); // → 7

// Traverse 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%4d", matrix[i][j]);
}
printf("\n");
}

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 20

12 Strings in C

String Basics
In C, strings are arrays of characters terminated by a null character '\0'.
char name[10] = "Mudit";
// Stored as: ['M','u','d','i','t','\0',?,?,?,?]

// Input/Output
printf("%s\n", name); // print string
scanf("%s", name); // read word (no spaces)
fgets(name, 10, stdin); // read line with spaces

// String length (manual)


int len = 0;
while (name[len] != '\0') len++;

string.h Functions
Function Description Example

strlen(s) Length (excl. \0) strlen("hello") → 5

strcpy(d,s) Copy s into d strcpy(dest, "hi")

strncpy(d,s,n) Copy max n chars strncpy(d, s, 5)

strcat(d,s) Append s to d strcat(dest, " world")

strcmp(s1,s2) Compare: 0=equal strcmp("a","b") → <0

strchr(s,c) Find char in string strchr("hello",'l')

strstr(s1,s2) Find substring strstr("hello","ell")

strupr(s) Uppercase (non-std) strupr("hello")

strlwr(s) Lowercase (non-std) strlwr("HELLO")

atoi(s) String to int atoi("42") → 42

atof(s) String to float atof("3.14") → 3.14

sprintf(buf,...) Print to string buffer sprintf(buf,"%d",n)

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 21

13 Pointers

What are Pointers?


A pointer is a variable that stores the memory address of another variable.
int x = 42;
int *ptr = &x; // ptr stores address of x

printf("%d\n", x); // → 42 (value)


printf("%p\n", &x); // → 0x... (address of x)
printf("%p\n", ptr); // → 0x... (same address)
printf("%d\n", *ptr); // → 42 (dereference: value at address)

// Modify via pointer


*ptr = 100;
printf("%d\n", x); // → 100

Pointer Arithmetic
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // pointer to first element

printf("%d\n", *p); // → 10
printf("%d\n", *(p+1)); // → 20
printf("%d\n", *(p+4)); // → 50

p++; // advance to next element


printf("%d\n", *p); // → 20

Pointer to Pointer & NULL


// Pointer to pointer
int x = 5;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp); // → 5

// NULL pointer (safe initialization)


int *ptr = NULL;
if (ptr == NULL) printf("Pointer is null\n");
⚠️WARNING: Never dereference a NULL pointer — it causes undefined behavior / crash (segmentation fault).

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 22

14 Structures & Unions

Structures (struct)
// Define a structure
struct Student {
char name[50];
int rollNo;
float marks;
};

// Declare and use


struct Student s1;
strcpy([Link], "Mudit");
[Link] = 42;
[Link] = 95.5;

printf("Name: %s, Roll: %d, Marks: %.1f\n",


[Link], [Link], [Link]);

// Initialize at declaration
struct Student s2 = {"Alice", 10, 88.0};

// typedef for cleaner syntax


typedef struct {
char name[50];
int age;
} Person;

Person p1 = {"Bob", 25};

Pointer to Structure
struct Student *ptr = &s1;

printf("%s\n", ptr->name); // → arrow operator


printf("%d\n", (*ptr).rollNo); // equivalent

Unions
A union stores different data types in the same memory location. Only ONE member holds a value at a
time.
union Data {
int i;
float f;
char c;
};

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 23

union Data d;
d.i = 65;
printf("%d %c\n", d.i, d.c); // → 65 A
// Size = size of largest member
printf("%zu\n", sizeof(union Data)); // → 4

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 24

15 Enumerations (enum)

enum Basics
// Define enum
enum Day { MON=1, TUE, WED, THU, FRI, SAT, SUN };

enum Day today = WED;


printf("Day: %d\n", today); // → 3

// Use in switch
switch (today) {
case MON: printf("Monday\n"); break;
case WED: printf("Wednesday\n"); break;
default: printf("Other day\n"); break;
}

// enum with typedef


typedef enum { RED, GREEN, BLUE } Color;
Color c = GREEN;

16 Storage Classes

Storage Class Specifiers


Storage Class Keyword Description

Automatic auto Default for local variables; exist within block scope

External extern Declared outside functions; accessible across files

Static static Retains value between function calls; file scope if global

Register register Hint to store in CPU register for speed (compiler decides)

// static — retains value across calls


void counter() {
static int count = 0;
count++;
printf("Called %d time(s)\n", count);
}
counter(); // → Called 1 time(s)
counter(); // → Called 2 time(s)
counter(); // → Called 3 time(s)

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 25

17 Preprocessor Directives

Common Directives
// Include header files
#include <stdio.h> // standard library
#include "myfile.h" // user-defined header

// Macro definitions
#define PI 3.14159
#define MAX 100
#define SQ(x) ((x)*(x)) // function-like macro

printf("%.5f\n", PI); // → 3.14159


printf("%d\n", SQ(5)); // → 25

// Conditional compilation
#ifdef DEBUG
printf("Debug mode ON\n");
#endif

#ifndef MAX_SIZE
#define MAX_SIZE 256
#endif

// Undefine a macro
#undef PI

// Predefined macros
printf("%s line %d\n", __FILE__, __LINE__);
printf("Compiled: %s\n", __DATE__);

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 26

18 File Handling

Opening & Closing Files


Mode Description

"r" Open for reading (file must exist)

Open for writing (creates/overwrites


"w" file)

Open for appending (creates if not


"a" exists)

"r+" Open for reading and writing

"w+" Read/write (creates/overwrites)

"a+" Read/append

"rb" / "wb" Binary read / binary write

#include <stdio.h>

FILE *fp;

// Write to file
fp = fopen("[Link]", "w");
if (fp == NULL) { printf("Error!\n"); return 1; }
fprintf(fp, "Hello File!\n");
fprintf(fp, "Marks: %d\n", 95);
fclose(fp);

// Read from file


fp = fopen("[Link]", "r");
char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 27

19 Dynamic Memory Allocation

malloc, calloc, realloc, free


#include <stdlib.h>

// malloc — allocate block (uninitialized)


int *arr = (int*) malloc(5 * sizeof(int));
if (arr == NULL) { printf("Memory error!\n"); return 1; }

// calloc — allocate and zero-initialize


int *arr2 = (int*) calloc(5, sizeof(int));

// Use the memory


for (int i = 0; i < 5; i++) arr[i] = i * 10;

// realloc — resize allocation


arr = (int*) realloc(arr, 10 * sizeof(int));

// ALWAYS free when done


free(arr);
free(arr2);
arr = NULL; // prevent dangling pointer

Function Purpose

Allocate 'size' bytes (not


malloc(size) initialized)

calloc(n, size) Allocate n*size bytes, all set to 0

realloc(ptr, size) Resize previously allocated block

free(ptr) Release memory back to the system

⚠️CRITICAL: Always free() every malloc()/calloc(). Memory leaks cause programs to consume RAM
indefinitely.

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 28

20 Recursion

Recursive Functions
Recursion is when a function calls itself. Every recursive function needs a base case to stop.
// Factorial: n! = n * (n-1)!
int factorial(int n) {
if (n == 0 || n == 1) // base case
return 1;
return n * factorial(n - 1); // recursive case
}

printf("%d\n", factorial(5)); // → 120

// Fibonacci: F(n) = F(n-1) + F(n-2)


int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}

for (int i = 0; i < 8; i++)


printf("%d ", fib(i)); // → 0 1 1 2 3 5 8 13

// Sum of digits
int sumDigits(int n) {
if (n == 0) return 0;
return (n % 10) + sumDigits(n / 10);
}
printf("%d\n", sumDigits(1234)); // → 10

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 29

21 Command Line Arguments

argc and argv


// argc = argument count
// argv = argument vector (array of strings)

int main(int argc, char *argv[]) {


printf("Program: %s\n", argv[0]);
printf("Arguments: %d\n", argc - 1);

for (int i = 1; i < argc; i++) {


printf("Arg %d: %s\n", i, argv[i]);
}
return 0;
}

// Run as:
// ./program hello world 42
// → Program: ./program
// → Arguments: 3
// → Arg 1: hello
// → Arg 2: world
// → Arg 3: 42

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 30

22 Bitwise Operators

Bitwise Operations
Operator Name & Example (a=12=1100, b=10=1010)

& AND: 12 & 10 = 8 (1000)

| OR: 12 | 10 = 14 (1110)

^ XOR: 12 ^ 10 = 6 (0110)

~ NOT: ~12 = -13 (inverts all bits)

<< Left shift: 12 << 1 = 24 (multiply by 2)

>> Right shift: 12 >> 1 = 6 (divide by 2)

// Practical uses

// Check if even/odd using & 1


if (n & 1) printf("Odd\n");
else printf("Even\n");

// Set bit k: n = n | (1 << k)


// Clear bit k: n = n & ~(1 << k)
// Toggle bit k:n = n ^ (1 << k)
// Check bit k: if (n & (1 << k))

// Swap without temp (XOR trick)


a = a ^ b;
b = a ^ b;
a = a ^ b;

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 31

23 Common Algorithms in C

Sorting — Bubble Sort


void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

Searching — Binary Search


int binarySearch(int arr[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1; // not found
}

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 32

24 Error Handling & Debugging

errno & perror


#include <errno.h>
#include <string.h>

FILE *fp = fopen("[Link]", "r");


if (fp == NULL) {
perror("Error"); // prints system error message
printf("Error code: %d\n", errno);
printf("Message: %s\n", strerror(errno));
return 1;
}

assert for Debugging


#include <assert.h>

int divide(int a, int b) {


assert(b != 0); // program aborts if b is 0
return a / b;
}

Common C Errors
Error Cause

Invalid memory access — NULL/wild


Segmentation Fault pointer dereference

Stack Overflow Infinite recursion — no base case

Memory Leak malloc() without matching free()

Buffer Overflow Writing beyond array bounds

Dangling Pointer Using pointer after free()

Undefined Behavior Using uninitialized variables

Array index = length instead of


Off-by-one Error length-1

Integer Overflow Value exceeds data type range

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 33

25 Quick Reference Cheat Sheet

C PROGRAMMING CHEAT SHEET

Data Types Summary


Type Size Format Specifier

char 1 byte %c

int 4 bytes %d or %i

float 4 bytes %f

double 8 bytes %lf

long int 4-8 bytes %ld

unsigned int 4 bytes %u

char[] (string) n bytes %s

pointer 4 or 8 bytes %p

Standard Headers
Header Contents

printf, scanf, fopen, fclose, fgets,


<stdio.h> fprintf

malloc, free, exit, atoi, rand,


<stdlib.h> qsort

strlen, strcpy, strcat, strcmp,


<string.h> strstr

sqrt, pow, abs, sin, cos, log, ceil,


<math.h> floor

isdigit, isalpha, isupper, tolower,


<ctype.h> toupper

<time.h> time, clock, difftime, strftime

C Programming Notes • Mudit Bagra • For Academic Excellence


C PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 34

<assert.h> assert()

<errno.h> errno, perror, strerror

<limits.h> INT_MAX, INT_MIN, CHAR_MAX, etc.

Pointer Quick Reference


Syntax Meaning

int *p; Declare pointer to int

p = &x; p stores address of x

*p Value at address p

p++ Advance pointer by sizeof(int)

int **pp Pointer to pointer

int *arr = malloc(n*sizeof(int)); Dynamic array of n ints

free(p); p=NULL; Free memory & nullify pointer

⚙ Happy Coding in C! — Mudit Bagra ⚙

C Programming Notes • Mudit Bagra • For Academic Excellence

You might also like