C Programming
C Programming
LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
C Programming
Material
OUR PARTNERS &
CERTIFICATIONS
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
c programming
1. Introduction to C Programming
Overview of C language
History and significance of C
Structure of a C program
Setting up a C development environment
3. Operators in C
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Increment and decrement operators
4. Control Structures
Conditional statements (if, if-else, switch)
Looping structures (for, while, do-while)
Break and continue statements
Nested loops and conditional statements
5. Functions in C
Defining and calling functions
Function arguments and return types
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Recursion
Function overloading (if applicable in context)
Scope and lifetime of variables (local vs. global)
7. Pointers
Introduction to pointers
Pointer arithmetic
Pointers to arrays, functions, and structures
Dynamic memory allocation (malloc, calloc, free)
Pointer to pointer, void pointers
9. File Handling in C
File operations (fopen, fclose, fread, fwrite, fprintf, fscanf)
Text vs. binary files
1.Overview of C language
2.Procedural Programming
C follows a procedural programming paradigm, where the logic of the program is
broken down into small, reusable functions or procedures. The focus is on
executing a sequence of instructions and manipulating data.
3.Portability
One of the core features of C is portability. A program written in C can be
compiled and run on any machine with minimal changes, making it highly
versatile. This is why C is often used to write system-level software, including
operating systems and compilers.
.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
4. Low-level Access
C gives the programmer full control over memory through pointers. With functions
like malloc, calloc, and free, C allows dynamic memory allocation and deallocation,
which is essential for creating efficient programs.
8.Standard Library
C comes with a rich standard library that provides a wide range of functions for tasks
such as input/output (I/O), string manipulation, mathematical computations, and
memory management. This saves time and effort in program development.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
9.Structured Language
int main() {
printf("Hello, World!\n");
return 0;
}
#include <stdio.h>: This is a preprocessor directive that includes the standard
input/output library for functions like printf.
2.Variables and Data Types: C allows you to declare variables with a specific data type.
Common types include:
3.Control Structures: C has standard control structures such as if, else, for, while, and
switch for conditional logic and looping.
4.Functions: Functions in C are blocks of code that perform specific tasks. You can define
functions to make your program more modular and easier to maintain.
History of C
The C programming language was developed in the early 1970s by Dennis Ritchie at Bell
Labs as part of the development of the Unix operating system. It was originally designed to
overcome the limitations of earlier programming languages like B and BCPL.
1. Predecessors to C:
BCPL (Basic Combined Programming Language): Before C, BCPL was used in the
early 1960s for writing system software. It was a high-level language with limited
functionality compared to what we have today.
B Language: Dennis Ritchie and Ken Thompson, another Bell Labs researcher,
developed the B language in the late 1960s, influenced by BCPL. B was still quite
low-level and lacked modern data types like int or float.
2.Creation of C (1972):
7.C11 (2011): Another update to the standard, C11 introduced features like multi-
threading support, better Unicode handling, and more, further improving the
language's utility for modern programming.
Significance of C
1. Portability:
One of C’s greatest contributions to programming is its portability. The
ability to write programs in C that could be compiled and executed on
different machines was revolutionary. This is especially important in the
development of operating systems and compiler software, where portability
allows the same codebase to work on different hardware.
Structure of a C program
The structure of a C program is organized into different parts, each with its specific
role. Here’s a breakdown of the structure:
1. Preprocessor Directives:
These are commands that are processed before the actual compilation of the
code. They start with the # symbol, such as #include for including libraries.
Common preprocessor directives include:
#include <stdio.h> (to include standard input/output functions)
#define (to define constants or macros)
2.Global Declarations:
This section declares variables, constants, or functions that can be accessed by all
functions in the program.
3.Main Function:
Every C program must have a main() function. This function serves as the entry
point for the program. The execution of the program starts from here.
int main() { \
// statements
return 0;
}
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
4.Local Declarations:
Inside the main() function (or any other function), local variables are declared. These
variables are only accessible within that function.
6.Return Statement:
The return statement in the main() function indicates the termination of the program
and returns a status code to the operating system, typically return 0; for successful
execution.
On Windows:
MinGW (Minimalist GNU for Windows):
a. Download MinGW from MinGW SourceForge.
b. During installation, make sure to select the gcc-core and gcc-g++
components.
c. Add the MinGW bin directory (e.g., C:\MinGW\bin) to the system's PATH
variable.
On macOS:
Install Xcode Command Line Tools:
a. Open Terminal.
b. Type xcode-select --install and follow the prompts.
c.
On Linux:
Use the package manager to install GCC:
For Ubuntu/Debian: sudo apt install build-essential
For Fedora: sudo dnf install gcc
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
For Code::Blocks:
1. Code::Blocks typically comes with a GCC compiler. During installation, ensure the
compiler is selected.
2. After installation, simply open Code::Blocks and start writing your C code. Click
on Build and Run to compile and execute.
4. Test the Setup
Write a simple C program to test the setup. Here’s a basic "Hello, World!" program:
In C programming, variables are used to store data that can change throughout the
program's execution. Each variable must be declared with a specific data type that
determines the kind of data it can hold. Common data types include int (for integers),
float (for floating-point numbers), char (for characters), and double (for larger floating-
point numbers). A variable's value can be modified at any point in the program.
Constants are values that remain unchanged during the execution of a program. They
are useful for representing fixed values like mathematical constants, limits, or
configuration settings. Constants can be declared in two ways in C: using the const
keyword or the #define preprocessor directive. For example, const int MAX = 100; or
#define MAX 100 defines a constant. Constants help improve code readability and
maintainability by preventing accidental changes to values that should remain fixed
throughout the program. Using constants also reduces the risk of errors related to
value changes.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Type conversion
Type conversion in C refers to the process of converting one data type into
another. This is necessary when performing operations involving different data
types or when a certain type is required to achieve accurate results. There are
two types of type conversion in C: implicit and explicit.
1. Implicit Type Conversion (Automatic Conversion):
This type of conversion is done automatically by the compiler when an
operation involves different data types. For example, if an int is added to a
float, the int is automatically converted to float before the operation. This
ensures that the result is accurate.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
In C programming, input and output operations are essential for interacting with the
user. The standard input and output functions are provided by the stdio.h library,
and the most commonly used functions are printf and scanf.
1. printf:
The printf function is used to display output to the screen. It allows formatted
output, meaning you can control how the data is presented. You can print different
data types such as integers, floating-point numbers, and strings using format
specifiers like %d for integers, %f for floats, and %s for strings.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
CHAPTER-3 Operators in C
Arithmetic operators
Relational operators
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Logical operators
1. AND (&&): Returns true if both conditions are true (e.g., a > b && x < y).
2.OR (||): Returns true if at least one condition is true (e.g., a > b || x < y).
3.NOT (!): Reverses the logical state of its operand. If the operand is true, it returns
false, and vice versa (e.g., !a).
These operators are essential for controlling the flow of execution based on multiple
conditions, enabling more complex decision-making in programs.
Bitwise operators
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Assignment operators
1. Increment (++): Increases the value of a variable by 1. It can be used in two forms:
Pre-increment (++a): Increases the value first, then uses the updated value.
Post-increment (a++): Uses the current value first, then increases it.
1. Decrement (--): Decreases the value of a variable by 1. It also has two forms:
Pre-decrement (--a): Decreases the value first, then uses the updated value.
Post-decrement (a--): Uses the current value first, then decreases it.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
The if statement evaluates a condition and runs a block of code only if the condition is
true. For example:
if condition:
# Code to execute if condition is true
The if-else statement provides an alternative, running one block of code if the
condition is true, and another if false:
if condition:
# Code if trueelse:
# Code if false
The switch statement, available in some languages like C and Java, checks a variable
against multiple possible values. It executes code corresponding to the matching
value:
switch (variable) {
case value1:
// Code for value1break;
case value2:
// Code for value2break;
default:
// Code if no match
}
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
The for loop is commonly used when the number of iterations is known in advance. It
has a structure that includes initialization, a condition, and an increment/decrement
statement:
for (int i = 0; i < 5; i++) {
// Code to repeat
}
The while loop repeats code as long as a condition remains true. It checks the
condition before each iteration:
while (condition) {
// Code to repeat
}
The do-while loop is similar to the while loop but ensures that the code block is
executed at least once, as the condition is checked after the execution:
do {
// Code to repeat
} while (condition);
These loops help manage repetitive tasks efficiently, each offering a suitable structure
depending on the situation.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
The continue statement, on the other hand, skips the current iteration and moves
to the next iteration of the loop. This is useful when you want to skip specific
conditions but continue looping. For instance:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skips the iteration when i equals 5
}
}
These statements help refine loop logic, providing more control over how loops
execute and how iterations are managed.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Nested loops and conditional statements are powerful tools in programming that
allow for complex decision-making and repetitive tasks within loops.
A nested loop occurs when one loop is placed inside another. This is often used
when working with multi-dimensional data structures, like matrices. For example, a
nested for loop can iterate over rows and columns:
for i in range(3): # Outer loop
for j in range(3): # Inner loop
print(i, j)
Conditional statements inside nested loops enable more refined control. For
instance, you may want to break out of the inner loop under certain conditions:
for i in range(3):
for j in range(3):
if i == j:
break # Breaks the inner loop when i equals j
print(i, j)
This combination of nested loops and conditional statements allows for highly
flexible and efficient algorithms, especially when working with complex problems
such as searching, sorting, or pattern generation.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
CHAPTER-5 Functions in C
A function is defined using a specific syntax that includes the function's name,
parameters (optional), and the block of code to execute. For example, in Python:
def greet(name):
print("Hello, " + name + "!")
In this case, the function greet is defined to take a parameter name and print a
greeting message.
To call a function, you simply use the function's name followed by parentheses,
passing in any required arguments:
greet("Alice") # Output: Hello, Alice!
Functions help improve code organization, reusability, and readability. They allow
the same block of code to be used multiple times with different inputs, reducing
redundancy and making code easier to maintain. Functions can also return values
to be used elsewhere in the program:
def add(a, b):
return a + b
Calling add(3, 5) would return 8.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Function arguments are values passed to a function when it is called. They allow
the function to work with different inputs. For example, in Python, you define
arguments inside the parentheses when defining a function:
def multiply(a, b):
return a * b
Here, a and b are the function’s arguments, which will be used to perform the
multiplication.
Return types specify what type of value a function will return after execution. In
many languages like Python, the return type is inferred, while in statically typed
languages like C or Java, you must declare the return type explicitly:
int add(int a, int b) {
return a + b;
}
In this case, the function add returns an int. The return value is typically used in
expressions or assigned to variables for further processing. Functions with no
return value can use void as the return type (in languages like C and Java).
Recursion
Recursion is a programming technique where a function calls itself to solve a
problem. It breaks a problem into smaller, more manageable subproblems,
typically with a base case to stop the recursion. For example, calculating the
factorial of a number using recursion:
def factorial(n):
if n == 0:
return 1else:
return n * factorial(n - 1)
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
void display(int i) {
cout << "Integer: " << i << endl;
}
void display(double d) {
cout << "Double: " << d << endl;
}
int main() {
display(5); // Calls display(int)display(5.5); // Calls display(double)return 0;
}
Scope and lifetime of variables (local vs. global)
Scope and lifetime of variables are critical concepts in programming, determining
where variables can be accessed and how long they exist in memory.
Local variables are declared inside a function or block and can only be accessed
within that function or block. They are created when the function is called and
destroyed when the function exits, making their lifetime limited to the duration of
the function's execution.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
def my_function():
x = 10 # Local variableprint(x)
Global variables, on the other hand, are declared outside any function and can be
accessed from anywhere in the program. Their lifetime lasts for the entire
duration of the program’s execution.
Example of a global variable:
x = 10 # Global variabledef my_function():
print(x) # Accesses global variable
Understanding variable scope helps prevent unintended side effects and ensures
better management of resources and data integrity within a program.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Declaring an array defines its name and type without assigning specific values. For
example, in C++:
int arr[5]; // Declares an array of 5 integers
Here, arr is declared as an integer array with 5 elements, but no values are assigned
yet.
Initializing an array involves assigning values to the array elements either at the
time of declaration or later in the code. Initialization can be done in different ways:
STATIC INITIALIZATION: VALUES ARE ASSIGNED AT THE TIME OF DECLARATION:
Int arr[] = {1, 2, 3, 4, 5}; // Array of 5 integers initialized with values
Dynamic Initialization: Values are assigned after the array is declared:
int arr[5];
arr[0] = 1;
arr[1] = 2; // etc.
Arrays can store multiple values of the same type, making them useful for handling
large data sets. The size and indexing (starting from 0) must be considered while
working with arrays
Multi-dimensional arrays
Multi-dimensional arrays are arrays that contain more than one level of data,
allowing you to represent tables, grids, or matrices. They are commonly used when
dealing with complex data structures, such as in scientific computations, graphics,
or when organizing data in rows and columns.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
This declares a 2x3 array, with 2 rows and 3 columns. You can access an element
using two indices:
int value = arr[1][2]; // Accesses the element in the second row, third column
(value 6)
You can extend this concept to higher dimensions, such as 3D arrays, by adding
more indices. Multi-dimensional arrays provide a powerful way to handle
structured data efficiently.
String functions like len() can be used to get the length of a string:
length = len(result) # Output: 11
Strings can also be manipulated using slicing. For example, extracting a substring:
substring = result[0:5] # Output: "Hello"
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Array and string pointers are crucial concepts in languages like C and C++ where
direct memory management is involved. A pointer is a variable that stores the
memory address of another variable, allowing you to access and manipulate data
indirectly.
In the context of arrays, a pointer can be used to refer to the first element of the
array. Arrays and pointers are closely related, as the name of an array essentially
acts as a pointer to its first element.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
For example:
int arr[] = {1, 2, 3};
int *ptr = arr; // Pointer to the first element of the array
For strings, which are arrays of characters, pointers can also be used to manipulate
characters. A string in C is simply a pointer to the first character of an array:
char str[] = "Hello";
char *str_ptr = str;
cout << *(str_ptr + 1); // Outputs 'e' (second character)
Using pointers allows for efficient memory handling and manipulation of arrays and
strings. However, it requires careful management to avoid errors like accessing
invalid memory.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
CHAPTER-7 Pointers
Introduction to pointers
Pointers are variables that store the memory address of another variable. They are
fundamental in languages like C and C++ for efficient memory management and direct
access to data. Instead of working with values directly, pointers allow you to
manipulate memory locations, making them useful for dynamic memory allocation,
arrays, and function arguments.
Pointer arithmetic
Pointer arithmetic allows you to manipulate pointers by performing arithmetic
operations, such as addition or subtraction, to navigate through memory locations.
This feature is especially useful when working with arrays or dynamically allocated
memory.
In pointer arithmetic, the key idea is that pointers are incremented or decremented
by the size of the data type they point to. For example, when you increment a pointer
that points to an integer, it moves by the size of an integer (usually 4 bytes):
int arr[] = {10, 20, 30};
int *ptr = arr; // Points to the first element
ptr++; // Moves the pointer to the second element
cout << *ptr; // Outputs 20
Here, ptr++ moves the pointer from arr[0] to arr[1], not by 1 byte, but by the size of an
integer (typically 4 bytes). You can also subtract pointers to find the distance
between them in terms of array elements:
int *ptr2 = arr + 2;
cout << ptr2 - ptr; // Outputs 2, the number of elements between ptr and ptr2
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Pointers to Arrays: A pointer can point to the first element of an array, allowing
access to all array elements. When you use a pointer with an array, the pointer
can be incremented to navigate through the array elements.
int arr[] = {10, 20, 30};
int *ptr = arr; // Pointer to the first element
cout << *(ptr + 1); // Outputs 20
Pointers to Functions: You can use pointers to reference and call functions
dynamically. This is useful for callback functions or implementing function tables.
void greet() {
cout << "Hello, World!";
}
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
In this example, the Person structure contains a string for the name, an integer
for age, and a float for height. To use the structure, you declare a variable of the
structure type and access its members using the dot (.) operator.
Example of using the structure:
struct Person person1;
strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;
Structures are useful for grouping related data and are commonly used to
represent real-world entities such as students, employees, or products in
programs.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
struct Person {
char name[50];
int age;
float height;
};
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Arrays of structures
In C, an array of structures allows you to store multiple instances of a structure,
making it useful for managing collections of related data. You define an array of
structures just like you would an array of basic data types, but the elements are
structure variables instead of simple types.
Example of defining an array of structures:
struct Person {
char name[50];
int age;
float height;
};
strcpy(people[0].name, "Alice");
people[0].age = 30;
people[0].height = 5.5;
strcpy(people[1].name, "Bob");
people[1].age = 25;
people[1].height = 5.8;
Arrays of structures are useful for storing and manipulating large sets of related
data, such as student records or employee details, in an organized manner.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Pointers to structures
Pointers to structures are widely used in dynamic memory allocation and data
structures like linked lists.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Each line is typically terminated with a newline character (\n), and data is
stored as a sequence of readable characters (ASCII or Unicode).
Common functions for handling text files include fopen(), fclose(), fscanf(),
fprintf(), fgets(), and fputs().
Text files are ideal for storing structured data like configuration files, logs, or
any data that can be interpreted as readable text.
1. Binary Files:
Binary files store data in its raw form, as sequences of bytes, which may
represent any type of data, including images, audio, or compiled programs.
They preserve data exactly as it is stored in memory without any formatting
or encoding.
Functions like fread(), fwrite(), and fopen() with "rb" or "wb" modes are used
to work with binary files.
Binary files are more efficient for large, complex data but are not human-
readable.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
1. #include <filename>:
This syntax is used to include standard library headers or system-defined
files. The compiler looks for the file in predefined system directories, such as
/usr/include on Unix-based systems or the standard directories on Windows.
Example: #include <stdio.h> includes the standard input/output library,
allowing the use of functions like printf() and scanf().
1. #include "filename":
This syntax is used for including user-defined header files. The compiler first
looks for the file in the current directory, and if it is not found there, it checks
the system directories.
Example: #include "myheader.h" includes a user-created header file that may
contain function prototypes, macros, and other declarations.
Using #include effectively helps separate code into modular components. Header
files typically contain declarations, function prototypes, and constants, while the
corresponding source files (.c files) implement the actual functionality. This
separation makes the code more maintainable, reusable, and easier to manage in
larger projects.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Handling errors in C
Error handling in C is crucial for building robust and reliable programs. Unlike higher-
level languages, C does not have built-in exceptions, so errors must be managed
manually through return codes, error flags, and proper checks.
Return Codes: Many C library functions signal errors by returning a specific value,
such as -1 or NULL. For example, functions like fopen() return NULL if the file
cannot be opened, and malloc() returns NULL if memory allocation fails. Always
check these return values before proceeding with operations.
Example:
FILE *file = fopen("file.txt", "r");
if (file == NULL) {
perror("Error opening file");
}
perror() Function: The perror() function prints a descriptive error message to
stderr based on the global errno variable. It is commonly used after a function
fails to provide a detailed explanation of the error.
Example: perror("Error opening file");
Custom Error Handling: For more complex error management, you can define
custom error codes or flags, and create functions to handle specific errors,
ensuring the program responds appropriately.
Exit Codes: Returning specific exit codes (like EXIT_FAILURE or EXIT_SUCCESS)
from main() helps indicate whether a program has executed successfully or
encountered an error.
Example: return EXIT_FAILURE;
By carefully checking for errors and responding accordingly, C programs can handle
unexpected situations effectively, minimizing crashes and undefined behavior.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
In C, the standard library provides several functions for error handling, primarily to
report errors, diagnose problems, and facilitate debugging. These functions rely on
the global variable errno, which holds error codes set by system calls or library
functions when an error occurs.
perror(): The perror() function prints a descriptive error message to stderr. It
outputs a string message followed by the error description corresponding to the
current value of errno. This is useful for diagnosing system errors after function
calls fail.
Example:
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("File opening error");
}
strerror(): The strerror() function returns a pointer to a string that describes the
error code stored in errno. This can be useful when you want to store or
manipulate the error message as a string.
Example:
printf("Error: %s\n", strerror(errno));
errno: The errno variable is set by system calls and library functions when an
error occurs. Common values of errno include EINVAL (invalid argument),
ENOMEM (out of memory), and EIO (input/output error).
exit() and abort(): The exit() function terminates the program, optionally providing
an exit status (usually EXIT_FAILURE or EXIT_SUCCESS). The abort() function is
used for abnormal program termination, often in response to a fatal error.
These functions allow developers to handle and report errors effectively, ensuring
that programs can recover from or report unexpected issues.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Debugging tools are essential for identifying and resolving issues in C programs. Two
of the most widely used tools for debugging are GDB (GNU Debugger) and Valgrind,
each offering unique features to help developers track down bugs, memory issues,
and performance problems.
1. GDB (GNU Debugger): GDB is a powerful debugger used to inspect the behavior of
a program during runtime. It allows you to step through the code line-by-line, set
breakpoints, inspect variables, and trace function calls. GDB is invaluable for
tracking down logical errors, crashes, or unexpected behavior.
Common commands include:
break <function>: Sets a breakpoint at the start of a function.
run: Starts the program in the debugger.
next and step: Step over or into functions.
print <variable>: Prints the value of a variable.
backtrace: Displays the function call stack.
Example usage: gdb ./program
2. Valgrind: Valgrind is a tool for detecting memory management issues, such as
memory leaks, accessing uninitialized memory, and buffer overflows. It helps
ensure that programs do not suffer from memory-related errors, which can lead
to crashes or undefined behavior.
The most common tool in Valgrind is Memcheck, which checks for memory
leaks and improper memory usage.
Example usage: valgrind ./program
These tools significantly improve code quality by providing insights into bugs and
memory issues, making them indispensable in the development and debugging
process.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Bit manipulation
Bit manipulation is a technique in C (and other low-level programming languages) that
involves directly manipulating individual bits of data. It is often used to optimize
performance, reduce memory usage, or work with hardware where operations are
done at the bit level.
Common Bitwise Operators:
1. AND (&): Performs a bitwise AND between two operands. The result is 1 if both bits
are 1, otherwise 0.
Example: 5 & 3 → 0101 & 0011 → 0001 (1 in decimal)
2. OR (|): Performs a bitwise OR between two operands. The result is 1 if at least one
bit is 1.
Example: 5 | 3 → 0101 | 0011 → 0111 (7 in decimal)
3. XOR (^): Performs a bitwise XOR. The result is 1 if the bits are different.
Example: 5 ^ 3 → 0101 ^ 0011 → 0110 (6 in decimal)
4. NOT (~): Flips all the bits of the operand.
Example: ~5 → ~0101 → 1010 (in two's complement, it becomes -6)
5. Shift Left (<<): Shifts bits to the left, effectively multiplying by powers of 2.
Example: 5 << 1 → 0101 << 1 → 1010 (10 in decimal)
6. Shift Right (>>): Shifts bits to the right, dividing by powers of 2.
Example: 5 >> 1 → 0101 >> 1 → 0010 (2 in decimal)
Applications of Bit Manipulation:
Efficient calculations: Bitwise operations are faster and more memory-efficient
compared to arithmetic operations.
Flags and masks: Used in settings like permission systems, where each bit in a byte
or integer represents a different flag.
Data compression and encryption: Bit manipulation is essential for optimizing
storage or securing data.
Bit manipulation is a fundamental tool in systems programming, embedded systems,
and performance-critical applications.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Memory Leaks:
Failure to release dynamically allocated memory with free() leads to memory leaks.
Advanced pointer management involves carefully tracking allocated memory and
ensuring it is freed appropriately to prevent resource wastage.. Pointer Arithmetic:
Pointer arithmetic enables manipulation of arrays and buffers efficiently. By
incrementing or decrementing pointers, you can access array elements or traverse
data structures like linked lists and trees.
Mastering advanced pointers and memory management allows developers to write
efficient, scalable code, particularly in resource-constrained environments or high-
performance systems.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Threads are the smallest unit of execution within a process. They allow a program to
perform multiple tasks simultaneously, which is essential for improving performance,
especially in multi-core systems. POSIX threads (Pthreads) is a widely-used thread
library defined by the POSIX standard for managing threads in C programs.
Key Concepts of POSIX Threads:
Thread Creation:
To create a thread in a C program, you use the pthread_create() function, which
takes a thread identifier, attributes, a function to run, and an argument for that
function.
Example:
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
Thread Synchronization:
Threads may need to synchronize access to shared resources. Pthreads provides
mechanisms like mutexes (pthread_mutex_t) to ensure that only one thread
accesses a resource at a time, preventing race conditions.
Example:
pthread_mutex_lock(&mutex);
// Critical section
pthread_mutex_unlock(&mutex);
Thread Termination:
Threads can terminate by returning from their thread function or calling
pthread_exit(). The main program can wait for threads to finish using
pthread_join().
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Example:
pthread_join(thread, NULL);
Thread Attributes:
Thread attributes control thread behavior, like scheduling or stack size. These can
be set using pthread_attr_t before creating a thread.
POSIX threads enable multi-threading in C, allowing for efficient parallel execution
and better resource utilization in programs that perform tasks concurrently.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
System calls
System calls are the fundamental interface between user programs and the operating
system (OS). They allow a program to request services or resources from the OS, such
as file operations, process management, memory allocation, and device I/O. System
calls are typically invoked through software interrupts, which transfer control to the
OS kernel.
Common system calls include:
File management: open(), read(), write(), close() for manipulating files.
Process control: fork() to create a new process, exec() to replace a process with
another, and exit() to terminate a process.
Memory management: malloc() and free() for dynamic memory allocation, and
mmap() for memory mapping files.
Device management: ioctl() for controlling hardware devices.
These system calls allow programs to interact with the underlying OS and perform
tasks such as reading from a file, allocating memory, or creating new processes. Each
system call has a specific function and follows a defined API to ensure proper
communication between user programs and the OS kernel.
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
T
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Process management
Process management in operating systems involves controlling and handling
processes during their lifecycle, from creation to termination. In C, process
management is achieved using system calls, which allow programs to interact with the
operating system to manage processes, control execution, and retrieve information
about the processes.
Key System Calls for Process Management:
fork():
a. fork() creates a new process by duplicating the calling process. The new
process is referred to as the child process. It returns a value of 0 to the child
and the child’s process ID (PID) to the parent
exec():
The exec() family of system calls replaces the current process’s image with a
new program. It is often used after fork() to execute a different program within
the child process.
wait() and waitpid():
These system calls allow a parent process to wait for the termination of a child
process. wait() returns the PID of the terminated child process, while waitpid()
provides more control over which child process to wait for.
r multitasking and process-based operations in modern operating systems.