0% found this document useful (0 votes)
4 views53 pages

C Programming Handbook.

The document provides an introduction to C programming, covering its features, basic structure, variables, data types, operators, control structures, and functions. It highlights the simplicity and efficiency of C, along with its modularity and rich library. The document includes examples of C syntax and programs to illustrate the concepts discussed.

Uploaded by

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

C Programming Handbook.

The document provides an introduction to C programming, covering its features, basic structure, variables, data types, operators, control structures, and functions. It highlights the simplicity and efficiency of C, along with its modularity and rich library. The document includes examples of C syntax and programs to illustrate the concepts discussed.

Uploaded by

xosad89037
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Chapter 1: Introduction to C Programming

1.1 C Language ka Overview


C programming language ek bahut hi powerful aur versatile language hai, jo Dennis Ritchie ne
1972 mein develop kari thi. Yeh language low-level memory access, simple keywords, aur clean
style ke liye famous hai. Aaj bhi, operating systems, embedded systems, aur high-performance
applications likhne ke liye C language ka use hota hai.

1.2 Features of C Language


C language ke kuch khas features hain jo isko unique banate hain:

1. Simple and Efficient: C language ko samajhna aur use karna aasan hai, aur yeh high-
level aur low-level dono tarah ki functionalities ko support karti hai.
2. Portable: C programs ko kisi bhi system pe run kiya ja sakta hai jahan C compiler
available ho.
3. Rich Library: C ke paas ek acchi khaasi standard library hai jisme commonly used
functions included hain.
4. Modularity: C programs ko modules mein divide kiya ja sakta hai jisse reusability badhti
hai aur maintenance easy ho jata hai.
5. Middle-Level Language: C ko ek middle-level language bola jata hai kyunki yeh low-level
memory access ko allow karti hai jaise pointers ke through, aur saath hi high-level
constructs bhi provide karti hai.

1.3 Basic Structure of a C Program


Ek simple C program kuch is tarah se dikhta hai:

#include <stdio.h> // Standard Input Output header file

int main() { // Main function


printf("Hello, World!"); // Output function
return 0; // Return statement
}

Hello, World!
Explanation:

#include <stdio.h>: Yeh line ek preprocessor directive hai jo standard input-output


functions ke liye header file include karti hai.
int main(): Yeh function program execution ka starting point hai. Har C program mein ek
main function hona zaroori hai.
printf("Hello, World!");: Yeh ek output function hai jo text screen pe print karta hai.
return 0;: Yeh line indicate karti hai ki program successfully execute ho gaya. 0 return
karna ek standard practice hai.

Great! Let’s continue with the next chapter.

Chapter 2: Variables, Data Types, and Operators


2.1 Variables kya hoti hain?
Variables programming mein ek jagah hoti hai jahan hum data ko store karte hain. Yeh ek
container ki tarah hoti hai jo kisi bhi value ko temporarily hold karti hai. Har variable ka ek naam
hota hai aur ek data type jo batata hai ki yeh kis type ki value store karega.

Syntax for Declaring Variables:

data_type variable_name;

Example:

int age;
float salary;
char grade;

int: Yeh integer type variable hai jo whole numbers ko store karta hai.
float: Yeh floating-point numbers ko store karta hai, yaani decimal values.
char: Yeh single character ko store karta hai.

2.2 Data Types in C


C language mein alag-alag types ke data ko store karne ke liye alag-alag data types hote hain.
Inhe broadly do categories mein divide kiya ja sakta hai:

1. Primitive Data Types:

int: Integer type, jo whole numbers ko store karta hai. Example: 5, -10.
float: Floating-point type, jo decimal numbers ko store karta hai. Example: 3.14, -0.001.
char: Character type, jo ek single character store karta hai. Example: 'A', 'b'.
double: Double-precision floating-point type, jo zyada accurate decimal numbers store
karta hai. Example: 3.14159265359.

2. Derived Data Types:

Arrays: Same type ke multiple values ko store karne ke liye.


Pointers: Memory addresses ko store karne ke liye.
Structures: Different types ke values ko ek group mein store karne ke liye.
Unions: Multiple members ko store kar sakte hain par ek time pe sirf ek hi.

2.3 Constants kya hoti hain?


Constants woh values hoti hain jo program execution ke dauran change nahi hoti. Jaise, agar
aapko kisi value ko program ke har part mein use karna hai bina usko change kiye, to aap
constants ka use kar sakte hain.

Example:

#define PI 3.14

Yahaan PI ek constant hai jo 3.14 value ko represent karta hai.

2.4 Operators in C
Operators woh symbols hote hain jo operations perform karte hain. C mein kuch common
operators hain:
1. Arithmetic Operators:

+ : Addition (jodna)
- : Subtraction (ghatana)
* : Multiplication (guna)
/ : Division (bhag)
% : Modulus (remainder nikalna)

Example:

int a = 10, b = 5;
int sum = a + b; // sum will be 15

2. Relational Operators:

