0% found this document useful (0 votes)
3 views

c Language Notes

The document provides a comprehensive introduction to the C programming language, covering its history, features, and structure of a C program. It details fundamental concepts such as data types, control flow statements, functions, arrays, pointers, structures, file handling, and advanced topics. Additionally, it emphasizes the importance of C in system programming, embedded systems, and game development, making it a valuable language for programmers at all levels.

Uploaded by

ravi pandey
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)
3 views

c Language Notes

The document provides a comprehensive introduction to the C programming language, covering its history, features, and structure of a C program. It details fundamental concepts such as data types, control flow statements, functions, arrays, pointers, structures, file handling, and advanced topics. Additionally, it emphasizes the importance of C in system programming, embedded systems, and game development, making it a valuable language for programmers at all levels.

Uploaded by

ravi pandey
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
You are on page 1/ 57

1.

Introduction to C Language

 History and Features of C


 Structure of a C Program
 Compilation and Execution Process
 Uses and Applications of C

2. Basics of C Programming

 Keywords and Identifiers


 Data Types (int, float, char, double, etc.)
 Constants and Variables
 Operators and Expressions
 Input and Output Functions (printf, scanf)

3. Control Flow Statements

 Decision-Making Statements
o if, if-else, nested if-else
o switch-case
 Looping Statements
o for loop
o while loop
o do-while loop
 Jump Statements
o break and continue
o goto statement

4. Functions in C

 Function Declaration and Definition


 Function Calling Mechanism
 Return Type and Parameters
 Call by Value vs Call by Reference
 Recursive Functions
 Storage Classes (auto, static, extern, register)

5. Arrays and Strings

 One-Dimensional Arrays
 Multi-Dimensional Arrays
 Character Arrays and Strings
 String Handling Functions (strlen, strcpy, strcmp, etc.)

6. Pointers in C

 Introduction to Pointers
 Pointer Arithmetic
 Pointer to Array and String
 Pointers and Functions
 Pointers to Pointers
 Dynamic Memory Allocation (malloc, calloc, realloc, free)

7. Structures and Unions

 Defining and Using Structures


 Arrays of Structures
 Nested Structures
 Pointer to Structures
 Unions and Differences from Structures

8. File Handling in C

 File Operations (fopen, fclose, fread, fwrite, etc.)


 File Modes (read, write, append, etc.)
 Reading and Writing Files
 Random Access in Files (fseek, ftell, rewind)

