c Language Notes
c Language Notes
Introduction to C Language
2. Basics of C Programming
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
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)
8. File Handling in C
9. Preprocessor Directives
#define, #include
Macro Substitution
Conditional Compilation (#ifdef, #ifndef, #endif)
Bitwise Operators
Enumerations (enum)
Typedef in C
Command-Line Arguments
Error Handling in C (perror, strerror)
⭐ 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
Example:
#include <stdio.h> // Preprocessor Directive
🔹 Step 2: Compilation
🔹 Step 3: Linking
🔹 Step 5: Execution
🔹 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:
Example:
int, float, char, double, if, else, return, void, switch, while,
etc.
✅ Identifiers:
Example:
Data types decide karte hain ki variable kis type ka data store karega.
C me primary data types ye hain:
✅ Constants:
Example:
✅ 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';
✅ Operators:
Operators wo symbols hote hain jo mathematical ya logical operations
perform karte hain.
🔹 Types of Operators:
Example:
int a = 10, b = 5;
int sum = a + b; // Arithmetic Operator
if (a > b) { // Relational Operator
printf("A is greater");
}
✅ Expressions:
✅ printf():
Example:
🔹 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:
📌 Decision-Making Statements
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:
Jab condition true hoti hai tab if block execute hota hai, aur agar false
hoti hai to else block execute hota hai.
Example:
Example:
int num = 0;
if (num > 0) {
printf("Positive Number");
} else {
if (num < 0) {
printf("Negative Number");
} else {
printf("Zero");
}
}
🔹 Output: Zero
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.
Jab hume fixed number of times execution karna ho to for loop best
hota hai.
Syntax:
Example:
🔹 Output: 1 2 3 4 5
Syntax:
while (condition) {
// Loop body
}
Example:
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
🔹 Output: 1 2 3 4 5
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.
Example:
🔹 Output: 1 2
continue current iteration skip karta hai aur next iteration start karta
hai.
Example:
🔹 Output: 1 2 4 5
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:
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.
Syntax:
return_type function_name(parameter_list);
Example:
✅ Function Definition
Function ka actual implementation hota hai jisme logic likha jata hai.
Syntax:
return_type function_name(parameters) {
// Function body
return value;
}
Example:
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:
Function kis type ka value return karega, ye return type decide karta
hai.
Example:
✅ Parameters:
Example:
✅ Call by Value
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;
}
✅ Call by Reference
Example:
int main() {
int a = 10;
change(&a);
printf("Value of a: %d", a);
return 0;
}
📌 Recursive Functions
Jab ek function khud ko call karta hai, to usse recursion kehte hain.
#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;
}
📌 Storage Classes
Storage classes variables ke lifetime, scope, aur memory location define karte
hain.
#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.
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
data_type array_name[size];
Example:
int numbers[5] = {10, 20, 30, 40, 50};
🔹 Accessing Elements
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
🔹 Output: 1 2 3 4 5
📌 Multi-Dimensional Arrays
data_type array_name[rows][columns];
Example:
🔹 Accessing Elements
🔹 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
#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;
}
char name[50];
gets(name); // Takes full sentence as input
puts(name); // Prints the string
⚠️Warning: gets() is unsafe, better to use fgets().
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length: %d", strlen(str)); // Output: 5
return 0;
}
🚀 Conclusion:
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
data_type *pointer_name;
Example:
int a = 10;
int *ptr = &a; // ptr me 'a' ka address store hoga
Example:
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
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
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Array ka first element ka
address
🔹 Output:
Value at ptr: 10
Value at ptr: 20
✅ Array ka naam khud ek pointer hota hai jo first element ka address store
karta hai.
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;
return 0;
}
🔹 Output:
arr[0]: 1, *(ptr): 1
arr[1]: 2, *(ptr+1): 2
arr[2]: 3, *(ptr+2): 3
#include <stdio.h>
int main() {
char *str = "Hello";
printf("%s", str); // Output: Hello
return 0;
}
#include <stdio.h>
int main() {
int num = 10;
changeValue(&num);
printf("New Value: %d", num); // Output: New
Value: 100
return 0;
}
📌 Pointers to Pointers
🔹 Example:
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
int **ptr2 = &ptr;
return 0;
}
🔹 Output:
Value of a: 10
Value using *ptr: 10
Value using **ptr2: 10
#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]);
}
🔹 Output: 1 2 3 4 5
🔹 calloc() - Memory Allocate karta hai aur Initialize bhi karta hai
🔹 Difference:
free(ptr);
🚀 Conclusion:
📌 Structures in C
struct Student {
char name[50];
int roll_no;
float marks;
};
s1.roll_no = 101;
s1.marks = 89.5;
strcpy(s1.name, "Rahul");
#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;
return 0;
}
🔹 Output:
Name: Rahul
Roll No: 101
Marks: 89.50
📌 Arrays of Structures
#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;
return 0;
}
🔹 Output:
📌 Nested Structures
#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;
return 0;
}
🔹 Output:
Name: Rahul
City: Delhi
PIN: 110001
📌 Pointer to Structures
#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;
return 0;
}
🔹 Output:
Name: Rahul
Roll No: 101
📌 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.
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
🔹 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:
✔️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.
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
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
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
FILE *ptr;
ptr = fopen("filename.txt", "mode");
fclose(ptr);
#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;
}
fclose(fp);
printf("Data written successfully!");
return 0;
}
int main() {
FILE *fp;
char str[100];
fclose(fp);
return 0;
}
🔹 Output:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fclose(fp);
return 0;
}
✅ 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
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("File not found!");
return 1;
}
char str[50];
fgets(str, 50, fp);
printf("Read after fseek: %s", str);
fclose(fp);
return 0;
}
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("File not found!");
return 1;
}
fclose(fp);
return 0;
}
🔹 Output:
Current Position: 0
After reading one char, Position: 1
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("File not found!");
return 1;
}
fclose(fp);
return 0;
}
🔹 Output:
🚀 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 in C
1. #define Directive
Syntax:
Example:
#include <stdio.h>
#define PI 3.14
int main() {
printf("The value of PI is: %.2f\n", PI);
return 0;
}
🔹 Output:
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:
int main() {
printf("Hello, World!\n");
return 0;
}
🔹 Explanation:
✅ 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.
Example:
#include <stdio.h>
int main() {
int num = 5;
printf("Square of %d is: %d\n", num,
SQUARE(num));
return 0;
}
🔹 Output:
Square of 5 is: 25
Important Notes:
📌 Conditional Compilation
✅ #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.
✅ #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:
✅ Explanation: Agar MAX_SIZE define nahi hai, to isse define kar diya
jayega.
3. #endif
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:
📌 Bitwise Operators
Examples:
🔹 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
🔹 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:
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:
Example:
#include <stdio.h>
int main() {
ULong num = 5000000000; // Now ULong is an alias
for unsigned long int
printf("The number is: %lu\n", num);
return 0;
}
🔹 Output:
#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:
📌 Command-Line Arguments
Syntax:
Example:
#include <stdio.h>
🔹 Command:
🔹 Output:
Explanation:
Error handling ek important part hota hai, jisse hum program ko run-time
errors ke time handle kar sakte hain.
1. perror()
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:
2. strerror()
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:
🚀 Conclusion:
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
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
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;
};
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:
Example:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int stack[MAX];
int top = -1;
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:
Example:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
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.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *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:
📌 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 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:
2. Binary Search
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:
📌 Sorting Algorithms in C
1. Bubble Sort
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: