0 ratings0% found this document useful (0 votes) 422 views25 pagesC Programming (Hand Written Notes)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
1. Introduction to C Programming
1.1. What ic C?
Welaberation: C ic a powerful, general-purpose programming language known for its
ePiciency and flexibility. Tt was developed in the early 17700 by Dennis Ritehie
at Bell Labs. C provides low-level access to memory, making it suitable for
ramming, but it alco supports high-level constructs for application
prog PP opp
development. It has a rich history and has influenced many other programming
languages.
Example: Here's a cimple “Hello, World!” program in C:
World! \n');
yp Your Development Environment:
start programming in C, it's important to cet up your
it. Thie involvec installing a C compiler, such ac GCC (GU
1 a code editor or integrated development environment
nr about the basic structure of aC
¢, the main function, and the
section, youll have a working
1.1 serves as a practical exempleChapter 2: Basic Syntax and Data Types
In thie chapter, we'll delve into the fundamental building blocks of
C programming. You'll learn about the syntax uced in C programs
and explore various data types, which are eccential for storing and
manipulating information.
2.1. Variables and Constants
Variables: Variables are named ctorage locations that hold data.
They are declared using a data type followed by a name.
Example: int age; declares an integer variableCharacter Data Type: The char data type is used to store single
characterc.
Example: char grade = ‘A>
2.3. Operators and Expressions
Arithmetic Operators: C supports arithmetic operators like +, -,
/, and % for basic mathematical operations.
Example: int recult = 10 + 5;
Relational Operators: Relaticseveral control structures
u to execute a block of code if a
ig fale, the code inside the if block ic
: The elce ctatement can be used in conjunction with if to execute
block of code if the condition ic Falce.
int num = 5;
(oum % 2 == 0)
printf The number ig even.\n');
J elce {
printf(The number i¢ odd.\n"):
i
Switch Statement: The ewitch ctatement ic used when you have multiple
conditions to evaluate. It provides a way to chooce between ceveral different code
blocks based on the value of an expression.
Example:
char grade = 8:e while loop repeatedly executes a block of cade as long as a
is Crue.
count = 1;
while (count <= 5) {
printf Count: %d\n', count);
count++;
i
| For Loop: The for loop is commonly used for iterating over a range of values or
performing a specific number of iterations.
Example:
for int i = 4; 1 <= 5; ite) {
printf Iteration $d\n", i);4. [Farctions and Modular Programming]
Function Basics En C programming, a function ic a self-contained block of code
that performs a specific tack. Functions allow you to break your program into
omaller, manageable pieces, making your code more organized and easier to
t takes two integers ac parameters and
lo add and prints the recult.
before ite actual definition. It
about the function's name, return
are usually placed at theint add(int a, int 6);
main() {
add(5, 3):
ult: d\n", result);
for add tells the compiler what to expect when it
the main function.
where a function calle itself to colve a
ant way to solve certain typec of problems.printf Factorial of fd ic d\n", n, result);
return 0;
I
thie example, the factorial Function caleulates the factorial of a number using
d Lifetime of Variables :
C have a scope (where they can be accecced) and a lifetime (how
ict). Understanding variable scope and lifetime ic crucial for writingwith 5 elements
.e firct element (index 0)
16 2 to the second element (index 1)
l Arrays =
idimensional arrays are arrays of arrays, forming a
structure. They are useful for representing tables, grids, and
matrices.
Example:
int matri[3][3] = {{1, 2, 3}, 4, 5, 68, ¢#, & Wf:
// Accessing elements
int element = matrix{1][2]; //Retrievec the value 6 from the matrix
5.3 Strings in C :
Tn © strings are represented ac arrays of characters. They are
null-terminated, meaning they end with a null character (\0') to cignify
the end of the string.
Example:
char greeting[6] = “Hello”: //Tneludes space for the null character
char name] = “John’: Auffmatically sized based on the string lengthrecult); /Dutput: “Hello World”
| strlen(recult); /fbet the length of the reculting string
rrintt Length: Bd\n", length); //Output: "Length: 17”
return 0;6. [Pointers
Pointere are a fund.
work directly with +
for efficient memory §
tasks.
6.1 Understanding Pointers
What Are Pointers?
Pointers are variablec that store y
They are denoted by an asterisk (*). For
int x= 10; Regular variable
int “ptr = Bx; ffbinter to int
Here, ptr stores the memory addrece of x.
Pointer Arithmetic :
You can perform arithmetic operations on pointers, such
and decrementing them. For instance:
int arrl5] = {1, 2, 3, 4, 5:
int “p = arr[2];
prt: (Moves p to the next element (arr[3])
6.2 Dynamic Memory Allocation (malloc, calloc, free)
malloc and calloc :
malloc and calloc are functions used for dynamic memory allocation.
malloc allocates a block of memory, while calloc initializes the allocated
memory to zero. Here's an example:
int Aare = (int “)malloo(5 * cizeoflint)); //Allocatec memory for an
array of 5 intsAfter you're d
it using free to
free(arr); //Releasec
Example: Dynamic Array
Creating a dynamic array
int size = 5;
int “dynamicArr = (int “)malloc(size
for (int i = 0; i < gives ine) f
dynamicArr[i] = i * 10;
i
free(dynamicArr); //Don't forget to free the mer
6.3 Pointers and Arrays :
Arrays and Pointers :
Arrays and pointers are clocely related in C. An array n
a pointer to ite first element:
int mumbere[] = {1, 2, 3, 4, SI;
int “ptr = number; (ptr points to the firct element of numbers
Pointer-to-Array -
You can create pointers to entire arrays, allowing you to manipulate
arrays more flexibly:
int arr[3] = (10, 20, 30);
int Cptr)[3] = &arr; /jptr ic a pointer to an array of 3 intsChapter #: [Structures and Unions]
2.1 Defining and Using Structures :
Structures in C allow you to group together variables of different data
types under a cingle name. They are fundamental for organizing data in
complex programs.
Example:
U/ Define a structure for a point in 2D space
struct Point {
inl x;Unions are similar to structure but allow you to store different data
types in the came memory location. Thie can be uceful when you want to
save memory, and you only need to accece one member at a time.
Example:
// Define a union for storing integers and floats
union Data {declarations.
Example:
U/ Define a typedef for a complex number
typedef struct {
double real;
+ BAIP\n’, num.real, nurm.imag):Chapter 8: [File Handling]
File handling in C ie eccential for reading and writing data to and from
files. Thie chapter explorec how to work with filec, perform input and
output operations, and handle errore effectively.
8.1 File I/O Operations :
Opening a File: Before you can read from or write to a file, you muct
open it. You can uce the fopen function for thie purpose. Here's an
example:
FILE “flePointer;
flePointer = fopen(‘example.txt’, 'r’);
if (flePointer == NULL) £
printl(File could not be opened.’);
return 7;
i
Reading Fromprintf File could not be created.");
return 1;
J
PorintfoutputFile, "Hello, World!’);
feloce(outputFile);
Clocing a File: Always cloce a file when you're done with it to free up
recources.
Feloce(FlePointer);
8.2 Error Handling with Fileo :
Checking for File Existence: You can use the
a file exicte before attempting to open it.
if (accece(‘example.txt’, FOK) 4 -
printf File existe.\n");mescages.
FILE “fle = fopen(‘nonexistent.txt’, 'r’):
if (Ble == NULL) £
perror(Error opening file’);
i
Thic chapter equips readere with the knowledge and practical ckille
needed to manipulate files in C. Understanding fle I/0 and error
handling i¢ crucial for various real-world applications, cuch ¢
processing and file management.programming, delv
2.1 Preproceccor Dir
The C prepri
before the actual compilation
conditional compilation and macro
Conditional Compilation: Conditional
exclude parte of your code based on pr
used to create code that behaves differently
#inclade
Hdefine DEBUG 1
int main() £
it DEBUG
printf Debug mode ic enabled.\n’);
ffelee
printl' Debug mode ic dicabled.\n");
Hendif
return 0;
i
Macros: Macros are a way to define reucable code cnippets. They are
often used for constants or simple functions.
Hdefine SQUARE (x) (x * x)
int main() {
int result = SQUARE (5);macros that can be uced
input/output, math, string +
Example: Using Standard
Hinclude
int main() £
double num = 16.0;
double squareRoot = cart (num);
printl(The square root of KIf i¢ Kiln", nui,
return 0;
i
7.3 Command-Line Arguments :
C programs can accept command-line arguments, allowing user
provide imput when running the program
Example: Command-Line Arguments
flinclude
int main(int arge, char “argv[]) {
if (arge 42) £
printf(Usage: s\n", argv[o]);
return 7;
iExample: Bit Mas
#inclade
int main() {
unsigned char flags = Ox0A;
flags [= (1 << 2); Set the third
flags &= ~(1 << 1); Cleof/the
printt( Flags: fx\n’, flags); //Output:
return 0;
iChapter 10: [C in Practice
In thie chapter, we will explore the
programming language. We will
and efficient C code, provide
offer concrete examples to illustrate
10.1 Best Practices :
Writing good C code involves
readability, maintainability, and ¢|
guidelines:
Naming Conventions: Use meaning!
and symbol names. For example, ins
reprecent the number of elements in
Code Formatting: Consistently format |
spacing conventions. Thig makes your
for (int i = 0; 4 < 10; ist) £
printf Tteration d\n’, i);
i
Commenting: Add comments to explain 6
important functions. Comments improve ¢
instance:
/* Caleulate the Factorial of a number “/
int factorial(int m) {
Bhke case
irc dt
return 7;J Uf Recursive cage
return n * factorial(n - 1):
J
Error Handling: Properly
error codes, return values, oF
10.2 Case Studie =
Th thie section, we will examine
Let's look at one example:
Case Study: File Compression
Imagine you are tacked with d
This case study will cover the de:
such a tool. Well delve into data
performance optimization techniques, ‘
practical applications.
10.3 Real-world Examples +
To illustrate the concepte diccucced in
code examples. Here's an example that
#include
int main() £
FILE “fle = fopen(‘non_exictent.txt”, 'b')-
if (Ble == NUL) {
perror(Error opening file’);
exit(1);
WW File procecsing code goec here...
feloce(le);return 0;
J
In thie example, we
cuccecsfully, and handle «