9. Preprocessor Directives

 #define, #include
 Macro Substitution
 Conditional Compilation (#ifdef, #ifndef, #endif)

10. Advanced Topics

 Bitwise Operators
 Enumerations (enum)
 Typedef in C
 Command-Line Arguments
 Error Handling in C (perror, strerror)

11. Data Structures in C (Optional but Important)

 Arrays, Linked Lists (Singly, Doubly, Circular)


 Stacks and Queues
 Trees and Graphs (Basic Implementation)
 Searching and Sorting Algorithms
1. Introduction to C Language

📌 History and Features of C

 1969-1973: C language Dennis Ritchie ne Bell Labs me develop kiya.


 B Language se Development: C, B language ka upgraded version hai, jo
Ken Thompson ne develop ki thi.
 UNIX Development: C language ka primary use UNIX operating system
likhne ke liye hua.
 Portability: C programs kisi bhi hardware ya operating system par run ho
sakte hain.
 Popularity: Aaj bhi system programming, embedded systems aur game
development me widely use hoti hai.

⭐ Features of C:

 Simple & Efficient: Basic syntax simple hone ke saath efficient execution
provide karti hai.
 Fast Execution: Low-level memory access aur minimal runtime overhead
ki wajah se C fast hoti hai.
 Portability: Ek system se dusre system me easily move kiya ja sakta hai.
 Rich Library: C ke pas built-in functions aur operators ka bada collection
hai.
 Structured Programming: Code ko functions me divide kar sakte hain, jo
modular programming me help karta hai.
 Memory Management: Manual memory allocation (malloc, calloc,
free) provide karti hai.
 Extensibility: C ko doosri languages (jaise ki C++ aur Java) ke saath
integrate kar sakte hain.

2. Structure of a C Program

Ek C program multiple parts me divide hota hai:

1️⃣ Preprocessor Directives: #include<stdio.h>, #define


2️⃣ Main Function: int main() jo program execution start karta hai.
3️⃣ Variable Declaration: Program me jo bhi variables use karne hain, unhe
declare karna.
4️⃣ Statements & Expressions: Code execution ke liye logic likhna.
5️⃣ Return Statement: Program ka execution complete hone ke baad return
statement dena (return 0;).

Example:
#include <stdio.h> // Preprocessor Directive

int main() { // Main Function


int a = 10; // Variable Declaration
printf("Hello, C!"); // Statement
return 0; // Return Statement
}

3. Compilation and Execution Process

C program ko run karne ke liye Compilation aur Execution hota hai:

🔹 Step 1: Writing the Code (Source Code)

 .c extension wale file me code likhte hain. (e.g., program.c)

🔹 Step 2: Compilation

 Compiler (gcc, Turbo C) code ko machine code me convert karta hai.


 Syntax errors ko check karta hai.

🔹 Step 3: Linking

 Jo bhi external libraries (stdio.h, math.h, etc.) use ho rahi hain,


unhe link karta hai.

🔹 Step 4: Generating Executable File

 Compiler .exe ya .out file generate karta hai.

🔹 Step 5: Execution

 Program run hone par CPU instructions execute karta hai.

4. Uses and Applications of C

✅ System Programming: OS development (Linux, Windows) me use hoti hai.


✅ Embedded Systems: IoT devices aur microcontrollers me C ka use hota hai.
✅ Game Development: Low-level graphics programming me C ka role hota
hai.
✅ Database Systems: MySQL jaise database software me C ka use hota hai.
✅ Networking & Security: Network protocols aur firewalls me C ka use hota
hai.
✅ Compilers & Interpreters: Java, Python jaise languages ke compilers bhi C
me likhe gaye hain.

🔹 Conclusion:
C ek powerful aur efficient programming language hai jo har level ke
programmers ke liye useful hai. Agar aap programming ke basic concepts
samajhna chahte hain to C language best choice hai.

2. Basics of C Programming

📌 Keywords and Identifiers

✅ Keywords:

 Keywords wo predefined words hote hain jo C compiler ke liye special


meaning rakhte hain.
 Inka use variable ya function name ke roop me nahi kiya ja sakta.
 C me 32 keywords hote hain.

Example:
int, float, char, double, if, else, return, void, switch, while,
etc.

✅ Identifiers:

 Identifiers user-defined names hote hain jo variables, functions, arrays,


pointers ke liye use kiye jate hain.
 Yeh kisi bhi keyword se match nahi kar sakte.
 Identifiers alphabets (A-Z, a-z), digits (0-9), aur underscore (_) ka
combination ho sakte hain.

Example:

int age; // age ek identifier hai


float salary; // salary ek identifier hai

📌 Data Types (int, float, char, double, etc.)

 Data types decide karte hain ki variable kis type ka data store karega.
 C me primary data types ye hain:

Data Type Size Example


int 4 Bytes int a = 10;
Data Type Size Example
float 4 Bytes float pi = 3.14;
char 1 Byte char grade = 'A';
double 8 Bytes double price = 99.99;

🔹 Derived Data Types: Arrays, Pointers, Structures, Unions


🔹 User-defined Data Types: typedef, enum

📌 Constants and Variables

✅ Constants:

 Aise values jo program execution ke dauraan change nahi hoti.


 Constants ko #define ya const keyword se define kiya jata hai.

Example:

#define PI 3.1415 // Macro constant


const int age = 18; // Integer constant

✅ Variables:

 Variable ek memory location hota hai jisme data store kiya jata hai.
 Variable ka value change ho sakta hai execution ke dauraan.
 Har variable ka ek data type hota hai.

Example:

int a = 10;
float price = 25.50;
char grade = 'A';

📝 Variable Naming Rules:


✔️Sirf alphabets, numbers, aur underscore (_) use kar sakte hain.
✔️First character alphabet ya underscore hona chahiye.
✔️C case-sensitive hai (Age aur age alag variables hain).
📌 Operators and Expressions

✅ Operators:
Operators wo symbols hote hain jo mathematical ya logical operations
perform karte hain.

🔹 Types of Operators:

1️⃣ Arithmetic Operators: +, -, *, /, % (modulus)


2️⃣ Relational Operators: ==, !=, <, >, <=, >=
3️⃣ Logical Operators: && (AND), || (OR), ! (NOT)
4️⃣ Assignment Operators: =, +=, -=, *=, /=
5️⃣ Bitwise Operators: &, |, ^, <<, >>
6️⃣ Increment/Decrement: ++ (increment), -- (decrement)
7️⃣ Ternary Operator: condition ? value1 : value2

Example:

int a = 10, b = 5;
int sum = a + b; // Arithmetic Operator
if (a > b) { // Relational Operator
printf("A is greater");
}

✅ Expressions:

 Expression ek combination hota hai operands aur operators ka jo value


return karta hai.
 Example: a + b * c, x > y && y < z

📌 Input and Output Functions (printf, scanf)

✅ printf():

 Yeh function output dikhane ke liye use hota hai.


 Format Specifiers:
o %d (integer), %f (float), %c (character), %s (string)

Example:

int age = 25;


printf("Age is %d", age);

🔹 Output: Age is 25

✅ scanf():
 Yeh function user se input lene ke liye use hota hai.

Example:

int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d", num);

🔹 Output:

Enter a number: 10
You entered 10

🚀 Conclusion:

 C programming ke basics samajhna programming ki strong foundation


banane me madad karta hai.
 Keywords aur identifiers se syntax aur naming rules clear hote hain.
 Data types aur variables program me data store karne me help karte
hain.
 Operators aur expressions logical aur mathematical calculations ke liye
zaroori hain.
 printf aur scanf se user interaction possible hota hai.

3. Control Flow Statements in C

Control flow statements ka use program ke execution ko control karne ke liye


hota hai. Ye statements program ke flow ko decision-making, looping, aur
jump operations ke zariye modify karte hain.

📌 Decision-Making Statements

Decision-making statements program ko kisi condition ke basis par different


paths me execute karne dete hain.

1️⃣ if Statement

 if statement tab execute hota hai jab condition true hoti hai.

Syntax:

if (condition) {
// Execute this block if condition is true
}

Example:

int age = 20;


if (age >= 18) {
printf("You are eligible to vote.");
}

🔹 Output: You are eligible to vote.

2️⃣ if-else Statement

 Jab condition true hoti hai tab if block execute hota hai, aur agar false
hoti hai to else block execute hota hai.

Example:

int num = 10;


if (num % 2 == 0) {
printf("Even Number");
} else {
printf("Odd Number");
}

🔹 Output: Even Number

3️⃣ Nested if-else Statement

 Jab ek if ke andar doosra if ya if-else hota hai to use nested if-


else kehte hain.

Example:

int num = 0;
if (num > 0) {
printf("Positive Number");
} else {
if (num < 0) {
printf("Negative Number");
} else {
printf("Zero");
}
}
🔹 Output: Zero

4️⃣ switch-case Statement

 switch-case multiple conditions check karne ke liye best alternative


hai.
 if-else se zyada readable aur efficient hota hai jab multiple values
check karni ho.

Syntax:

switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code (if no case matches)
}

Example:

int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}

🔹 Output: Wednesday

📌 Looping Statements

Loops program ke ek part ko multiple times execute karne ke liye use hote
hain.

1️⃣ for Loop

 Jab hume fixed number of times execution karna ho to for loop best
hota hai.
Syntax:

for (initialization; condition; increment/decrement)


{
// Loop body
}

Example:

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


printf("%d ", i);
}

🔹 Output: 1 2 3 4 5

2️⃣ while Loop

 Jab hume unknown number of iterations chahiye aur condition true


hone tak execute karna ho tab while loop use hota hai.

Syntax:

while (condition) {
// Loop body
}

Example:

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

🔹 Output: 1 2 3 4 5

3️⃣ do-while Loop

 do-while loop pehle ek baar execute hota hai, phir condition check
hoti hai.

Syntax:

do {
// Loop body
} while (condition);

Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);

🔹 Output: 1 2 3 4 5

📌 Jump Statements

Jump statements program ke normal flow ko change karne ke liye use hote
hain.

1️⃣ break Statement

 break loop ko turant terminate kar deta hai.

Example:

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


if (i == 3) {
break; // Loop ends when i is 3
}
printf("%d ", i);
}

🔹 Output: 1 2

2️⃣ continue Statement

 continue current iteration skip karta hai aur next iteration start karta
hai.

Example:

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


if (i == 3) {
continue; // Skips when i is 3
}
printf("%d ", i);
}

🔹 Output: 1 2 4 5

3️⃣ goto Statement

 goto statement directly kisi label par jump karne ke liye use hota hai.
 Yeh bad programming practice mana jata hai kyunki isse code complex
ho jata hai.

Example:

int i = 1;
start:
printf("%d ", i);
i++;
if (i <= 5) {
goto start; // Jump back to start
}

🔹 Output: 1 2 3 4 5

🚀 Conclusion:

🔹 Decision-making statements (if, switch) program ke execution path


decide karte hain.
🔹 Looping statements (for, while, do-while) repetitive tasks execute
karne ke liye use hote hain.
🔹 Jump statements (break, continue, goto) execution flow ko modify
karte hain.

4. Functions in C

Function ek reusable block of code hota hai jo ek specific task perform karta
hai. Functions modular programming ko support karte hain, jisse code
readable aur maintainable hota hai.

📌 Function Declaration and Definition

✅ Function Declaration (Prototype)


 Function declare karne ka matlab compiler ko batana ki function exist
karta hai.
 Function declaration return type, function name aur parameters specify
karta hai.

Syntax:

return_type function_name(parameter_list);

Example:

int add(int, int); // Function declaration

✅ Function Definition

 Function ka actual implementation hota hai jisme logic likha jata hai.

Syntax:

return_type function_name(parameters) {
// Function body
return value;
}

Example:

int add(int a, int b) {


return a + b;
}

📌 Function Calling Mechanism

Function call karne ka matlab us function ko execute karna hai.

Example:

#include <stdio.h>

// Function declaration
int add(int, int);

int main() {
int result = add(5, 10); // Function call
printf("Sum: %d", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}

🔹 Output: Sum: 15

📌 Return Type and Parameters

✅ Return Type:

 Function kis type ka value return karega, ye return type decide karta
hai.

Example:

float divide(int a, int b) {


return (float)a / b; // float value return
karega
}

✅ Parameters:

 Function me parameters (arguments) bhejne se dynamic input


processing hoti hai.

Example:

void greet(char name[]) {


printf("Hello, %s!", name);
}

📌 Call by Value vs Call by Reference

✅ Call by Value

 Function me actual values ka copy pass hota hai.


 Function me changes original value ko affect nahi karte.

Example:

void change(int x) {
x = 100; // This change does not affect the
original variable
}
int main() {
int a = 10;
change(a);
printf("Value of a: %d", a);
return 0;
}

🔹 Output: Value of a: 10 (original value change nahi hui)

✅ Call by Reference

 Function me memory address (pointer) pass hota hai.


 Function changes original variable ko affect karte hain.

Example:

void change(int *x) {


*x = 100; // This change affects the original
variable
}

int main() {
int a = 10;
change(&a);
printf("Value of a: %d", a);
return 0;
}

🔹 Output: Value of a: 100 (original value change ho gayi)

📌 Recursive Functions

Jab ek function khud ko call karta hai, to usse recursion kehte hain.

✅ Example: Factorial using Recursion

#include <stdio.h>

int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}

int main() {
int num = 5;
printf("Factorial of %d is %d", num,
factorial(num));
return 0;
}

🔹 Output: Factorial of 5 is 120

📌 Storage Classes

Storage classes variables ke lifetime, scope, aur memory location define karte
hain.

Storage Class Scope Lifetime Default Value


auto Local Function ke end tak Garbage Value
static Local/Global Program ke end tak Zero (0)
extern Global Program ke end tak Zero (0)
register Local Function ke end tak Garbage Value

✅ Example of Storage Classes:

#include <stdio.h>

void demo() {
static int count = 0; // Static variable retains
value
count++;
printf("Count: %d\n", count);
}

int main() {
demo();
demo();
demo();
return 0;
}

🔹 Output:

Count: 1
Count: 2
Count: 3
🚀 Conclusion:

✔️Functions modular aur reusable code likhne ke liye essential hote hain.
✔️Call by Value me variable ka copy pass hota hai, jabki Call by Reference
me original memory address.
✔️Recursion self-calling functions ka concept hai jo factorial, Fibonacci
series jese problems me useful hai.
✔️Storage Classes variables ke scope aur lifetime define karte hain.

Agar aapko C language me efficiency aur modularity chahiye, to functions ka


proper use karna important hai!

5. Arrays and Strings in C

Array ek collection of similar data types ka ordered list hota hai, jisme same
type ke multiple values store kiya jata hai. Strings character arrays hote hain
jo text data store karne ke liye use kiye jate hain.

📌 One-Dimensional Arrays

✅ One-dimensional array ek single row ya single column ka collection hota


hai.

🔹 Declaration and Initialization

data_type array_name[size];

Example:
int numbers[5] = {10, 20, 30, 40, 50};

🔹 Accessing Elements

Array ke elements ko indexing (0-based index) se access kiya jata hai.

printf("%d", numbers[2]); // Output: 30

🔹 Array Traversal (Loop through Array)

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; i++) {


printf("%d ", arr[i]);
}
return 0;
}

🔹 Output: 1 2 3 4 5

📌 Multi-Dimensional Arrays

✅ Multi-dimensional array ek table-like structure hota hai jo rows aur


columns me data store karta hai.

🔹 Declaration and Initialization

data_type array_name[rows][columns];

Example:

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

🔹 Accessing Elements

printf("%d", matrix[1][2]); // Output: 6

🔹 2D Array Traversal

#include <stdio.h>

int main() {
int matrix[2][2] = {{1, 2}, {3, 4}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

🔹 Output:

1 2
3 4

📌 Character Arrays and Strings

✅ String ek character array hota hai jo '\0' (null character) ke sath


terminate hota hai.

🔹 Declaration and Initialization

char name[10] = "Hello";


char name[] = {'H', 'e', 'l', 'l', 'o', '\0'}; //
Same as above

🔹 String Input & Output

#include <stdio.h>

int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name); // Note: Does not take multi-
word input
printf("Hello, %s!", name);
return 0;
}

🔹 Input: John Doe


🔹 Output: Hello, John! (Only John print hoga kyunki scanf spaces ke
baad input nahi leta)

✅ Multi-word input lene ke liye gets() use kar sakte hain:

char name[50];
gets(name); // Takes full sentence as input
puts(name); // Prints the string
⚠️Warning: gets() is unsafe, better to use fgets().

📌 String Handling Functions

C me string.h library ke predefined functions strings ko manipulate karne


