C Programming Notes by Coding Age
C Programming Notes by Coding Age
INDEX
1. Introduction to Programming ........................................ 5
1.1 What is a Programming Language? ...................................................... 5
1.2 Introduction to C Language .................................................................. 5
1.3 Compiling and Running a Program ..................................................... 5
1.4 First Program in C ............................................................................. 6
2. Variables in C............................................................. 7
2.1 What is a Variable? ........................................................................ 7
2.2 Variable Naming Rules .................................................................... 7
5. Input/Output in C................................................... 11
5.1 Taking Input: scanf() .................................................................... 12
5.2 Displaying Output in C: printf() ........................................................... 13
6. Operators in C ................................................... 15
6.1 Unary Operators ............................................................................ 16
6.2 Binary Operators (Arithmetic, Relational, Logical, Bitwise) ........... 18
6.3 Assignment Operators .................................................................... 22
6.4 Ternary Operator ........................................................................... 23
8. Loops in C .......................................................... 29
8.1 while Loop ................................................................................... 30
8.2 for Loop ......................................................................................... 31
9. Functions in C .................................................... 35
9.1 Types: Return vs Non-return ........................................................ 37
9.2 Parameters and Arguments ....................................................... 39
C Language:
Compiling a Program:
The code we write, known as source code, is written in a human-readable
form. However, computers can only understand binary machine code (i.e.,
0s and 1s).
For example:
gcc filename.c
Every time we make changes to the source code, we must recompile the
program. This ensures that the latest changes are reflected in the new
executable file.
Running a program(execution) :
The process when a program performs the given task after it has been
compiled, is known as running or execution.
To run a program after it has been compiled, we use the command a.exe
#include <stdio.h>
int main(){
printf("Hello World!");
return 0;
}
C program.
printf("Hello World!"); — This is a statement that prints the text "Hello World!"
on the screen.
The semicolon ( ; ) at the end of each statement marks the end of that
instruction.
Example 2 :
#include <stdio.h>
int main(){
int n = 5;
char b = 's';
return 0;
}
- Here, n is a variable and the word 'int' written right before it, is the
datatype of variable n.
- This statement is similar to the first one. The only difference is that the
datatype of variable b is char.
Variable :
In the previous example, n and b are two different variables, each storing
their own values.
💡
ex: int a; int a; ❌ //not allowed
ex: int a; int b; ✔️ //allowed
Data type :
As the name suggests, data type tells the type of information that can be
stored in a given variable.
1. int
2. long
3. float
4. double
5. char
(These are only the frequently used ones, there are a few more data types in
C.)
Stores a single
char m = 't';
char 1 bytes character/letter/number, within
single quotes.
Note: Size and range of a data type may vary depending on the system being used. The sizes
mentioned above are the general ones.
🎯 Format Specifier in C
🧠 What is it?
A format specifier tells the compiler what type of data is being input or output.
It is used inside functions like scanf() and printf() to properly read or display
values.
Every data type has its own format specifier, below is the list of format
specifiers of some commonly used data types:
Explanation:
Explanation:
All bits are used for the magnitude (no sign bit).
Keywords :
Keywords are the words that have meanings already assigned to them by
the language and theyʼre fixed.
Every keyword has its own job which makes code writing easier for us.
🧠 Syntax of scanf() :
📌 Inside scanf() :
1. Format Specifier : A formatted string (which basically means, format
specifier inside double
quotes) e.g. :
“%d”. It tells the system, the type of value that has to be taken as
input.
2. Address of the variable in which we want to store the user input (attaching
'&'
to the left of variable name gives the address of that variable) e.g. :
&v
🧪 Example 3
📘 C Notes by Coding Age 11
#include <stdio.h>
int main() {
int v, m, n;
float b;
return 0;
}
3. Then it asks for 2 integers – stores them in m and n , then prints them with
"and" in between.
(**printf() and scanf() are two of the many functions defined in stdio.h header
file)
"%d" , “%f" → format specifier
"&v", &m, &n , &b → address of variable (location where a variable is located in the memory)
📚 Both scanf() and printf() are two of the many functions defined in the stdio.h
💡 Tip:
You must use & before variable names in scanf() (but not in printf() ).
📤 Displaying Output in C
In C programming, we display output to the user using a special function:
🧠 Syntax of printf() :
📌 Inside printf() :
1. Format Specifier: Written inside double quotes. It tells the program what
type of data to print — like %d for integers or %f for float.
3. Both the format specifier and the variable name are separated by a comma.
int main() {
int age = 20;
float weight = 55.5;
return 0;
}
\n is a newline character, which moves the output to the next line after
printing.
int main() {
int num;
float price;
return 0;
💡 Tips:
You do not use & in printf() — only use it in scanf() .
Operators :
What is an Operator?
An operator is a symbol or sign that tells the computer to perform a specific
action or calculation on one or more operands.
Example to Understand:
If you see this:
2+3
1. Unary Operator:
1) Increment Operator :
Pre-Increment ( ++var )
The ++ operator is placed before the variable (on the immediate left).
Post-Increment ( var++ )
The ++ operator is placed after the variable (on the immediate right).
2) Decrement Operator :
Pre-Decrement ( -var )
The - is placed before the variable.
Post-Decrement ( var-- )
The - is placed after the variable.
#include <stdio.h>
int main(){
int a = 4, b = 10;
int z = ++a; //Pre Increment
printf("%d ", z); // Output is 5 (increased immediate
ly)
int y = b++; //Post Increment
printf("%d ", y);
// Output is 10 (did not increase in the current expression)
y = b; //now increased by 1
printf("%d ", y); // Output is 11
//-------------------------Same goes for Decrement Operator,
it decreases by 1
int c = 21, d = 7;
int x = --c; //Pre Decrement
printf("%d ", x); // Output is 20 (decreased immediatel
y)
int w = d--; //Post decrement
printf("%d ", w); // Output is 7 (did not decrease in t
he current expression)
w = d;//now decreased by 1
✅ Tip to Remember:
Pre = Change first, then use
2. Binary Operator:
A
binary operator works with two operands. It performs operations using one
operator and two values.
1) Arithmetic Operator( +, - , *, /, %) :
Performs basic mathematical operations.
#include <stdio.h>
int main(){
int a = 3;
int b = 2;
printf(“%d”, (a+b)); // Output is 5
return 0;
}
Example 7 :
#include <stdio.h>
int main(){
int a = 5, b= 7, c = 9;
Example 8:
#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a&b); //Output is 2 which is 0010 in binary
return 0;
}
#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
#include <stdio.h>
int main(){
int a = 10; //001010
printf(“%d”, a<<2); //Output is 40 which is 101000 in binary
return 0;
}
Fills the emptied bits on the left with 0 (for unsigned numbers).
Example 11:
#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a>>b); //Output is 2 which is 0010 in binar
y
return 0;
}
v) ^ (bitwise XOR)
Returns 0 if both bits are the same; returns 1 if the bits are different.
#include <stdio.h>
int main(){
int a = 10; //1010
int b = 2; //0010
printf(“%d”, a^b); //Output is 8 which is 1000 in binary
return 0;
}
Example 13:
#include <stdio.h>
int main(){
int a = 11;
print("%d",
return 0;
}
Operator Description
+= c += a is equivalent to c = c + a
-= c -= a is equivalent to c = c - a
*= c *= a is equivalent to c = c * a
/= c /= a is equivalent to c = c / a
% c % a is equivalent to c = c % a
Example 14:
#include <stdio.h>
int main(){
int x = 20;
x += 10;
printf("x+10 = %d", x);//now x is 30
x *= 10;
printf("\nx*10 = %d", x);//now x is 200
x /= 10;
printf("\nx/10 = %d", x);//now x is 20
x %= 10;
printf("\nx%%10 = %d", x);//now x is 0
return 0;
}
3. Ternary Operator:
1) Conditional Operator( ? : ):
The ternary operator is a shortcut for simple if-else conditions.
statements.
Syntax :
Example 15:
🌟Conditional Statements
🔸 Why use Conditional Statements?
Conditions allow us to make decisions in a program.
Conditional statements help us control the flow of the program and instruct
the machine what to do when a condition is met or not met.
📘 Explanation:
The if statement is used when you want to execute a block of code only when
a certain condition is true. If the condition is false, the code inside if does not
run.
📌 Think like this:
📘 C Notes by Coding Age 24
“If this condition is true, then do this task.”
if(condition) {
// code to execute if condition is true
}
✅ Example:
int a = 5, b = 3;
if(a > b) {
printf("a is greater than b");
}
📘 Explanation:
The else statement comes after an if and is used when the if condition is false.
So, either if runs or else runs, not both.
📌 Think like this:
“If this is true, do this. Otherwise, do that.”
if(condition) {
// code if true
} else {
// code if false
}
✅ Example:
int r = 2, p = 5;
if(r > p) {
printf("Not equal");
} else {
🧾 Output: Equal
📘 Explanation:
When you want to check multiple conditions, use else if . If the if condition is
false, it checks the next one. You can have many else if s.
📌 Think like this:
“If not this, then maybe that.”
if(condition1) {
// executes if condition1 is true
} else if(condition2) {
// executes if condition2 is true
} else {
// executes if none are true
}
✅ Example:
int a = 10, b = 13;
if (a > b) {
printf("%d", a);
} else if (a < b) {
printf("%d", b);
} else {
printf("a and b are equal");
}
🧾 Output: 13
if(condition1) {
if(condition2) {
// executes only if both conditions are true
} else {
// executes if only condition1 is true
}
} else {
// executes if condition1 is false
}
✅ Example:
int z;
printf("Enter a number = ");
scanf("%d", &z);
if(z % 2 == 0) {
if(z % 3 == 0) {
printf("%d is an even number divisible by 3", z);
} else {
printf("%d is an even number but not divisible by 3", z);
}
} else {
printf("%d is not an even number", z);
}
🧾 Sample Input: 6
switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no match
}
✅ Example:
int option;
printf("Enter option - ");
scanf("%d", &option);
switch(option) {
case 1:
printf("Selected option is 1");
break;
case 2:
printf("Selected option is 2");
break;
case 3:
printf("Selected option is 3");
break;
default:
🧾 Input: 2
🔔 Note:
Always use break after each case to avoid fall-through.
🔁 Loops
🔸 Why use Loops?
Loops allow us to execute a block of code multiple times, either a fixed or
variable number of times.
They make the code more efficient, clean, and shorter, especially when
doing repetitive tasks.
Instead of writing the same code again and again, we can use a loop to
repeat it.
🔹 Types of Loops in C:
📘 C Notes by Coding Age 29
There are 3 primary types of loops in C:
1️⃣ while loop
2️⃣ for loop
3️⃣ do-while loop
while(condition) {
// code block
}
✅ Example:
#include <stdio.h>
int main() {
int j = 1;
while(j <= 3) {
printf("This is a while loop.\n");
j++;
}
return 0;
}
🧾 Output:
This is a while loop.
This is a while loop.
This is a while loop.
✅ Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
printf("This is a for loop.\n");
}
return 0;
}
🧾 Output:
This is a for loop.
This is a for loop.
This is a for loop.
This is a for loop.
This is a for loop.
It ensures the code runs at least once, even if the condition is false.
do {
// code block
} while(condition);
✅ Example:
📘 C Notes by Coding Age 32
#include <stdio.h>
int main() {
int k = 1;
do {
printf("This is a do-while loop.\n");
k++;
} while(k > 5);
return 0;
}
🧾 Output:
This is a do-while loop.
🔁 Nested Loops
📘 Explanation:
A loop inside another loop is called a nested loop. There can be any
number of loops inside a loop.
For each outer loop iteration, the inner loop runs completely.
✅ Example:
#include <stdio.h>
int main() {
int n = 3, i, j;
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
printf("* ");
}
🧾 Output:
***
***
***
💡 You can also use nested while and do-while loops in the same way.
🛑 Break Statement
📘 Explanation:
break is used to exit a loop or a switch statement immediately.
✅ Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
printf("Loop terminated at %d\n", i);
break;
}
printf("Break Statement %d\n", i);
}
return 0;
}
🔄 Continue Statement
📘 Explanation:
continue skips the current iteration and goes to the next iteration of the
loop.
✅ Example:
#include <stdio.h>
int main() {
for(int j = 1; j <= 5; j++) {
if(j == 4) {
continue; // skips when j == 4
}
printf("%d ", j);
}
return 0;
}
🧾 Output:
1235
📚 Types of Functions in C
Functions are mainly of two types:
The returned value must match the data type specified in the function
definition.
🔧 Syntax:
returnType functionName(parameter1, parameter2, ...) {
// code
return value;
}
📦 Example:
int addTwoNumbers(int m, int n) {
int sum = m + n;
return sum;
}
📌 Explanation:
For example, the addTwoNumbers ( return type is int ) function returns the
sum which is an integer.
💡 Real-Life Analogy:
Like a calculator: You press 5 + 6, and it gives you 11 as
output.
🔧 Syntax:
void functionName(parameter1, parameter2, ...) {
// code
}
📦 Example:
void sumOfTwoNumbers(int k, int j) {
int sum = k + j;
printf("Sum is %d", sum);
}
📌 Explanation:
void is used because we don’t want to return anything.
The "Void function" does not return any value. Hence, we write void at the
beginning, which indicates that the function upon being called, does not
return any value.
For example, the sumOfTwoNumbers function prints the value of sum but does
not return any value.
🏷️ Function Name
A function name is the identifier given to a function. It is used to call the
function.
They represent the inputs that the function expects to receive when it is
called.
📦 Example:
void printAlpha(char ch) {
printf("Alpha, %c!", ch);
}
They are used to fill the parameters and are given inside the parentheses
during a function call.
📦 Example:
int main() {
printAlpha('A'); // 'A' is the argument
return 0;
}
🚀 Calling a Function
Here’s how you call a function from main() :
#include <stdio.h>
// Void function
void sumOfTwoNumbers(int k, int j) {
int sum = k + j;
printf("Sum is %d\n", sum);
}
return 0;
}
📍 Control Transfer
The moment a function is called, the control of the program shifts from main()
🛠️ Function Execution
The function performs its specific task. The statements inside the function
block are executed line by line.
🔹 Step 3:
If it’s a void function, it does not return any value — it simply finishes its
work (e.g., printing).
🔹 Step 4:
↩️ Return to Caller
Control goes back to the point just after the function call.
📝 Important Note:
🔹 The execution of every C program always begins with the
function.
main()
📘 Arrays
🔹 What is an Array?
An array is a linear data structure in C that allows you to store multiple
values of the same data type in a single variable.
It is used when you want to store a list of values rather than creating
individual variables for each item.
Memory Representation:
Index: 0 1 2 3 4
Values: 5 8 2 6 9
📌 Indexing starts at 0, and each index holds one element of the array.
🔹 Declaring a 1D Array
int array1[5]; // Declaration: creates space for 5 integers
This means:
array2[0] = 19
array2[1] = 17
array2[2] = 32
return 0;
}
return 0;
}
🧠 This program first takes input and then prints all elements.
🔹 How to Find Size of an Array in C?
Size of an array:
When the size of an array is not known to us, it can be calculated by using
the sizeof operator. sizeof gives the size in bytes.
In the above example, sizeof( array ) gives the total size of the array in bytes,
and sizeof( array [0]) gives the size of one element. The division of these two
values gives the total number of elements in the array.
🔹 Visual Diagram
1D Array: arr[5] = {5, 8, 2, 6, 9}
📘 2D Arrays
🔹 What is a 2D Array?
A 2D array (two-dimensional array) is like a table or matrix with rows and
columns.
Each element in a 2D array is accessed by two indices – one for row and
one for column.
🔹 Example of a 2D Matrix
Let's take a 3x3 matrix:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
🔹 Declaring a 2D Array
int array1[5][5];
1 2 3
4 5 6
7 8 9
array2[0][0] → 1
array2[2][1] → 8
array2[1][0] → 4
return 0;
}
printf("Enter 6 elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &arr[i][j]);
printf("Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
✅ This program:
Takes 6 values (2 rows × 3 columns) from the user
📊 Representation:
Row ↓ / Col → [0] [1] [2]
┌──┬──┬──┐
[0] │1 │2 │3 │
├──┼──┼──┤
[1] │4 │5 │6 │
├──┼──┼──┤
[2] │7 │8 │9 │
└──┴──┴──┘
Strings
There is a ‘ char ʼ data type in C which allows only one character to be
stored in a variable. The value assigned to the variable has to be inside
single quotes (ʼ ‘).
When a string is stored in a char array, the array ends with a null character.
To elaborate, the element at the last index of a char array is ‘\0ʼ, which is a
null character.
Each character takes 1 byte in memory, and the null character is crucial to
signal the end of the string.
This stores each character of the string on each index of the array.
🔹 Declaring Strings in C
There are two ways to declare strings:
👉 To print:
int s = sizeof(str) / sizeof(char);
for(int i = 0; i < s; i++) {
printf("%c", str[i]);
}
int size = 5;
char str[size];
2. Using scanf()
scanf("%s", str);
// ⚠️ Cannot read multi-word strings
3. Using fgets() ✅ (Recommended)
fgets() function requires three arguments -
first, the char array, where we are going to store the string input.
4. Using getchar()
char ch = getchar();
// Reads a single character
2. Using printf()
printf("%s", str);
3. Using puts()
puts(str);
// Adds a newline automatically
4. Using putchar()
putchar(str[i]);
// Prints one character at a time
Pointers
🔹 What is a Pointer?
A pointer is a special type of variable that stores the memory address of
another variable
of the
same data type.
if variable ‘ ptr ʼ stores the address of variable ‘ a ʼ , then variable ‘ ptr ʼ has
to be a pointer. It also means that variable ‘ ptr ʼ points(→) to the location
where variable ‘ a ʼ is located.
If pointer is of int data type, the address that it stores has to be of a variable
of int data type only. Same goes for pointers of other data types as well.
Meaning, pointer and the variable whose address it stores have to be of
same data type.
Using a pointer we can access the value of the variable that is being
pointed by that pointer.
✅ Example:
#include <stdio.h>
int main(){
int a = 5;
int *p = &a;
printf("Address of a: %p\n", p); // prints address
printf("Value of a: %d\n", *p); // prints 5
*p = 7;
🔹 Size of Pointer
Pointer size depends on the system architecture:
int *ptr;
printf("Size of pointer: %lu\n", sizeof(ptr));
🔹 Pointer to an Array
Pointers can be used to access and manipulate array elements efficiently.
We can easily move the pointer to point to each index of the array.
#include <stdio.h>
int main(){
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // or &arr[0]
🔹 Pointer to a String
#include <stdio.h>
int main(){
while(*ptr != '\0'){
printf("%c ", *ptr);
ptr++;
}
return 0;
}
✅ Example:
#include <stdio.h>
int main() {
int x = 10;
int *p = &x; // pointer to x
int **pp = &p; // pointer to pointer
Types of pointer:
There are various types of pointer in C. Some of them are listed below:
Null pointer : Null pointer does not store the address of any variable, hence
it does not point to any location. It holds the value Null.
Void pointer : Void pointer does not have a specific data type. It can store
the address of a variable of any data type.
📌 1. What is a Structure?
A Structure is a user-defined data type in C that allows grouping of different
types of data items under a single name.
🔹 Key Points:
Each element inside a structure is called a member.
The total size of the structure is the sum of the sizes of all members (may
include padding for alignment).
🔹 Useful for representing real-life entities like Person, Student, Employee, etc.
Think of a structure like a record or a form – just like a student form collects
, age (int) , and
name (string) percentage (float) together, a structure can combine these
in programming.
✅ Syntax of Structure
struct StructureName {
data_type member1;
data_type member2;
...
};
Example:
struct Student {
char name[50];
int rollNo;
float percentage;
};
int main() {
struct Student s1;
}
✅ Example:
struct Student s1;
strcpy(s1.name, "Amit");
s1.rollNo = 101;
s1.percentage = 85.5;
✅ Example:
struct Student s1 = {"Ravi", 102, 78.5};
struct Student *ptr = &s1;
🚀 5. Initializing a Structure
There are several ways to initialize a structure.
✅ Method 1: Member-wise
struct Student s1;
s1.rollNo = 103;
strcpy(s1.name, "Neha");
s1.percentage = 88.0;
✅ Syntax:
typedef struct {
int id;
char name[50];
} Employee;
Employee e1;
int main() {
struct Student s1 = {"Amit", 101};
display(s1);
}
✅ Example:
struct Student {
char name[50];
int rollNo;
};
int main() {
struct Student students[3];
struct Person {
char name[50];
int main() {
struct Person p1 = {"Ravi", {"Delhi", 110001}};
printf("Name: %s, City: %s", p1.name, p1.addr.city);
}
Union
🧊 1. What is a Union?
A Union is a user-defined data type where all members share the same
memory. So, only one member can contain a value at any time.
✅ Syntax of Union
union Data {
int i;
float f;
char str[20];
};
✅ Example:
union Data d;
d.i = 10;
printf("Integer: %d\n", d.i);
d.f = 5.5;
⚠️ Important: Only the last assigned member will have a valid value. Previous
ones get corrupted.
Allocates
Memory memory for all Allocates memory for the largest member only
members
Sum of all
Size Size of the largest member
members' sizes
🔹 Why is it needed?
When we declare an array using static memory allocation, the size is fixed
at compile time and cannot be changed later.
🔹Dynamic
Difference Between Static Memory Allocation and
Memory Allocation
Static Memory Dynamic Memory Allocation
Feature
Allocation (SMA) (DMA)
Memory Allocation
Compile Time Run Time
Time
Can be wasteful or
Memory Utilization More Efficient
insufficient
🔸 Example:
int arr[10]; // Static memory allocation
Suppose we later need to store only 7 elements; the extra 3 spaces remain
unused, wasting memory.
Function Purpose
void*
void* is a pointer that can hold the address of any data type (e.g., int, char,
float, etc.).
A pointer that can point to any type of data and needs to be cast to the
appropriate type before use.
🔸 Syntax:
ptr = (data_type*) malloc(size_in_bytes);
🔸 Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, n, i, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
🔸 Syntax:
ptr = (data_type*) calloc(num_elements, size_of_each_element);
🔸 Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, n, i, sum = 0;
if (ptr == NULL) {
printf("Memory allocation failed!");
exit(0);
}
🔸 Syntax:
ptr = (data_type*) realloc(ptr, new_size_in_bytes);
🔸 Example:
int main() {
int *ptr, n1, n2, i;
printf("Enter initial number of elements: ");
scanf("%d", &n1);
if (ptr == NULL) {
printf("Memory allocation failed!");
exit(0);
}
🔸 Syntax:
free(ptr);
ptr = NULL;
🔸 Example:
#include <stdlib.h>
int *ptr = (int*) malloc(5 * sizeof(int));
free(ptr); // Now memory is released
ptr = NULL; // Avoid dangling pointer
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 4;
return 0;
}
Explanation:
1. Allocate row pointers:
int **arr = malloc(rows * sizeof(int *));
3. Accessing Elements:
The elements can be accessed using arr[i][j] (like a regular 2D array).
4. Freeing Memory:
It's important to free each row first, and then free the array of pointers.
📁 File Handling
File handling is an essential concept in C programming that allows a program to
store data permanently and interact with files stored on the disk. Unlike
variables (which lose their data once the program ends), file handling ensures
data is saved and can be retrieved later.
🗂️ 1. What is a File?
A file is a collection of related data stored on a storage device. It is used to
save data permanently for later use.
📌 Types of Files:
Text Files: Human-readable format (e.g., .txt , .csv )
Closing files: Releasing system resources tied to the file after operations.
📂 3. File Modes in C
C uses file modes to define the purpose of opening a file (read/write/append).
Use FILE *fopen(const char *filename, const char *mode);
If File Doesn't
Mode Operation If File Exists
Exist
"r" Read-only Opens the file Returns NULL
✳️ Writing to a File
✳️ Closing a File
fclose(file); // Always close the file after us
✅ Explanation:
"w" mode creates a new file or overwrites an existing file.
✅ Explanation:
"r" mode opens an existing file for reading only.
✅ Explanation:
"a" mode opens the file for writing at the end (append).
✳️ 4. Writing to a File
fprintf(file, "Hello, World!\n"); // Write a formatted string
fputc('A', file); // Write a single character
fputs("C programming", file); // Write a string
✅ Explanation:
fprintf() is like printf() , but outputs to a file.
✅ Explanation:
fscanf() is like scanf() , reads formatted data.
✅ Explanation:
Appends data at the end of the file without erasing existing content.
✳️ 7. Closing a File
fclose(file);
✅ Explanation:
Always close files after operations to save changes and free resources.
✍️ Example Program:
#include <stdio.h>
int main() {
FILE *file;
char str[100];
char ch;
return 0;
}
📌 Explanation:
w+ mode allows reading & writing, and clears the file if it exists.
Parameters :
pointer : It is the pointer that points to the FILE that we need to modify.
offset : It is the number of characters or bytes, where the position of the file
pointer needs to be shifted relative to the current position to determine the
new position.
position : It is the position from where the offset is added. Position defines
the point with respect to which the file pointer needs to be moved. It has
three values:
Return value :
It returns zero if successful, or else it returns a non-zero value.
int main() {
FILE *fp = fopen("file.txt", "w+");
if (fp == NULL) {
printf("File not found!\n");
exit(1);
}
fprintf(fp, "abcdefghijk");
fclose(fp);
return 0;
}
📌 ftell() returns the current position of the file pointer (in bytes).
📌 fseek() is useful for random access (like moving to a specific record in a
binary file).