Master C Langauge Ebook PDF
Master C Langauge Ebook PDF
C Basics
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
data_type variable_name;
int age;
float temperature;
char firstInitial;
float pi = 3.14159;
In this example, the variables score, pi, and grade are declared and
immediately assigned initial values.
You can change the value of a variable after its initialization using the
assignment operator (=). For example:
score = 95;
pi = 3.14;
grade = 'B';
Example of Variables: -
#include <stdio.h>
int main() {
int age;
// Assign a value to the 'age' variable
age = 25;
return 0;
C supports several basic data types, which are classified into three
categories: integer, floating-point, and character.
#include <stdio.h>
int main() {
return 0;
#include <stdio.h>
int main() {
float pi = 3.14159;
return 0;
#include <stdio.h>
int main() {
return 0;
'\n': Newline
'\t': Tab
'\r': Carriage return
'\\': Backslash
'\'': Single quote
Printing Character: - You can use the “%c” format specifier in the
“printf” function to print characters:
Reading Characters: - You can use the “%c” format specifier with the
“scanf” function to read characters from input:
char userInput;
scanf("%c", &userInput);
1.5 Constants
Constants are fixed values that remain the same while a program is
being run. They are used to represent things like mathematical
constants, configuration parameters, and more that remain constant
during the course of the program. By giving meaningful names to
quantities that may otherwise appear in your code as "magic
numbers," constants make your code easier to understand,
and maintain, and make fewer mistakes. Here is how C defines and
employs constants:
1.5.1 Defining Constants
Using #define
Syntax:
Example:
#define PI 3.14159
Syntax:
Example:
const int MAX_ATTEMPTS = 3;
Once constants are defined, they can be used in your code wherever
you would use the corresponding literal values.
Example:
#include <stdio.h>
#define PI 3.14159
int main() {
printf("Invalid score\n");
}
return 0;
Syntax:
printf("format_string", argument_list);
Example:
#include <stdio.h>
int main() {
return 0;
The “scanf()” function is used to read input from the user. It allows
you to receive data and store it in variables.
Syntax:
Example:
#include <stdio.h>
int main() {
int age;
scanf("%d", &age);
return 0;
1.7.1 Operators
Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
ii. Relational Operator: These operators compare two values.
Symbol Name
== Equal to
!= Not Equal to
< Less Than
> Greater Than
<= Less than or Equal to
>= Greater than or Equal to
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
Symbol Name
= Assign
+= Add and Assign
-= Subtract and Assign
*= Multiply and Assign
/= Divide and Assign
%= Modulus and Assign
v. Increment and Decrement Operator:
Symbol Name
++ Increment
-- Decrement
1.7.2 Expressions
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 7;
int sum = a + b;
int product = a * c;
return 0;
}
#include <stdio.h>
int main() {
int x = 5, y = 10;
return 0;
2.1 Introduction
Control statements in the C programming language are essential
constructs that allow you to dictate the flow of a program. They
determine the sequence in which instructions are executed, based
on conditions and loops. Control statements help you create flexible
and dynamic programs by enabling you to make decisions and repeat
actions as needed. In C, there are mainly four types of control
statements: conditional statements, switch case statements, loops,
and jump statements.
2.2.1 if Statement
if (condition) {
Breakdown of Syntax:
Example:
}
In this example, if the age variable is greater than or equal to 18, the
message "You are an adult" will be printed.
if (condition) {
} else {
Example:
} else {
In this example, if the age variable is less than 18, the message "You
are a minor" will be printed because the else block is executed.
2.2.3 else-if Statement
if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else {
Example:
printf("A grade.\n");
printf("B grade.\n");
} else if (score >= 70) {
printf("C grade.\n");
} else {
printf("F grade.\n");
switch (expression) {
case constant1:
break;
case constant2:
break;
Example:
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good!\n");
break;
case 'C':
printf("Average.\n");
break;
default:
printf("Not specified.\n");
In this example, the switch statement checks the value of grade and
executes the code block corresponding to the matching case label.
2.4 Loops
Loops are important control structures in the C programming
language that let you continually run a piece of code based on a
given condition. They provide you the ability to handle arrays or
collections of data, automate repetitive activities, and execute
actions a certain number of times. The "while" loop, the "for" loop,
and the "do-while" loop are the three main forms of loops offered by
C. We'll examine each form of loop, its syntax, use cases.
while (condition) {
Breakdown of Syntax:
Example:
int count = 0;
while (count < 5) {
In this example, the while loop runs as long as count is less than 5. It
prints the current value of count and increments it in each iteration.
The “for” loop is a versatile and widely used loop in C. It allows you
to specify loop initialization, condition, and update expressions all in
one line. The syntax of the “for” loop is as follows:
Breakdown of Syntax:
do {
} while (condition);
Breakdown of Syntax:
int num = 0;
do {
goto label;
// ...
label:
Breakdown of Syntax:
Example:
#include <stdio.h>
int main() {
int i = 0;
loop_start:
if (i < 5) {
i++;
goto loop_start; // Jump back to the loop_start label
return 0;
In this example, the program uses “goto” to create a loop that prints
the value of i while incrementing it until it reaches 5.
if (i == 5) {
In this example, the break statement is used to exit the “for” loop
when i becomes equal to 5. This prevents further iterations of the
loop.
Using “break” in Switch Statement
switch (choice) {
case 1:
break;
case 2:
break;
default:
if (i == 2) {
continue; // Skip the iteration when i is equal to 2
int result = a + b;
void greet() {
printf("Hello, world!\n");
In a void function, you can use return without a value to exit the
function. It's optional in void functions, as shown above.
3
Function
3.1 Introduction
In the C programming language, a function is a named chunk of code
that can accept input arguments, carry out actions, and, if you want
to return a result. It has a specific capability and enables it to be
called from other software areas. The separation of concerns is
encouraged through functions, which also improve the general
structure and manageability of C programs. They are defined using a
particular syntax that has a name, a return type, a list of required
parameters, and the body of the function, which contains the actual
code to be performed. Functions are important tools for code reuse
and abstraction in C since they may be called repeatedly from
different places in the program.
Example:
#include <stdio.h>
// Function declaration
int main() {
int result;
int a = 5;
int b = 3;
// Calling the add function
return 0;
// Function definition
3.3.1 Parameters
Example:
#include <stdio.h>
int main() {
greetUser(userName);
return 0;
}
Explanation about Example:
3.3.2 Arguments
Example:
#include <stdio.h>
// Function declaration
int main() {
int result;
int a = 5;
int b = 3;
return 0;
// Function definition
}
Explanation about Example:
Here, ‘a’ and ‘b’ are the arguments passed to the add function.
return_type function_name(parameters) {
// Function body
}
return_type: Indicates the data type of the value that the
function will return, such as “int”, float, or any other valid C
data type. If the function doesn't return a value, you use void
as the return type.
function_name: The name of the function.
parameters: Any input values or parameters that the function
might require.
expression: The value that the function sends back as its result.
This expression should match the specified return type.
Example:
#include <stdio.h>
// Function declaration
int main() {
int result;
int a = 5;
int b = 3;
// Function definition
return sum;
return_type: This is the data type of the value that the function
is expected to return. Use void if the function doesn't return a
value.
result_variable: An optional variable to store the value
returned by the function.
function_name: The name of the function you want to call.
arguments: Any values or expressions enclosed in parentheses
() that you want to pass as input to the function. If the function
doesn't require any input, you can leave the parentheses
empty.
Example:
#include <stdio.h>
// Function prototype
int result;
int a = 5;
int b = 3;
// Calling the add function and storing the result in 'result' variable
return 0;
// Function definition
return sum;
}
Explanation about Example:
3.6.1 Scope
3.6.2 Lifetime
Example:
#include <stdio.h>
int main() {
return 0;
4.1 Introduction
An array is a group of identically typed items that are kept in close
order to one another in memory. Access to these items is made
possible via an array's index or position. When you declare an array
in C, you must specify how many items it will include; this size cannot
be modified at a later time. For storing and managing collections of
data, such as numbers, characters, or other forms of values, arrays
are frequently employed. A C array's first member normally has an
index of 0, and its last element typically has an index that is one
lower than the array's size.
int myArray[5];
Explicit Initialization: You can explicitly specify the initial values for
each element in the array using curly braces “{}” and providing the
values separated by commas. For example:
This initializes “myArray” with the values 10, 20, 30, 40, and 50,
respectively.
Example:
#include <stdio.h>
int main() {
printf("myArray1: ");
printf("\n");
printf("myArray2: ");
printf("\n");
printf("myArray3: ");
printf("\n");
return 0;
Important (Arrays):
Array Index
Array Bounds
#include <stdio.h>
int main() {
// Modify an element
myArray[1] = 99;
return 0;
Use a Loop
Ensure that the loop terminates when the index reaches the last
valid position in the array. In this case, the condition “i < arraySize”
ensures the loop stops after processing all elements.
Example:
#include <stdio.h>
int main() {
int sum = 0;
sum += myArray[i];
return 0;
}
int matrix[3][4];
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
};
printf("\n");
This nested `for` loop first iterates through each row and then within
each row, it iterates through the columns, printing each element.
Example:
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access and print elements in the 2D array
printf("Matrix:\n");
return 0;
Matrix:
1 2 3
4 5 6
7 8 9
Declare the function that will receive the array as an argument. The
function signature should include the array's data type and a pointer
to the array. You can also specify the array size or omit it.
Define the function as you would any other function. The parameter
“arr[“] represents a pointer to the array, and size represents the
number of elements in the array. You can now work with the array
inside the function.
In your main program, call the function and pass the array as an
argument. Make sure to provide the correct array and size. Any
changes made to the array inside the function will affect the original
array because you are working with the same memory location.
int main() {
myFunction(myArray, size);
return 0;
}
Example:
#include <stdio.h>
arr[i] *= 2;
int main() {
doubleArray(myArray, size);
return 0;
char strArray[3][20];
You can assign values to the elements of the string array either
during declaration or later in your program. Here's an example of
assigning values during declaration:
char strArray[3][20] = {
"Hello,",
"World!",
"C Programming"
};
You can access and manipulate individual strings within the string
array using array indices and string manipulation functions from the
“<string.h>” library. Here's an example of accessing and printing the
strings:
#include <stdio.h>
#include <string.h>
int main() {
char strArray[3][20] = {
"Hello,",
"World!",
"C Programming"
};
for (int i = 0; i < 3; i++) {
// Modify a string
strcpy(strArray[1], "Universe!");
return 0;
In this example, we print the strings stored in the strArray, then use
strcpy to modify the second string.
Output:
String 1: Hello,
String 2: World!
String 3: C Programming
#include <stdio.h>
#include <stdlib.h>
int main() {
int* intArray[5];
intArray[i] = (int*)malloc(sizeof(int));
*intArray[i] = i * 10; // Store a value in the allocated memory
return 0;
Deallocate Memory
5.1 Introduction
A pointer is a variable that stores the memory address of another
variable in the C programming language. By referring to the region in
memory where the real data is kept, pointers are used to alter and
access data indirectly. They are a core component of C and are
frequently used for operations like dynamic memory allocation, the
efficient manipulation of data in memory, and the creation of data
structures like arrays and linked lists. Pointers may be used to
execute operations like dereferencing (accessing the value at the
pointed memory location) and pointer arithmetic (manipulating the
memory address). Pointers are defined using an asterisk (*). For
effective low-level memory management and C programming, an
understanding of pointers is essential.
To declare a pointer, you need to specify the data type it points to,
followed by an asterisk (*), and then the pointer variable name. For
example, if you want to declare a pointer to an integer, you would
do it like this:
This declares a pointer variable “ptr” that can hold the memory
address of an integer.
Direct Initialization
int x = 42;
Here, “&x” retrieves the address of the integer variable x, and that
address is stored in the pointer “ptr”.
Dynamic Memory Allocation
Null Initialization
You can initialize one pointer with the value of another pointer of
the same type:
int *ptr1;
Both “ptr1” and “ptr2” will now point to the same memory address.
Example:
#include <stdio.h>
int main() {
*pointer = 99;
Example:
Suppose you have an integer array and a pointer to its first element:
Example:
You can access the value of “num” via the pointer “ptr” using the
dereference operator:
Now, the variable value holds the value 42, which is the same as the
value of num. You can also modify the value through the pointer:
After this operation, both “*ptr” and “num” will have a value of 10.
Accessing values via pointers is crucial when working with data
structures like arrays, linked lists, or when dynamically allocating
memory. It provides a way to interact with data indirectly, making it
easier to manipulate and manage memory efficiently in C programs.
Example:
#include <stdio.h>
(*numPtr)++;
int main() {
int num = 5;
return 0;
free(arr);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
arr[i] = i * 10;
return 0;
Example:
#include <stdio.h>
*ptr1 = *ptr2;
*ptr2 = temp;
int main() {
swap(&ptr1, &ptr2);
return 0;
6.1 Introduction
The fundamental data types in the C programming language that let
you create unique composite data structures are structures and
unions. They make it simpler to work with complicated data in a
program by combining several variables of different data kinds under
a single name. Unions and structures both provide this function,
although they both have unique characteristics and applications.
Structures
struct structure_name {
data_type member1;
data_type member2;
// ...
};
Unions
union union_name {
data_type member1;
data_type member2;
// ...
};
data_type member1;
data_type member2;
// ...
};
Once you have defined a structure variable, you can access its
individual members using the dot (.) operator. Here's the syntax:
variable_name.member_name
value1, value2, etc.: These are the values you provide for the
structure members in the order they are declared in the
structure.
struct Point {
int x;
int y;
};
p1.x = 5;
p1.y = 10;
Now, you have two Point variables, p1 and p2, representing different
points in the 2D coordinate system.
printf("Point p1: (%d, %d)\n", p1.x, p1.y); // Output: Point p1: (5, 10)
printf("Point p2: (%d, %d)\n", p2.x, p2.y); // Output: Point p2: (3, 7)
First, define the structure that you want to pass by value. Let's use a
Person structure as an example:
struct Person {
char name[50];
int age;
};
}
Step – 3 Call the Function
Now, you can create a Person variable and call the “printPerson”
function to print its details:
int main() {
strcpy(person1.name, "Pawan");
person1.age = 30;
printPerson(person1);
return 0;
struct Person {
char name[50];
int age;
};
(p->age)++;
int main() {
strcpy(person1.name, "Bob");
person1.age = 25;
incrementAge(&person1);
return 0;
First, define the individual structures that you want to nest within
the outer structure. These inner structures can have their own
members and data types.
struct Date {
int day;
int month;
int year;
};
struct Student {
char name[50];
int roll_number;
};
Next, define the outer structure that will contain instances of the
inner structures. Declare the inner structures as members of the
outer structure.
struct University {
char name[100];
int established_year;
struct Student students[100];
};
Now, you can create instances of the outer structure and populate
them with data, including instances of the inner structures.
int main() {
myUniversity.established_year = 1990;
strcpy(myUniversity.students[0].name, "Pawan");
myUniversity.students[0].roll_number = 101;
myUniversity.students[0].birth_date.day = 15;
myUniversity.students[0].birth_date.month = 5;
myUniversity.students[0].birth_date.year = 2000;
return 0;
First, define the union that contains the members you want to
access. The union declaration specifies the data types of its
members.
union MyUnion {
int integer_member;
double double_member;
char string_member[20];
};
Next, create a variable of the union type and assign values to one of
its members. Only one member should be accessed and modified at
a time, as they all share the same memory space.
myVar.integer_member = 42;
Remember that you should only access one member of the union at
a time. Accessing a different member will read the same memory
location, potentially leading to incorrect results. For example,
accessing “double_member” or “string_member” after assigning a
value to “integer_member” may yield unpredictable results.
myVar.double_member = 3.14159;
Example:
#include <stdio.h>
union MyUnion {
int integer_member;
double double_member;
char string_member[20];
};
int main() {
myVar.integer_member = 42;
myVar.double_member = 3.14159;
return 0;
// Define a structure
struct Student {
char name[50];
int roll_number;
};
// Define a union
union Color {
char rgb[3];
int hex;
};
In this example, we have a structure Student with two members
(name and roll_number) and a union Color with two members (rgb
and hex).
Next, use “typedef” to create an alias for the structure or union. You
provide the new name you want to use for the data type, followed
by the keyword “typedef” and the original data type.
Now, you can use Student and Color as shorthand names for the
“struct” Student and union Color data types, respectively.
You can now declare variables using the alias instead of the full data
type name, making your code more concise and readable.
int main() {
Student student1;
strcpy(student1.name, "Alice");
student1.roll_number = 101;
Color color1;
color1.hex = 0xFF0000;
return 0;
#include <stdio.h>
#include <string.h>
// Define a structure
struct Employee {
char name[50];
int employee_id;
double salary;
};
// Create aliases using typedef
int main() {
Employee employee1;
employee1.employee_id = 1001;
employee1.salary = 55000.0;
return 0;
7.1 Introduction
Working with data in different applications requires the use of
handling files, which is a key feature of the C programming language.
It gives the program the ability to change file contents as well as read
and write data to files. This feature is important for C programmers
since it is required for operations like data storage, retrieval, and
manipulation.
You must include the standard I/O library, "stdio.h>," which offers
functions and data types for interacting with files, in order to
conduct file handling operations in C. The FILE structure, which
represents a file and holds details like its name, status, and location,
is the main data structure used for handling files. The following
functions are often used for file operations: "fopen()," "fclose(),"
"fread()," "fwrite()," "fscanf()," and "fprintf()."
The multiple file modes that C offers, such as read ("r"), write ("w"),
append ("a"), binary ("b"), and others, specify how the file is
accessed and opened. When interacting with files, error
management is essential since operations might fail for a variety of
reasons, such as file not found errors or permissions problems.
Robust file handling is ensured by checking the return values of file
functions and employing error-handling methods like "perror()" and
"feof()".
To open a file, you can use the “fopen()” function. This function takes
two arguments: the name of the file you want to open and the mode
in which you want to open it (read, write, append, etc.). For example,
to open a file named "example.txt" for reading:
Always close the file when you're done using it to free up system
resources and ensure data integrity. Use the “fclose()” function:
fclose(filePointer);
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
char ch;
if (filePointer == NULL) {
putchar(ch);
}
// Close the file
if (fclose(filePointer) == 0) {
} else {
#include <stdio.h>
Declare a File Pointer: Declare a file pointer variable to represent the
file you want to read from.
FILE *filePointer;
Open the File: Use the “fopen()” function to open the file in the
desired mode (e.g., "r" for reading). Check if the file opened
successfully.
if (filePointer == NULL) {
return 1;
char buffer[100];
Close the File: After you've finished reading from the file, close it
using “fclose()”.
fclose(filePointer);
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
char buffer[100];
if (filePointer == NULL) {
return 1;
printf("%s", buffer);
fclose(filePointer);
return 0;
}
This program opens the file "example.txt" in read mode, reads its
contents line by line using “fgets()”, and prints each line to the
console. Make sure to handle errors and close the file when you're
done to ensure proper file handling in your C programs.
#include <stdio.h>
FILE *filePointer;
Open the File: Use the “fopen()” function to open the file in the
desired mode, such as "w" for write mode. If the file does not exist, it
will be created. Check for successful file opening.
if (filePointer == NULL) {
Close the File: After you've finished writing, close the file using
“fclose()”.
fclose(filePointer);
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
if (filePointer == NULL) {
return 1;
}
fclose(filePointer);
return 0;
if (someFunction() == -1) {
perror("Error occurred");
if (filePointer == NULL) {
return 1;
Example:
#include <errno.h>
#include <string.h>
int main() {
if (filePointer == NULL) {
return 1;
fclose(filePointer);
return 0;
Examples:
Source code files, configuration files, log files, and documents (e.g.,
.txt, .c, .html, .csv).
#include <stdio.h>
int main() {
if (textFile == NULL) {
return 1;
}
fprintf(textFile, "Hello, world!\n");
fclose(textFile);
return 0;
Examples:
Image files (e.g., .jpg, .png), audio files (e.g., .mp3, .wav), and
compiled program files (e.g., .exe, .o).
#include <stdio.h>
int main() {
if (binaryFile == NULL) {
fclose(binaryFile);
return 0;
When working with text files in C, you often use functions like
“fprintf()” and “fscanf()” for reading and writing. For binary files, you
use “fwrite()” and “fread()” to read and write binary data.
Important
The choice between text and binary files depends on the data's
nature. Text files are suitable for human-readable, structured data,
while binary files are more versatile for arbitrary data types but are
not human-readable. Properly choosing between these file types
ensure efficient and accurate data storage and retrieval in C
programs.
Example:
#include <stdio.h>
int main() {
if (filePointer == NULL) {
return 1;
}
// Move the file position to offset 5 from the beginning
fseek(filePointer, 5, SEEK_SET);
char buffer[100];
fclose(filePointer);
return 0;
}
In this example,
As a result, you can control where you read or write data within a
file by manipulating the file position with “fseek()”. The second
argument of “fseek()” is the offset, and the third argument specifies
the reference point for seeking (“SEEK_SET” for the beginning,
“SEEK_CUR” for the current position, and “SEEK_END” for the end of
the file). Proper file positioning is crucial for efficient and accurate
file I/O operations in C.