ke liye use hote hain.

🔹 strlen() - String Length

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello";
printf("Length: %d", strlen(str)); // Output: 5
return 0;
}

🔹 strcpy() - Copy String

char source[] = "Hello";


char destination[10];
strcpy(destination, source);
printf("%s", destination); // Output: Hello

🔹 strcmp() - Compare Strings

if (strcmp("apple", "banana") < 0) {


printf("Apple comes before Banana");
}

🔹 strcat() - Concatenate Strings

char str1[20] = "Hello, ";


char str2[] = "World!";
strcat(str1, str2);
printf("%s", str1); // Output: Hello, World!

🚀 Conclusion:

✔️One-dimensional array data store karne ke liye use hota hai.


✔️Multi-dimensional array rows aur columns ke form me data store karta hai.
✔️Strings character arrays hote hain jo text store karne ke liye use kiye
jate hain.
✔️Predefined string functions string manipulation ke liye use hote hain.
Agar aapko efficient C programming seekhni hai, to arrays aur strings ka
proper understanding bahut zaroori hai!

6. Pointers in C

Pointer ek special variable hota hai jo kisi memory location ka address store
karta hai. Yeh efficient memory management aur dynamic memory
allocation me kaafi useful hote hain.

📌 Introduction to Pointers

✅ Pointer ek variable hota hai jo kisi dusre variable ke memory address ko


store karta hai.

🔹 Pointer Declaration and Initialization

data_type *pointer_name;

Example:

int a = 10;
int *ptr = &a; // ptr me 'a' ka address store hoga

✅ & (Address-of operator): Kisi variable ka address return karta hai.


✅ * (Dereference operator): Pointer ke andar stored address pe jo value hai,
usko access karta hai.

Example:

#include <stdio.h>

int main() {
int a = 10;
int *ptr = &a;

printf("Value of a: %d\n", a);


printf("Address of a: %p\n", &a);
printf("Pointer ptr stores address: %p\n", ptr);
printf("Value at address stored in ptr: %d\n",
*ptr);

return 0;
}

🔹 Output:
Value of a: 10
Address of a: 0x7ffcd0b6
Pointer ptr stores address: 0x7ffcd0b6
Value at address stored in ptr: 10

📌 Pointer Arithmetic

✅ Pointer ke sath arithmetic operations bhi perform ho sakte hain:

 ptr + 1 → Next memory location


 ptr - 1 → Previous memory location

#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Array ka first element ka
address

printf("Value at ptr: %d\n", *ptr);


ptr++; // Move to next element
printf("Value at ptr: %d\n", *ptr);
return 0;
}

🔹 Output:

Value at ptr: 10
Value at ptr: 20

📌 Pointer to Array and String

✅ Array ka naam khud ek pointer hota hai jo first element ka address store
karta hai.

🔹 Array and Pointer Relationship

#include <stdio.h>

int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;

printf("arr[0]: %d, *(ptr): %d\n", arr[0], *ptr);


printf("arr[1]: %d, *(ptr+1): %d\n", arr[1],
*(ptr+1));
printf("arr[2]: %d, *(ptr+2): %d\n", arr[2],
*(ptr+2));

return 0;
}

🔹 Output:

arr[0]: 1, *(ptr): 1
arr[1]: 2, *(ptr+1): 2
arr[2]: 3, *(ptr+2): 3

✅ String Pointer Example:

#include <stdio.h>

int main() {
char *str = "Hello";
printf("%s", str); // Output: Hello
return 0;
}

📌 Pointers and Functions

✅ Pointers functions me arguments ke reference ko pass karne ke liye use


hote hain.

🔹 Call by Reference using Pointers

#include <stdio.h>

void changeValue(int *x) {


*x = 100; // Pointer ka use karke original value
modify karna
}

int main() {
int num = 10;
changeValue(&num);
printf("New Value: %d", num); // Output: New
Value: 100
return 0;
}
📌 Pointers to Pointers

✅ Pointer jo ek aur pointer ke address ko store karta hai, use pointer to


pointer kehte hain.

🔹 Example:

#include <stdio.h>

int main() {
int a = 10;
int *ptr = &a;
int **ptr2 = &ptr;

printf("Value of a: %d\n", a);


printf("Value using *ptr: %d\n", *ptr);
printf("Value using **ptr2: %d\n", **ptr2);

return 0;
}

🔹 Output:

Value of a: 10
Value using *ptr: 10
Value using **ptr2: 10

📌 Dynamic Memory Allocation

✅ C me dynamic memory allocation ke liye malloc, calloc, realloc,


aur free functions use hote hain.
✅ Yeh functions stdlib.h library me available hote hain.

🔹 malloc() - Memory Allocate karta hai but Initialize nahi karta

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int *)malloc(5 * sizeof(int)); // 5
integers ke liye memory allocate

if (ptr == NULL) {
printf("Memory allocation failed!");
return 1;
}
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1;
printf("%d ", ptr[i]);
}

free(ptr); // Memory free karna zaroori hai


return 0;
}

🔹 Output: 1 2 3 4 5

🔹 calloc() - Memory Allocate karta hai aur Initialize bhi karta hai

int *ptr = (int *)calloc(5, sizeof(int)); // 5


integers initialize with 0

🔹 Difference:

Function Initialization Use Case


malloc() Garbage Value Faster, when initialization not needed
calloc() Zero (0) When zero-initialization is needed

🔹 realloc() - Existing Memory Resize karta hai

ptr = (int *)realloc(ptr, 10 * sizeof(int)); //


Resize memory to 10 integers

🔹 free() - Dynamically Allocated Memory ko Free karta hai

free(ptr);

🚀 Conclusion:

✔️Pointers ek variable ka memory address store karte hain.


✔️Pointer arithmetic se memory address manipulation ho sakta hai.
✔️Pointers ko arrays, strings, aur functions ke sath efficiently use kiya jata
hai.
✔️Dynamic memory allocation se runtime memory manage karna possible
hota hai (malloc, calloc, realloc, free).
Agar aapko C programming me efficiency aur flexibility chahiye, to
pointers ka strong understanding hona bahut zaroori hai!

7. Structures and Unions in C

C language me structures aur unions ka use complex data types ko store


karne ke liye kiya jata hai. Yeh dono multiple data members ko ek single unit
me group karne ki suvidha dete hain.

📌 Structures in C

✅ Structure ek user-defined data type hai jo different types ke multiple


variables ko ek sath store karne ke liye use hota hai.