== : Equal to
!= : Not equal to
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to

Example:

int x = 5, y = 10;
if (x < y) {
// This condition is true
}

3. Logical Operators:

&& : Logical AND


|| : Logical OR
! : Logical NOT

Example:

int a = 5, b = 10;
if (a > 0 && b > 0) {
// This condition is true
}

4. Assignment Operators:

= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
%= : Modulus and assign

Example:

int x = 10;
x += 5; // x will be 15

5. Increment and Decrement Operators:

++ : Increment (increase value by 1)


-- : Decrement (decrease value by 1)

Example:

int i = 1;
i++; // i will be 2

2.5 Example Program: Using Variables and Operators

#include <stdio.h>

int main() {
int num1 = 10, num2 = 20;
int sum = num1 + num2; // Addition
int diff = num2 - num1; // Subtraction
int prod = num1 * num2; // Multiplication
int quot = num2 / num1; // Division
printf("Sum = %d\n", sum);
printf("Difference = %d\n", diff);
printf("Product = %d\n", prod);
printf("Quotient = %d\n", quot);

return 0;
}

Sum = 30
Difference = 10
Product = 200
Quotient = 2

Is program mein humne variables declare kiye hain, aur un par arithmetic operations perform
karke results ko output kiya hai.

Let's move on to the next chapter.

Chapter 3: Control Structures


3.1 Introduction to Control Structures
Control structures C programming mein aapko allow karte hain ki aap apne program ke flow ko
control kar sakein. Inka use karke aap decision-making, looping, aur branching ko implement
kar sakte hain. Control structures ko teen categories mein divide kiya ja sakta hai:

1. Sequential Control Structures


2. Decision-Making Control Structures
3. Loop Control Structures

3.2 Sequential Control Structures


Sequential control structure mein statements ek ke baad ek execute hote hain, jaisa ki aapne
pehle ke chapters mein dekha hai. Yeh simplest form hai control ka, aur har statement apne
previous statement ke baad execute hota hai.
Example:

#include <stdio.h>

int main() {
int a = 5;
int b = 10;
int sum = a + b; // Sequential execution
printf("Sum = %d\n", sum);
return 0;
}

Sum = 15

3.3 Decision-Making Control Structures


Decision-making control structures aapko allow karte hain ki aap apne program mein conditions
ke base pe decisions le sakein. C mein commonly used decision-making control structures
hain:

1. if Statement
if statement ko use karke aap kisi condition ko check kar sakte hain. Agar condition true hoti
hai, to uske andar ka code execute hota hai.

Syntax:

if (condition) {
// Code to be executed if condition is true
}

Example:

int num = 10;


if (num > 0) {
printf("Number is positive\n");
}

Number is positive
2. if-else Statement
if-else statement mein agar condition true hoti hai to if block execute hota hai, aur agar
false hoti hai to else block execute hota hai.

Syntax:

if (condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}

Example:

int num = -5;


if (num > 0) {
printf("Number is positive\n");
} else {
printf("Number is negative or zero\n");
}

Number is negative or zero

3. else-if Ladder
else-if ladder tab use hoti hai jab aapko multiple conditions check karni ho. Har if ke baad
ek else-if statement ho sakti hai, aur aakhir mein ek else block ho sakta hai.

Syntax:

if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else if (condition3) {
// Code for condition3
} else {
// Code if all conditions are false
}
Example:

int num = 0;
if (num > 0) {
printf("Number is positive\n");
} else if (num < 0) {
printf("Number is negative\n");
} else {
printf("Number is zero\n");
}

Number is zero

4. switch Statement
switch statement multiple conditions ko check karne ke liye use hoti hai, par yeh if-else se
thoda different hota hai. Yeh ek variable ki value ko check karta hai aur uske hisaab se code
execute karta hai.

Syntax:

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

Example:

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

Wednesday

3.4 Loop Control Structures


Loop control structures se aapko allow hota hai ki aap code ko repeatedly execute kar sakein
jab tak koi condition true hai. C mein commonly used loops hain:

1. for Loop
for loop use hota hai jab aapko kisi block of code ko fixed number of times execute karna ho.

Syntax:

for (initialization; condition; increment/decrement) {


// Code to be executed
}

Example:

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

1
2
3
4
5
2. while Loop
while loop tab use hota hai jab aapko pata ho ki koi condition true hai par aapko number of
iterations nahi pata. Yeh loop tab tak execute hota hai jab tak condition true rahe.

Syntax:

while (condition) {
// Code to be executed
}

Example:

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

1
2
3
4
5

3. do-while Loop
do-while loop while loop se different hota hai kyunki yeh pehle ek baar code ko execute
karta hai phir condition check karta hai. Isliye yeh loop at least ek baar toh zaroor execute hota
hai.

Syntax:

do {
// Code to be executed
} while (condition);

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

1
2
3
4
5

3.5 Example Program: Using Control Structures

#include <stdio.h>