🔹 Defining and Using Structures

struct Student {
char name[50];
int roll_no;
float marks;
};

🔹 Structure ka variable declare karna:

struct Student s1;

🔹 Structure ke members ko access karna:

s1.roll_no = 101;
s1.marks = 89.5;
strcpy(s1.name, "Rahul");

🔹 Example: Structure ka use karna

#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int roll_no;
float marks;
};

int main() {
struct Student s1;

strcpy(s1.name, "Rahul");
s1.roll_no = 101;
s1.marks = 89.5;

printf("Name: %s\n", s1.name);


printf("Roll No: %d\n", s1.roll_no);
printf("Marks: %.2f\n", s1.marks);

return 0;
}

🔹 Output:

Name: Rahul
Roll No: 101
Marks: 89.50

📌 Arrays of Structures

✅ Agar ek se zyada students ka data store karna ho, to structure ka array


use kiya jata hai.

#include <stdio.h>
#include <string.h>

struct Student {
char name[50];
int roll_no;
float marks;
};

int main() {
struct Student s[2];

strcpy(s[0].name, "Rahul");
s[0].roll_no = 101;
s[0].marks = 90.5;
strcpy(s[1].name, "Amit");
s[1].roll_no = 102;
s[1].marks = 85.3;

for (int i = 0; i < 2; i++) {


printf("Name: %s, Roll No: %d, Marks: %.2f\
n", s[i].name, s[i].roll_no, s[i].marks);
}

return 0;
}

🔹 Output:

Name: Rahul, Roll No: 101, Marks: 90.50


Name: Amit, Roll No: 102, Marks: 85.30

📌 Nested Structures

✅ Ek structure ke andar doosra structure define karna nested structure


hota hai.

#include <stdio.h>
#include <string.h>

struct Address {
char city[20];
int pin;
};

struct Student {
char name[50];
struct Address addr;
};

int main() {
struct Student s1;
strcpy(s1.name, "Rahul");
strcpy(s1.addr.city, "Delhi");
s1.addr.pin = 110001;

printf("Name: %s\nCity: %s\nPIN: %d\n", s1.name,


s1.addr.city, s1.addr.pin);

return 0;
}
🔹 Output:

Name: Rahul
City: Delhi
PIN: 110001

📌 Pointer to Structures

✅ Structure ka address store karne ke liye pointers ka use hota hai.

#include <stdio.h>
#include <string.h>

struct Student {
char name[50];
int roll_no;
};

int main() {
struct Student s1 = {"Rahul", 101};
struct Student *ptr = &s1;

printf("Name: %s\n", ptr->name); // Using arrow


operator (->)
printf("Roll No: %d\n", ptr->roll_no);

return 0;
}

🔹 Output:

Name: Rahul
Roll No: 101

🔹 Note: ptr->name shortcut hai (*ptr).name ka.

📌 Unions in C

✅ Union ek special data type hai jo memory ko efficiently use karta hai.
✅ Ek time me sirf ek hi member active rah sakta hai.

🔹 Defining and Using Unions

union Data {
int i;
float f;
char str[20];
};

🔹 Example:

#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data d;

d.i = 10;
printf("i: %d\n", d.i);

d.f = 20.5;
printf("f: %.2f\n", d.f);

strcpy(d.str, "Hello");
printf("str: %s\n", d.str);

return 0;
}

🔹 Output:

i: 10
f: 20.50
str: Hello

🚀 Lekin dikkat ye hai ki ek waqt me sirf ek member ka data accessible hota


hai.

📌 Difference Between Structures and Unions


Feature Structure Union
Memory Har member ke liye alag Sabhi members ek memory share
Usage memory karte hain
Size Har member ka total size hota Sirf largest member ka size hota
Feature Structure Union
hai hai
Saare members ek sath access Ek waqt me sirf ek member
Access
ho sakte hain access ho sakta hai

🔹 Example:

struct Example {
int x;
char y;
float z;
};

union ExampleU {
int x;
char y;
float z;
};

int main() {
printf("Size of struct: %lu\n", sizeof(struct
Example));
printf("Size of union: %lu\n", sizeof(union
ExampleU));
return 0;
}

🔹 Output:

Size of struct: 12
Size of union: 4

🚀 Conclusion: Structure zyada memory leta hai, jabki union memory-efficient


hota hai.

🚀 Conclusion:

✔️Structures multiple data types ko ek sath store karne ke liye use hote
hain.
✔️Arrays of structures ek se zyada records store karne ke liye useful hain.
✔️Nested structures ek structure ke andar doosra structure use karne ki
suvidha dete hain.
✔️Pointers ke sath structures ko dynamically manage kiya ja sakta hai.
✔️Unions ek time me sirf ek hi value store karte hain, jo memory efficient
hota hai.

Agar aapko C me data ko efficiently manage karna hai, to structures aur


unions ka proper understanding bahut zaroori hai!

8. File Handling in C

File handling data ko permanent store karne ka ek tarika hai. Yeh C language
ka ek important feature hai, jisme hum files ko create, read, write aur
modify kar sakte hain.

📌 File Operations in C

✅ C language me file handling ke liye stdio.h library ka use hota hai.


✅ Files ko handle karne ke liye important functions:

Function Description
fopen() File open karne ke liye
fclose() File close karne ke liye
fread() File se data read karne ke liye
fwrite() File me data write karne ke liye
fprintf() File me formatted data likhne ke liye
fscanf() File se formatted data read karne ke liye
fgetc() File se ek character read karne ke liye
fputc() File me ek character write karne ke liye
fgets() File se ek line read karne ke liye
fputs() File me ek line write karne ke liye

📌 File Modes in C

✅ File open karne ke alag-alag modes hote hain, jo file ke behavior ko


define karte hain.

Mode Meaning
"r" Read mode, agar file exist nahi karti to error aayega
Mode Meaning
"w" Write mode, agar file exist karti hai to purani file delete ho jayegi
"a" Append mode, naya data file ke end me add karega
"r+" Read/Write mode, file exist honi chahiye
"w+" Read/Write mode, purani file delete ho jayegi
"a+" Read/Append mode, naya data file ke end me add karega

📌 Reading and Writing Files

✅ File open aur close karne ka basic syntax:

FILE *ptr;
ptr = fopen("filename.txt", "mode");
fclose(ptr);

🔹 Writing to a File (fprintf and fputs)

#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("test.txt", "w"); // File open in
write mode

if (fp == NULL) {
printf("File open error!");
return 1;
}

fprintf(fp, "Hello, this is a test file.\n");


fputs("This is another line.\n", fp);

fclose(fp);
printf("Data written successfully!");
return 0;
}

🔹 Output: test.txt file me data likh diya jayega.

🔹 Reading from a File (fscanf, fgets)


#include <stdio.h>

int main() {
FILE *fp;
char str[100];

fp = fopen("test.txt", "r"); // File open in read


mode
if (fp == NULL) {
printf("File does not exist!");
return 1;
}

while (fgets(str, 100, fp) != NULL) {


printf("%s", str);
}

fclose(fp);
return 0;
}

🔹 Output:

Hello, this is a test file.


This is another line.

🔹 Character-by-Character File Handling (fgetc, fputc)

#include <stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen("test.txt", "r"); // Read mode


if (fp == NULL) {
printf("File not found!");
return 1;
}

while ((ch = fgetc(fp)) != EOF) {


printf("%c", ch);
}

fclose(fp);
return 0;
}

🔹 Output: File ka har character alag-alag print hoga.

📌 Random Access in Files (fseek, ftell, rewind)

✅ Sometimes hume file ke kisi specific position se data read ya write karna
hota hai.

Function Description
fseek(fp, offset, origin) File pointer ko move karne ke liye
ftell(fp) Current position return karta hai
rewind(fp) File pointer ko start position pe le jata hai

🔹 fseek() Example (File Pointer Move Karna)

#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("test.txt", "r");

if (fp == NULL) {
printf("File not found!");
return 1;
}

fseek(fp, 6, SEEK_SET); // File pointer ko 6th


position pe move karo

char str[50];
fgets(str, 50, fp);
printf("Read after fseek: %s", str);

fclose(fp);
return 0;
}

🔹 Output: fseek() ke baad 6th character se text read hoga.


🔹 ftell() Example (Current Position Find Karna)

#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("test.txt", "r");

if (fp == NULL) {
printf("File not found!");
return 1;
}

printf("Current Position: %ld\n", ftell(fp));


fgetc(fp); // Ek character read karo
printf("After reading one char, Position: %ld\n",
ftell(fp));

fclose(fp);
return 0;
}

🔹 Output:

Current Position: 0
After reading one char, Position: 1

🔹 rewind() Example (File Pointer Reset Karna)

#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("test.txt", "r");

if (fp == NULL) {
printf("File not found!");
return 1;
}

fseek(fp, 10, SEEK_SET);


printf("Position before rewind: %ld\n",
ftell(fp));

rewind(fp); // File pointer ko wapas start pe le


aao
printf("Position after rewind: %ld\n",
ftell(fp));

fclose(fp);
return 0;
}

🔹 Output:

Position before rewind: 10


Position after rewind: 0

🚀 Conclusion:

✔️File handling data ko permanently store karne ke liye use hota hai.
✔️File modes se define hota hai ki hum file ko read/write/append kar sakte
hain.
✔️Basic file operations me fopen(), fclose(), fscanf(),
fprintf(), fgets() aur fputs() aate hain.
✔️Random access ke liye fseek(), ftell(), rewind() ka use hota hai.

Agar aapko C me data persistence aur efficient file management karna hai,
to file handling ka proper understanding zaroori hai!

9. Preprocessor Directives in C

Preprocessor directives C program ke compilation ke pehle execute hote


hain. Yeh compiler ko instructions dete hain, jise program ke code ko modify
karne ke liye use kiya jata hai. Yeh compiler se code ko process karne ke liye
pehle kaam karte hain, jaise files ko include karna, constants define karna, aur
conditional compilation karna.

📌 Preprocessor Directives in C

1. #define Directive

✅ #define ka use constants ya macros ko define karne ke liye kiya jata


hai.

Syntax:

#define constant_name value

Example:
#include <stdio.h>

#define PI 3.14

int main() {
printf("The value of PI is: %.2f\n", PI);
return 0;
}

🔹 Output:

The value of PI is: 3.14

✅ Yahaan PI ko constant 3.14 se replace kar diya gaya hai.

2. #include Directive

✅ #include ka use header files ko include karne ke liye hota hai, jo pre-
defined functions aur constants provide karte hain.

Syntax:
#include <header_file>

Ya

#include "header_file"

 < > ka use standard libraries ko include karne ke liye hota hai.
 " " ka use user-defined libraries ko include karne ke liye hota hai.

Example:

#include <stdio.h> // Standard library


#include "myheader.h" // User-defined library

int main() {
printf("Hello, World!\n");
return 0;
}

🔹 Explanation:

 <stdio.h> standard library hai jo input/output functions (jaise


printf) provide karti hai.
 "myheader.h" ek user-defined header file ho sakti hai.
📌 Macro Substitution

✅ Macro ka use reusable code ko define karne ke liye kiya jata hai jo
program ke different parts me use ho sakta hai.
✅ Macro ek preprocessor directive hai jo variable ya function ko substitute
karta hai jab program compile hota hai.

Syntax for Macros:

#define MACRO_NAME(parameters) replacement_code

Example:

#include <stdio.h>

#define SQUARE(x) ((x) * (x))

int main() {
int num = 5;
printf("Square of %d is: %d\n", num,
SQUARE(num));
return 0;
}

🔹 Output:

Square of 5 is: 25

✅ Explanation: SQUARE(5) ko compile time me (5 * 5) me convert kar


diya gaya hai.

Important Notes:

 Macros ko function ki tarah treat kiya jata hai.


 Bracket use karo inside macro definition to avoid errors due to operator
precedence.

📌 Conditional Compilation

✅ Conditional compilation ka use code ko specific conditions ke basis pe


compile karne ke liye hota hai.
✅ Iska use alag-alag platform-specific code ya debug code ko
include/exclude karne ke liye hota hai.
✅ #ifdef, #ifndef, #endif directives ka use hota hai conditional
compilation me.
1. #ifdef (If Defined)

✅ #ifdef ka use tab hota hai jab aap check karna chahte hain ki koi
macro define kiya gaya hai ya nahi.

Syntax:

#ifdef MACRO_NAME
// Code block
#endif

Example:

#include <stdio.h>

#define DEBUG

int main() {
#ifdef DEBUG
printf("Debug mode is ON\n");
#endif
printf("Program is running\n");
return 0;
}

🔹 Output:

Debug mode is ON
Program is running

✅ Explanation: Jab DEBUG define hota hai, tab debug-related code execute
hota hai.