int main() {
int number = 2;

// Using if-else statement


if (number == 1) {
printf("Number is one\n");
} else if (number == 2) {
printf("Number is two\n");
} else {
printf("Number is neither one nor two\n");
}

// Using switch statement


switch (number) {
case 1:
printf("Number is one\n");
break;
case 2:
printf("Number is two\n");
break;
default:
printf("Number is something else\n");
}

// Using for loop


for (int i = 1; i <= 3; i++) {
printf("Iteration %d\n", i);
}

return 0;
}

Number is two
Number is two
Iteration 1
Iteration 2
Iteration 3

Is program mein humne decision-making aur looping control structures ko use karke output
generate kiya hai.

Great! Let’s proceed to the next chapter.

Chapter 4: Functions
4.1 Introduction to Functions
Functions C programming mein ek reusable block of code hote hain jo specific task perform
karte hain. Functions ka use karke aap apne code ko modular aur manageable bana sakte
hain. Aap ek function ko ek bar define karke, usko program ke multiple jagah use kar sakte
hain.

4.2 Defining a Function


Function ko define karne ke liye aapko function ka naam, return type, aur parameters specify
karne hote hain. Function ka syntax kuch is tarah hota hai:

Syntax:

return_type function_name(parameters) {
// Code to be executed
}
Example:

#include <stdio.h>

// Function definition
void greet() {
printf("Hello, World!\n");
}

int main() {
greet(); // Function call
return 0;
}

Hello, World!

Explanation:

void greet(): Yeh function definition hai. void return type ko indicate karta hai ki function
kuch bhi return nahi karega.
greet();: Yeh function call hai jo main function se greet function ko execute karta hai.

4.3 Function with Parameters


Function parameters wo values hote hain jo function ko input ke roop mein diye jate hain. Aap
function ko parameters ke sath define aur call kar sakte hain.

Syntax:

return_type function_name(parameter1, parameter2, ...) {


// Code to be executed
}

Example:

#include <stdio.h>

// Function definition with parameters


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

Sum = 15

Explanation:

int add(int a, int b): Yeh function do integer parameters ko accept karta hai aur unka sum
return karta hai.
add(5, 10): Yeh function call hai jo 5 aur 10 ko parameters ke roop mein pass karta hai.

4.4 Return Values


Functions se values return ki ja sakti hain jo calling function ke dwara use ki jati hain. Return
type function definition mein specify kiya jata hai aur return statement se value return ki jati
hai.

Example:

#include <stdio.h>

int multiply(int x, int y) {


return x * y;
}

int main() {
int result = multiply(4, 5); // Function call
printf("Product = %d\n", result);
return 0;
}

Product = 20

Explanation:

int multiply(int x, int y): Yeh function do integer values ko multiply karta hai aur result
return karta hai.
return x * y;: Yeh statement function se result return karta hai.

4.5 Function Overloading (Not Supported in C)


C language function overloading ko support nahi karti. Function overloading mein ek hi naam
ke multiple functions hote hain jo different parameters ke sath define kiye jate hain. Lekin, C++
mein yeh feature available hai.

4.6 Recursive Functions


Recursive functions wo functions hote hain jo apne aap ko call karte hain. Yeh approach
complex problems ko solve karne ke liye use hoti hai.

Syntax:

return_type function_name(parameters) {
if (condition) {
// Recursive call
function_name(parameters);
}
// Base case
}

Example:

#include <stdio.h>

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

int main() {
int result = factorial(5); // Function call
printf("Factorial = %d\n", result);
return 0;
}
Factorial = 120

Explanation:

int factorial(int n): Yeh function factorial calculate karta hai using recursion.
factorial(n - 1): Yeh recursive call hai jo function ko apne aap ko call karta hai.

4.7 Example Program: Using Functions

#include <stdio.h>

// Function to calculate area of a rectangle


int area(int length, int width) {
return length * width;
}

int main() {
int length = 10;
int width = 5;
int rect_area = area(length, width); // Function call
printf("Area of rectangle = %d\n", rect_area);
return 0;
}

Area of rectangle = 50

Is program mein humne area function ko define kiya hai jo rectangle ka area calculate karta
hai aur main function se call kiya hai.

Great! Let’s move on to the next chapter.

Chapter 5: Arrays and Strings


5.1 Introduction to Arrays
Arrays C programming mein ek data structure hain jo same type ki multiple values ko store
karne ke liye use hote hain. Arrays ka size fixed hota hai aur yeh contiguous memory locations
mein store hote hain.

1. Declaring and Initializing Arrays


Syntax for Declaration:

data_type array_name[array_size];

Syntax for Initialization:

data_type array_name[array_size] = {value1, value2, ...};

Example:

int numbers[5]; // Declaring an array of integers


numbers[0] = 1; // Initializing the first element
numbers[1] = 2; // Initializing the second element

int scores[3] = {90, 85, 88}; // Declaring and initializing an array

2. Accessing Array Elements

Array elements ko index ke through access kiya jata hai. Array indexing 0 se start hoti hai.

Example:

#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
printf("First element: %d\n", arr[0]); // Accessing first element
printf("Second element: %d\n", arr[1]); // Accessing second element
return 0;
}

First element: 10
Second element: 20
5.2 Multidimensional Arrays
Multidimensional arrays ko 2D (two-dimensional) aur 3D (three-dimensional) arrays ke roop
mein declare kiya ja sakta hai. Yeh arrays tab use hote hain jab aapko grid-like structure ko
represent karna ho.

Syntax for 2D Array:

data_type array_name[rows][columns];

Example:

#include <stdio.h>

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

printf("Element at (0, 1): %d\n", matrix[0][1]); // Accessing element at


row 0, column 1
printf("Element at (1, 2): %d\n", matrix[1][2]); // Accessing element at
row 1, column 2

return 0;
}

Element at (0, 1): 2


Element at (1, 2): 6

5.3 Strings in C
Strings C mein character arrays ke roop mein store kiye jate hain. String ko '\0' (null
character) se terminate kiya jata hai jo string ki end ko indicate karta hai.

1. Declaring and Initializing Strings

Syntax:

char string_name[size];
Initialization:

char str1[] = "Hello";


char str2[6] = "World"; // Explicitly specifying size

2. Accessing String Characters


String ke characters ko index ke through access kiya jata hai.

Example:

#include <stdio.h>

int main() {
char str[] = "Hello";
printf("First character: %c\n", str[0]); // Accessing first character
printf("Second character: %c\n", str[1]); // Accessing second character
return 0;
}

First character: H
Second character: e

3. Common String Functions

C library mein string functions ka ek set hota hai jo strings ko manipulate karne mein help karte
hain. Yeh functions <string.h> header file mein define hote hain.

Examples:

strlen(): String ki length return karta hai.

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

int main() {
char str[] = "Hello";
printf("Length of string: %lu\n", strlen(str));
return 0;
}

Length of string: 5

strcpy(): Ek string ko dusri string mein copy karta hai.

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

int main() {
char source[] = "Hello";
char destination[10];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}

Copied string: Hello

strcmp(): Do strings ko compare karta hai.

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

int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
Copied string: Hello

str1 is less than str2

5.4 Example Program: Arrays and Strings

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

int main() {
// Array example
int arr[4] = {10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
printf("Array element at index %d: %d\n", i, arr[i]);
}

// String example
char name[20] = "Programming";
printf("String: %s\n", name);
printf("Length of string: %lu\n", strlen(name));

char copy[20];
strcpy(copy, name);
printf("Copied string: %s\n", copy);

return 0;
}

Array element at index 0: 10


Array element at index 1: 20
Array element at index 2: 30
Array element at index 3: 40
String: Programming
Length of string: 11
Copied string: Programming

Is program mein humne arrays aur strings ko declare kiya, initialize kiya, aur unhe manipulate
kiya.
Great! Let’s move on to the next chapter.

Chapter 6: Pointers and Memory Management


6.1 Introduction to Pointers
Pointers C programming mein ek special type ke variables hote hain jo memory addresses ko
store karte hain. Pointers ka use karke aap directly memory locations ko access aur manipulate
kar sakte hain.

1. Declaring and Initializing Pointers

Syntax for Declaring Pointers:

data_type *pointer_name;

Syntax for Initializing Pointers:

pointer_name = &variable_name;

Example:

#include <stdio.h>

int main() {
int num = 10;
int *ptr; // Pointer declaration
ptr = &num; // Pointer initialization

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


printf("Address of num: %p\n", (void*)ptr); // Printing address
printf("Value at address ptr: %d\n", *ptr); // Dereferencing pointer

return 0;
}

Value of num: 10
Address of num: [memory address]
Value at address ptr: 10

Explanation:

int *ptr: Yeh pointer declaration hai jo integer type ke memory address ko store kar sakta
hai.
ptr = &num: Yeh num variable ke address ko ptr pointer mein store karta hai.
printf("Address of num: %p\n", (void*)ptr): Yeh ptr ke address ko print karta hai.
printf("Value at address ptr: %d\n", *ptr): Yeh ptr ke address pe stored value ko print
karta hai.

6.2 Pointer Arithmetic


Pointer arithmetic se aap pointers ke address ko manipulate kar sakte hain. Basic pointer
arithmetic operations include increment, decrement, addition, and subtraction.

Example:

#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr;

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


printf("Value at index %d: %d\n", i, *(ptr + i));
}

return 0;
}

Value at index 0: 10
Value at index 1: 20
Value at index 2: 30

Explanation:

int *ptr = arr: Yeh arr array ke starting address ko ptr pointer mein store karta hai.
*(ptr + i): Yeh pointer arithmetic se ptr ko i position pe shift karta hai aur value access
karta hai.
6.3 Pointers and Arrays
Arrays aur pointers closely related hote hain. Array ke naam ko pointer ke roop mein treat kiya
jata hai jo array ke starting address ko represent karta hai.

Example:

#include <stdio.h>

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

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


printf("Array element %d: %d\n", i, *(ptr + i));
}

return 0;
}

Array element 0: 1
Array element 1: 2
Array element 2: 3
Array element 3: 4

Explanation:

int *ptr = arr: Yeh arr array ke starting address ko ptr pointer mein store karta hai.
*(ptr + i): Yeh pointer arithmetic se arr ke elements ko access karta hai.

6.4 Dynamic Memory Allocation


Dynamic memory allocation se aap run-time pe memory allocate kar sakte hain. C mein yeh
functions ka use karke kiya jata hai:

malloc(): Memory allocate karta hai.


calloc(): Memory allocate karta hai aur initialize karta hai.
realloc(): Existing memory block ko resize karta hai.
free(): Allocated memory ko free karta hai.

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

int main() {
int *arr;
int n = 5;

arr = (int *)malloc(n * sizeof(int)); // Allocating memory

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

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


arr[i] = i + 1;
}

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


printf("Array element %d: %d\n", i, arr[i]);
}

free(arr); // Freeing allocated memory

return 0;
}

Array element 0: 1
Array element 1: 2
Array element 2: 3
Array element 3: 4
Array element 4: 5

Explanation:

malloc(n * sizeof(int)): Yeh n integers ke liye memory allocate karta hai.


free(arr): Yeh allocated memory ko free karta hai.

6.5 Pointers to Functions


Pointers ko functions ke addresses ko store karne ke liye bhi use kiya ja sakta hai. Yeh
technique function callbacks aur dynamic function calling mein use hoti hai.
Example:

#include <stdio.h>

void display() {
printf("Function called through pointer\n");
}

int main() {
void (*func_ptr)(); // Function pointer declaration
func_ptr = display; // Function pointer initialization
func_ptr(); // Function call using pointer

return 0;
}

Function called through pointer

Explanation:

void (*func_ptr)(): Yeh function pointer declaration hai jo display function ke address ko
store kar sakta hai.
func_ptr = display: Yeh function pointer ko display function ke address se initialize
karta hai.
func_ptr(): Yeh function pointer se function ko call karta hai.

6.6 Example Program: Using Pointers and Dynamic


Memory Allocation

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

int main() {
int *arr;
int size;

printf("Enter the number of elements: ");


scanf("%d", &size);

arr = (int *)malloc(size * sizeof(int)); // Allocate memory


if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

printf("Enter %d elements:\n", size);


for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("You entered:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

free(arr); // Free allocated memory

return 0;
}

Enter the number of elements: 3


Enter 3 elements:
10
20
30
You entered:
10 20 30

Is program mein user se array size aur elements input karte hain, dynamically memory allocate
karte hain, aur un elements ko print karte hain.

Great! Let’s move on to the next chapter.

Chapter 7: File Handling and Input/Output


Operations
7.1 Introduction to File Handling
File handling se aap data ko files mein store aur read kar sakte hain. C programming mein file
handling ke liye stdio.h library functions ka use hota hai. Files ko handle karne ke liye aapko
file pointers ka use karna hota hai.

1. Opening and Closing Files


Syntax for Opening a File:

FILE *fopen(const char *filename, const char *mode);

Syntax for Closing a File:

int fclose(FILE *stream);

File Modes:

"r": Read mode (file must exist)


"w": Write mode (creates file if it doesn’t exist, overwrites if it exists)
"a": Append mode (creates file if it doesn’t exist, appends data if it exists)
"r+": Read and write mode
"w+": Read and write mode (overwrites existing file)
"a+": Read and append mode

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "w"); // Open file in write mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

fprintf(file, "Hello, File Handling!\n"); // Writing to file

fclose(file); // Closing file

return 0;
}
Hello, File Handling!

Explanation:

fopen("example.txt", "w"): example.txt file ko write mode mein open karta hai.
fprintf(file, "Hello, File Handling!\n"): File mein data write karta hai.
fclose(file): File ko close karta hai.

7.2 Reading from Files


File se data read karne ke liye fscanf() , fgets() , aur fread() functions ka use kiya jata
hai.

1. Using fscanf()
Syntax:

int fscanf(FILE *stream, const char *format, ...);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "r"); // Open file in read mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

char buffer[100];
fscanf(file, "%s", buffer); // Reading from file
printf("Read from file: %s\n", buffer);

fclose(file); // Closing file

return 0;
}
Read from file: Hello,

Explanation:

fscanf(file, "%s", buffer): File se string read karta hai aur buffer mein store karta hai.

2. Using fgets()

Syntax:

char *fgets(char *str, int n, FILE *stream);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "r"); // Open file in read mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

char buffer[100];
fgets(buffer, sizeof(buffer), file); // Reading line from file
printf("Read from file: %s", buffer);

fclose(file); // Closing file

return 0;
}

Read from file: Hello, File Handling!

Explanation:

fgets(buffer, sizeof(buffer), file): File se ek line read karta hai aur buffer mein store
karta hai.

7.3 Writing to Files


Files mein data write karne ke liye fprintf() , fputs() , aur fwrite() functions ka use hota
hai.

1. Using fprintf()
Syntax:

int fprintf(FILE *stream, const char *format, ...);

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "w"); // Open file in write mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

fprintf(file, "Hello, File Handling!\n"); // Writing to file

fclose(file); // Closing file

return 0;
}

Hello, File Handling!

Explanation:

fprintf(file, "Hello, File Handling!\n"): File mein formatted data write karta hai.

2. Using fputs()
Syntax:

int fputs(const char *str, FILE *stream);

Example:
#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "w"); // Open file in write mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

fputs("Hello, File Handling!\n", file); // Writing to file

fclose(file); // Closing file

return 0;
}

Hello, File Handling!

Explanation:

fputs("Hello, File Handling!\n", file): File mein string write karta hai.

7.4 File Pointers and File Positioning


File pointers aur file positioning ke functions se aap file ke current position ko track aur
manipulate kar sakte hain.

1. Using ftell() and fseek()

ftell(FILE *stream) : Current file position ko return karta hai.


fseek(FILE *stream, long int offset, int whence) : File position ko set karta hai.

Example:

#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "r"); // Open file in read mode
if (file == NULL) {
printf("Error opening file\n");
return 1;
}

fseek(file, 0, SEEK_END); // Move to end of file


long size = ftell(file); // Get file size
printf("File size: %ld bytes\n", size);

fclose(file); // Closing file

return 0;
}

File size: [size] bytes

Explanation:

fseek(file, 0, SEEK_END): File pointer ko end of file pe set karta hai.


ftell(file): Current file position (i.e., file size) ko return karta hai.

7.5 Example Program: File Handling

#include <stdio.h>

int main() {
// Writing to a file
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("Error opening file for writing\n");
return 1;
}

fprintf(file, "File Handling in C\n");


fclose(file);

// Reading from a file


file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file for reading\n");
return 1;
}

char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);

return 0;
}

File Handling in C

Is program mein pehle file mein data write karte hain aur phir usi file se data read karte hain.

Great! Let’s proceed to the next chapter.

Chapter 8: Structures and Unions


8.1 Introduction to Structures
Structures C programming mein ek custom data type define karne ke liye use hote hain jo
multiple different data types ko ek single unit mein group karte hain. Structures ko use karke
aap complex data models create kar sakte hain.

1. Defining a Structure

Syntax:

struct structure_name {
data_type member1;
data_type member2;
// Other members
};

Example:

#include <stdio.h>

// Defining a structure
struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1; // Creating a structure variable

// Assigning values
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 5.9;

// Accessing values
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n", person1.height);

return 0;
}

Name: John Doe


Age: 30
Height: 5.90

Explanation:

struct Person: Yeh structure ko define karta hai jo name , age , aur height members ko
include karta hai.
person1: Yeh Person type ka structure variable hai.
person1.name: Structure member ko access karta hai aur value assign karta hai.

8.2 Nested Structures


Structures ko dusre structures ke andar bhi use kiya ja sakta hai. Yeh technique complex data
models ko represent karne ke liye useful hoti hai.

Example:

#include <stdio.h>

// Defining nested structure


struct Address {
char street[100];
char city[50];
};

struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};

int main() {
struct Person person1;

// Assigning values
strcpy(person1.name, "Jane Doe");
person1.age = 28;
strcpy(person1.address.street, "123 Main St");
strcpy(person1.address.city, "New York");

// Accessing values
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Address: %s, %s\n", person1.address.street, person1.address.city);

return 0;
}

Name: Jane Doe


Age: 28
Address: 123 Main St, New York

Explanation:

struct Address: Yeh ek nested structure define karta hai jo address ke details ko store
karta hai.
struct Person: Yeh Address structure ko include karta hai.

8.3 Unions
Unions C programming mein ek special data type hote hain jo multiple data types ko ek single
memory location mein store karte hain. Union ke through aap ek hi time pe sirf ek member ko
store kar sakte hain, lekin memory space save hoti hai.
1. Defining a Union
Syntax:

union union_name {
data_type member1;
data_type member2;
// Other members
};

Example:

#include <stdio.h>

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

int main() {
union Data data;

// Assigning values
data.i = 10;
printf("Integer: %d\n", data.i);

data.f = 220.5; // Overwrites previous value


printf("Float: %.2f\n", data.f);

strcpy(data.str, "Hello, World!"); // Overwrites previous value


printf("String: %s\n", data.str);

return 0;
}

Integer: 10
Float: 220.50
String: Hello, World!

Explanation:
union Data: Yeh union ko define karta hai jo i , f , aur str members ko include karta
hai.
data: Yeh Data type ka union variable hai.
data.i, data.f, data.str: Union ke members ko access karte hain. Notice how assigning a
value to one member overwrites the value of previous members.

8.4 Using Structures and Unions with Functions


Structures aur unions ko functions ke parameters aur return types ke roop mein use kiya ja
sakta hai.

1. Passing Structures to Functions


Example:

#include <stdio.h>

// Defining a structure
struct Person {
char name[50];
int age;
};

// Function to print structure details


void printPerson(struct Person p) {
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
}

int main() {
struct Person person1 = {"Alice", 25};
printPerson(person1); // Passing structure to function

return 0;
}

Name: Alice
Age: 25

Explanation:
void printPerson(struct Person p): Yeh function ek structure ko parameter ke roop mein
accept karta hai.

2. Returning Structures from Functions

Example:

#include <stdio.h>

// Defining a structure
struct Person {
char name[50];
int age;
};

// Function to return a structure


struct Person createPerson(char name[], int age) {
struct Person p;
strcpy(p.name, name);
p.age = age;
return p;
}

int main() {
struct Person person1 = createPerson("Bob", 30); // Returning structure
from function
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);

return 0;
}

Name: Bob
Age: 30

Explanation:

struct Person createPerson(char name[], int age): Yeh function ek structure ko return
karta hai.

8.5 Example Program: Structures and Unions


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

// Defining a structure
struct Book {
char title[50];
char author[50];
int year;
};

// Defining a union
union Value {
int i;
float f;
char str[20];
};

int main() {
// Using structure
struct Book book1;
strcpy(book1.title, "The Great Gatsby");
strcpy(book1.author, "F. Scott Fitzgerald");
book1.year = 1925;

printf("Book Title: %s\n", book1.title);


printf("Book Author: %s\n", book1.author);
printf("Publication Year: %d\n", book1.year);

// Using union
union Value val;
val.i = 100;
printf("Integer value: %d\n", val.i);
val.f = 98.6;
printf("Float value: %.2f\n", val.f);
strcpy(val.str, "Union Example");
printf("String value: %s\n", val.str);

return 0;
}

Book Title: The Great Gatsby


Book Author: F. Scott Fitzgerald
Publication Year: 1925
Integer value: 100
Float value: 98.60
String value: Union Example

Is program mein humne ek structure aur ek union ko define kiya, unka use kiya aur unke
members ko print kiya.

Great! Let’s move on to the next chapter.

Chapter 9: Advanced Topics


9.1 Error Handling
C programming mein error handling directly language ka part nahi hota, lekin errno aur error
codes ka use karke errors ko handle kiya ja sakta hai. Errors ko handle karne ke liye, errno.h
header file aur perror() function ka use kiya jata hai.

1. Using errno and perror()

Example:

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

int main() {
FILE *file = fopen("nonexistentfile.txt", "r");

if (file == NULL) {
// Print the error message
perror("Error opening file");
printf("Error code: %d\n", errno);
} else {
// File operations
fclose(file);
}

return 0;
}
Error opening file: No such file or directory
Error code: 2

Explanation:

fopen("nonexistentfile.txt", "r"): Agar file nahi milti hai, to NULL return hota hai aur
errno set hota hai.
perror("Error opening file"): Error message ko print karta hai jo errno ke value se
associated hota hai.
printf("Error code: %d\n", errno): Error code ko print karta hai.

9.2 Preprocessor Directives


Preprocessor directives C compiler ke compilation process se pehle source code ko modify
karte hain. Yeh directives #include , #define , aur #ifdef etc. hote hain.

1. #include Directive
Syntax:

#include <header_file>
#include "user_defined_file"

Example:

#include <stdio.h> // Standard library header file


#include "myheader.h" // User-defined header file

Explanation:

#include <stdio.h>: Standard I/O functions ko include karta hai.


#include "myheader.h": User-defined header file ko include karta hai, jo same directory
mein hona chahiye.

2. #define Directive
Syntax:
#define MACRO_NAME value

Example:

#include <stdio.h>

#define PI 3.14

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

Value of PI: 3.14

Explanation:

#define PI 3.14: PI macro ko 3.14 value assign karta hai. Compiler isko replace kar
deta hai.

3. Conditional Compilation

Syntax:

#ifdef MACRO_NAME
// Code to compile if MACRO_NAME is defined
#else
// Code to compile if MACRO_NAME is not defined
#endif

Example:

#include <stdio.h>

#define DEBUG

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

Debug mode is enabled.


Program execution.

Explanation:

#ifdef DEBUG: Yeh check karta hai ki DEBUG macro define hai ya nahi. Agar hai, to
debug related code execute hoga.

9.3 Macro Functions


Macro functions ko #define directive ke through define kiya jata hai aur function-like syntax
hota hai. Yeh code reusability aur readability improve karte hain.

Syntax:

#define MACRO_NAME(parameters) (expression)

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;
}

Square of 5 is 25

Explanation:

#define SQUARE(x) ((x) * (x)): Yeh macro function x ka square calculate karta hai.
9.4 Example Program: Error Handling and Preprocessor
Directives

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