2. #ifndef (If Not Defined)

✅ #ifndef ka use tab hota hai jab aap ensure karna chahte hain ki koi
macro define nahi kiya gaya ho.

Syntax:

#ifndef MACRO_NAME
// Code block
#endif
Example:

#include <stdio.h>

#ifndef MAX_SIZE
#define MAX_SIZE 100
#endif

int main() {
printf("Max size is: %d\n", MAX_SIZE);
return 0;
}

🔹 Output:

Max size is: 100

✅ Explanation: Agar MAX_SIZE define nahi hai, to isse define kar diya
jayega.

3. #endif

✅ #endif ka use #ifdef aur #ifndef ke block ko close karne ke liye


hota hai.

4. #if, #elif, #else (Advanced Conditional Compilation)

✅ Agar aapko complex conditions check karni ho to #if, #elif, aur


#else ka use kar sakte hain.

Syntax:

#if condition
// Code block
#elif condition
// Code block
#else
// Code block
#endif

Example:

#include <stdio.h>
#define PLATFORM "Windows"

int main() {
#if defined(PLATFORM) && (PLATFORM == "Windows")
printf("This is Windows platform\n");
#else
printf("This is not Windows\n");
#endif
return 0;
}

🚀 Conclusion:

✔️Preprocessor directives C code ko modify karte hain, jise compile hone


se pehle process kiya jata hai.
✔️#define ka use constants aur macros define karne ke liye hota hai.
✔️#include ka use files ko include karne ke liye hota hai.
✔️Macro substitution se hum repetitive code ko short karte hain.
✔️Conditional compilation se hum specific code ko platform ya condition
ke basis pe compile karte hain.
✔️#ifdef, #ifndef, #endif, #if, #elif, #else ka use conditional
compilation me hota hai.

10. Advanced Topics in C

C programming me kuch advanced topics hote hain jo aapke programming


skills ko next level tak le jaate hain. Yeh topics aapko efficiency, portability,
aur robustness mein help karte hain. Chaliye in advanced topics ko detail mein
samajhte hain.

📌 Bitwise Operators

Bitwise operators binary numbers pe operations perform karte hain. Yeh


operators bits (0s and 1s) ko manipulate karte hain, jo low-level programming
tasks mein kaafi useful hote hain.

Types of Bitwise Operators:


Operator Description
& Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift

Examples:

1. Bitwise AND (&)


2.#include <stdio.h>
3.
4.int main() {
5. int a = 5; // 0101
6. int b = 3; // 0011
7. int result = a & b; // 0001 (1 in decimal)
8. printf("a & b = %d\n", result);
9. return 0;
10. }

🔹 Output:

a & b = 1

11.Bitwise OR (|)
12. #include <stdio.h>
13.
14. int main() {
15. int a = 5; // 0101
16. int b = 3; // 0011
17. int result = a | b; // 0111 (7 in decimal)
18. printf("a | b = %d\n", result);
19. return 0;
20. }

🔹 Output:

a | b = 7

21.Left Shift (<<)


22. #include <stdio.h>
23.
24. int main() {
25. int a = 5; // 0101
26. int result = a << 1; // 1010 (10 in
decimal)
27. printf("a << 1 = %d\n", result);
28. return 0;
29. }

🔹 Output:

a << 1 = 10

📌 Enumerations (enum)

Enumeration (enum) integer values ko readable names dene ke liye use hoti
hai. Yeh ek user-defined type hai jisme aap custom identifiers ko define kar
sakte hain jo internally integers represent karte hain.

Syntax:

enum EnumName {
Identifier1,
Identifier2,
Identifier3
};

Example:

#include <stdio.h>

enum Weekday {
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
};

int main() {
enum Weekday today = Wednesday;
printf("The value of today is: %d\n", today);
return 0;
}
🔹 Output:

The value of today is: 3

Custom Values in enum:

enum Weekday {
Sunday = 1, // 1
Monday, // 2
Tuesday, // 3
Wednesday, // 4
Thursday, // 5
Friday, // 6
Saturday // 7
};

📌 Typedef in C

typedef ka use ek existing data type ko ek new name (alias) dene ke liye hota
hai. Yeh code ko simplify karne aur readability improve karne ke liye use hota
hai, especially jab hum complex data types (like structs) ka use karte hain.

Syntax:

typedef existing_type new_name;

Example:

#include <stdio.h>

typedef unsigned long int ULong;

int main() {
ULong num = 5000000000; // Now ULong is an alias
for unsigned long int
printf("The number is: %lu\n", num);
return 0;
}

🔹 Output:

The number is: 5000000000

Using typedef with Structs:

#include <stdio.h>
typedef struct {
int id;
char name[20];
} Student;

int main() {
Student s1 = {1, "John"};
printf("ID: %d, Name: %s\n", s1.id, s1.name);
return 0;
}

🔹 Output:

ID: 1, Name: John

📌 Command-Line Arguments

Command-line arguments program ko run karte waqt external inputs pass


karne ka ek tareeka hai. Iska use runtime pe data provide karne ke liye hota
hai, jaise file names, input data, etc.

Syntax:

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


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

Example:

#include <stdio.h>

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