#define FILE_NAME "testfile.txt"

int main() {
FILE *file = fopen(FILE_NAME, "r");

if (file == NULL) {
perror("Error opening file");
printf("Error code: %d\n", errno);
return 1;
}

#ifdef DEBUG
printf("File opened successfully.\n");
#endif

fclose(file);

return 0;
}

Error opening file: No such file or directory


Error code: 2

Is program mein, file handling aur error handling ke saath preprocessor directives aur macro
function ka use kiya gaya hai.

Great! Let’s move on to the next chapter.

Chapter 10: Advanced Topics in C


10.1 Memory Management
C programming mein memory management manual hota hai, aur malloc() , calloc() ,
realloc() , aur free() functions ka use karke dynamic memory allocation aur deallocation
kiya jata hai.

1. Dynamic Memory Allocation


1.1 `malloc() Function

Syntax:

void *malloc(size_t size);

Example:

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

int main() {
int *arr;
int n = 5;

arr = (int *)malloc(n * sizeof(int)); // Allocating memory for 5 integers

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Assigning values
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}

// Printing values
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

free(arr); // Freeing allocated memory

return 0;
}
1 2 3 4 5

Explanation:

malloc(n * sizeof(int)): n integers ke liye memory allocate karta hai.


free(arr): Allocated memory ko deallocate karta hai.

1.2 `calloc() Function

Syntax:

void *calloc(size_t num, size_t size);

Example:

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

int main() {
int *arr;
int n = 5;

arr = (int *)calloc(n, sizeof(int)); // Allocating memory and initializing


to 0

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Printing values
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

free(arr); // Freeing allocated memory

return 0;
}

0 0 0 0 0
Explanation:

calloc(n, sizeof(int)): n integers ke liye memory allocate karta hai aur initialize karta hai.

1.3 `realloc() Function

Syntax:

void *realloc(void *ptr, size_t size);

Example:

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

int main() {
int *arr;
int n = 5;

arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Reallocating memory
n = 10;
arr = (int *)realloc(arr, n * sizeof(int));

if (arr == NULL) {
printf("Memory reallocation failed\n");
return 1;
}

// Assigning new values


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

// Printing values
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr); // Freeing allocated memory

return 0;
}

1 2 3 4 5 6 7 8 9 10

Explanation:

realloc(arr, n * sizeof(int)): Pehle allocated memory ko resize karta hai.

10.2 Multi-threading
C mein multi-threading ko implement karne ke liye pthread library ka use kiya jata hai.
Threads ek program ke andar parallel tasks ko execute karte hain.

1. Creating and Managing Threads


1.1 Basic Thread Creation

Example:

#include <stdio.h>
#include <pthread.h>

void *printMessage(void *msg) {


printf("%s\n", (char *)msg);
return NULL;
}

int main() {
pthread_t thread1;
const char *message = "Hello from the thread!";

pthread_create(&thread1, NULL, printMessage, (void *)message);


pthread_join(thread1, NULL); // Wait for thread to finish

return 0;
}
Hello from the thread!

Explanation:

pthread_create(&thread1, NULL, printMessage, (void *)message): Ek new thread


create karta hai jo printMessage function ko execute karega.
pthread_join(thread1, NULL): Main thread ko wait karata hai jab tak thread1 finish nahi
hota.

2. Thread Synchronization
Multi-threading mein data consistency aur race conditions ko handle karne ke liye
synchronization techniques ka use kiya jata hai.

2.1 Using Mutexes

Example:

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
int counter = 0;

void *incrementCounter(void *arg) {


pthread_mutex_lock(&mutex); // Lock the mutex
counter++;
printf("Counter: %d\n", counter);
pthread_mutex_unlock(&mutex); // Unlock the mutex
return NULL;
}

int main() {
pthread_t thread1, thread2;

pthread_mutex_init(&mutex, NULL);

pthread_create(&thread1, NULL, incrementCounter, NULL);


pthread_create(&thread2, NULL, incrementCounter, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&mutex);

return 0;
}

Counter: 1
Counter: 2

Explanation:

pthread_mutex_lock(&mutex): Mutex ko lock karta hai.


pthread_mutex_unlock(&mutex): Mutex ko unlock karta hai.
pthread_mutex_init(&mutex, NULL): Mutex ko initialize karta hai.
pthread_mutex_destroy(&mutex): Mutex ko destroy karta hai.

10.3 Example Program: Memory Management and


Threads

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

void *printArray(void *arr) {


int *array = (int *)arr;
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("\n");
return NULL;
}

int main() {
pthread_t thread1;
int *arr = (int *)malloc(5 * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Initializing array
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}

pthread_create(&thread1, NULL, printArray, (void *)arr);


pthread_join(thread1, NULL);

free(arr); // Freeing allocated memory

return 0;
}

1 2 3 4 5

Is program mein, memory allocation aur threading ke concepts ka use kiya gaya hai.

THE END

You might also like