printf("Total arguments passed: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}

🔹 Command:

./program arg1 arg2 arg3

🔹 Output:

Total arguments passed: 4


Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

Explanation:

 argc: Total number of arguments.


 argv[]: Array of arguments passed to the program.

📌 Error Handling in C (perror, strerror)

Error handling ek important part hota hai, jisse hum program ko run-time
errors ke time handle kar sakte hain.

1. perror()

 perror() ek built-in function hai jo error messages print karta hai


based on errno (a global variable).

Syntax:

perror("Error message");

Example:

#include <stdio.h>
#include <errno.h>

int main() {
FILE *fp = fopen("nonexistent_file.txt", "r");
if (fp == NULL) {
perror("File open failed");
}
return 0;
}

🔹 Output:

File open failed: No such file or directory

2. strerror()

strerror() function error code ko human-readable message me convert


karta hai.
Syntax:

char *strerror(int errnum);

Example:

#include <stdio.h>
#include <string.h>

int main() {
printf("Error Message: %s\n", strerror(2)); // 2
= ENOENT (No such file or directory)
return 0;
}

🔹 Output:

Error Message: No such file or directory

🚀 Conclusion:

✔️Bitwise operators low-level data manipulation ke liye use hota hai.


✔️Enumerations (enum) ko use karke hum constants ko readable names de
sakte hain.
✔️Typedef se hum complex types ko simple alias de sakte hain.
✔️Command-line arguments se hum program ko runtime me input data de
sakte hain.
✔️Error handling se hum program me errors ko efficiently manage kar sakte
hain using perror() and strerror().

C programming me yeh advanced concepts aapko more control aur


flexibility dete hain.

11. Data Structures in C (Optional but Important)

Data structures ka use efficient data storage, access, aur modification ke liye
hota hai. C language me data structures ka implementation low-level aur
flexible hota hai, jo performance-critical applications me kaafi useful hota hai.
Aaj hum kuch important data structures jaise arrays, linked lists, stacks,
queues, trees, graphs, aur searching/sorting algorithms ke baare me
samjhenge.
📌 Arrays in C

Arrays ek collection of elements hota hai, jisme same type ke data store kiye
jaate hain. Array ka size ek baar define kiya jaata hai, aur uske baad usme
elements access karne ke liye indexing ka use hota hai.

Syntax:

data_type array_name[array_size];

Example:

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

🔹 Output:

1 2 3 4 5

📌 Linked Lists in C

1. Singly Linked List

A singly linked list me har node ek data aur next node ka address rakhti hai.
Isme ek direction me data traverse kiya jaata hai.

Node Structure:
struct Node {
int data;
struct Node *next;
};
Example:
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};
int main() {
struct Node *head = NULL, *temp = NULL;
// Create a new node
temp = (struct Node*) malloc(sizeof(struct
Node));
temp->data = 10;
temp->next = NULL;
head = temp;
printf("Data: %d\n", head->data);
return 0;
}

🔹 Output:

Data: 10

2. Doubly Linked List

A doubly linked list me har node me do pointers hote hain: ek apne next node
ko point karta hai aur dusra apne previous node ko.

Node Structure:
struct Node {
int data;
struct Node *next;
struct Node *prev;
};

3. Circular Linked List

In a circular linked list, last node ka next pointer head node ko point karta
hai, thus making a loop.

📌 Stacks in C

A stack ek LIFO (Last In First Out) data structure hota hai, jisme last
inserted element pehle remove hota hai. Stack me push (element insert karna)
aur pop (element remove karna) operations hote hain.

Operations:

 Push: Stack me element add karna


 Pop: Stack se element nikalna
 Peek/Top: Stack ka top element dekhna
 isEmpty: Stack empty hai ya nahi

Example:
#include <stdio.h>
#include <stdlib.h>

#define MAX 5
int stack[MAX];
int top = -1;

void push(int value) {


if (top < MAX - 1) {
stack[++top] = value;
printf("%d pushed to stack\n", value);
} else {
printf("Stack Overflow\n");
}
}

int pop() {
if (top >= 0) {
return stack[top--];
} else {
printf("Stack Underflow\n");
return -1;
}
}

int main() {
push(10);
push(20);
printf("%d popped from stack\n", pop());
return 0;
}

🔹 Output:

10 pushed to stack
20 pushed to stack
20 popped from stack

📌 Queues in C

A queue ek FIFO (First In First Out) data structure hota hai, jisme first
inserted element pehle remove hota hai. Queue me enqueue (element insert
karna) aur dequeue (element remove karna) operations hote hain.
Operations:

 Enqueue: Queue me element add karna


 Dequeue: Queue se element nikalna
 Front: Queue ka front element dekhna
 isEmpty: Queue empty hai ya nahi

Example:
#include <stdio.h>
#include <stdlib.h>

#define MAX 5
int queue[MAX];
int front = -1, rear = -1;

void enqueue(int value) {


if (rear < MAX - 1) {
if (front == -1) front = 0;
queue[++rear] = value;
printf("%d enqueued to queue\n", value);
} else {
printf("Queue Overflow\n");
}
}

int dequeue() {
if (front <= rear && front != -1) {
return queue[front++];
} else {
printf("Queue Underflow\n");
return -1;
}
}

int main() {
enqueue(10);
enqueue(20);
printf("%d dequeued from queue\n", dequeue());
return 0;
}

🔹 Output:

10 enqueued to queue
20 enqueued to queue
10 dequeued from queue
📌 Trees in C

A tree ek hierarchical data structure hai jisme root node se branches spread
hoti hain. Binary tree ek tree ka type hota hai jisme har node ke maximum 2
children hote hain.

Binary Tree Example:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *left, *right;
};

struct Node* newNode(int data) {


struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}

void inorder(struct Node* root) {


if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
printf("Inorder traversal: ");
inorder(root);
return 0;
}

🔹 Output:

Inorder traversal: 2 1 3
📌 Graphs in C

A graph ek non-linear data structure hai jisme nodes (vertices) aur edges hote
hain jo nodes ko connect karte hain. Graph ko directed ya undirected banaya
ja sakta hai.

Graph Representation:

 Adjacency Matrix: 2D array ka use karke graph ko represent karte hain.


 Adjacency List: Linked list ka use karke graph ko represent karte hain.

📌 Searching Algorithms in C

1. Linear Search

Linear search ek simple algorithm hai jo har element ko ek-ek karke search
karta hai.

Example:
#include <stdio.h>

int linearSearch(int arr[], int n, int key) {


for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int result = linearSearch(arr, 5, 30);
printf("Element found at index: %d\n", result);
return 0;
}

🔹 Output:

Element found at index: 2

2. Binary Search

Binary search ek efficient algorithm hai jo sorted array me mid element ke


comparison se search karte hain.

Example:
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int
key) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int result = binarySearch(arr, 0, 4, 30);
printf("Element found at index: %d\n", result);
return 0;
}

🔹 Output:

Element found at index: 2

📌 Sorting Algorithms in C

1. Bubble Sort

Bubble sort ek simple sorting algorithm hai jisme adjacent elements ko


compare karke swap kiya jata hai.

2. Selection Sort

Selection sort me minimum element ko select karke usse swap kiya jata hai.

3. Insertion Sort

Insertion sort me elements ko ek-ek karke sorted order me insert kiya jata hai.

🚀 Conclusion:

✔️Arrays, Linked Lists, Stacks, Queues aapko basic data structures ke


concepts samjhate hain.
✔️Trees aur Graphs ko samajhkar aap complex hierarchical aur interconnected
data ko efficiently represent kar sakte hain.
✔️Searching aur Sorting algorithms aapko data ko efficiently search aur
organize karne me help karte hain.

You might also like