Ip 345 Units
Ip 345 Units
1. Array Indexing in C
In C, an array is a collection of elements of the same data type stored in contiguous memory
locations. Each element of an array can be accessed using an index, and the indexing starts
from 0.
Example:
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50};
// Accessing array elements
printf("Element at index 0: %d\n", arr[0]); // Output: 10
printf("Element at index 1: %d\n", arr[1]); // Output: 20
printf("Element at index 2: %d\n", arr[2]); // Output: 30
printf("Element at index 3: %d\n", arr[3]); // Output: 40
printf("Element at index 4: %d\n", arr[4]); // Output: 50
return 0;
}
Here, arr[0] refers to the first element of the array, arr[1] to the second, and so
on.
Arrays in C are stored in contiguous memory locations, meaning that the memory addresses
for each element are next to each other. When you declare an array, say int arr[5], the C
compiler allocates 5 contiguous memory locations to store the integers.
The memory of an array is contiguous, and each element occupies the same amount of
memory as the data type.
The base address of an array is the address of the first element (arr[0]).
For example, if the base address of arr[0] is 0x1000, the addresses for the other elements will
be:
1
3. Programs with Arrays of Integers
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Array initialization
return 0;
}
In this program:
4. Two-Dimensional Arrays in C
Example:
#include <stdio.h>
int main() {
// Declaration of a 2D array (3 rows, 4 columns)
int arr[3][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
// Accessing elements using two indices
printf("Element at arr[0][0]: %d\n", arr[0][0]); // Output: 1
printf("Element at arr[1][2]: %d\n", arr[1][2]); // Output: 7
return 0;
}
2
In this example:
Introduction to Strings in C
In C, strings are arrays of characters. A string is terminated with a special character '\0' (null
character) to mark the end of the string.
For example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!"; // String initialization
return 0;
}
In this case, "Hello, World!" is an array of characters: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o',
'r', 'l', 'd', '!', '\0'].
The printf function with the %s format specifier prints the entire string, stopping when
it encounters the '\0'.
6. Operations on Strings in C
C provides several standard library functions to perform common operations on strings, such
as concatenation, copying, and finding the length of a string. These functions are defined in
the header file <string.h>.
String Length: strlen() returns the length of a string (not counting the null character).
#include <string.h>
int len = strlen(str); // Returns the length of str
int result = strcmp(str1, str2); // Returns 0 if str1 and str2 are equal
3
7. Example Program Using Strings
#include <stdio.h>
#include <string.h> // Required for string functions
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
// Copying strings
char str3[50];
strcpy(str3, str1);
printf("After copying: %s\n", str3); // Output: Hello World!
// Comparing strings
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal.\n");
} else {
printf("str1 and str3 are not equal.\n");
}
return 0;
}
4
UNIT IV Pointers & User Defined Data types: Pointers, dereferencing and address
operators, pointer and address arithmetic, array manipulation using pointers, User-
defined data types-Structures and Unions.
In C, pointers are variables that store memory addresses. They are one of the most powerful
and complex features of C, allowing for direct memory manipulation. Alongside pointers,
user-defined data types like structures and unions allow us to define complex data types to
suit our needs.
1. Pointers in C
a. What is a Pointer?
A pointer is a variable that stores the memory address of another variable. Pointers can point
to variables of any data type, such as integers, floats, characters, etc.
In this example:
Dereferencing a pointer means accessing the value stored at the address the pointer is
pointing to. This is done using the * operator.
int x = 10;
int *p = &x; // p stores the address of x
printf("%d\n", *p); // Dereferencing p to get the value of x, Output: 10
The & operator is used to get the memory address of a variable. For example:
int x = 5;
printf("Address of x: %p\n", &x); // Prints the address of x
5
d. Pointer Arithmetic
Incrementing a pointer (p++): Moves the pointer to the next memory location of the
same type.
Decrementing a pointer (p--): Moves the pointer to the previous memory location of
the same type.
Example:
In C, arrays and pointers are closely related. An array name is a pointer to the first element of
the array.
Example:
In C programming, arrays and pointers are closely related. An array can be thought of as a
pointer to the first element of the array. This is important because it means that arrays can be
manipulated using pointers and vice versa.
The key point is that the name of an array is essentially a pointer to the first element of the
array.
6
2. Array Name as a Pointer
When you declare an array in C, the name of the array behaves like a pointer to its first
element. For example:
In this case, arr is a pointer to the first element of the array. You can access the elements of
the array using both the array indexing notation and pointer arithmetic.
Since arr is a pointer to the first element, arr + i gives the address of the i-th element, and
*(arr + i) dereferences that address to get the value stored there.
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
return 0;
}
Explanation:
Pointer arithmetic allows you to traverse the array using a pointer, and it can be used to
iterate over the elements of an array.
7
Example: Iterating Over an Array Using Pointers
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
return 0;
}
6. Pointer to an Array
You can also declare a pointer to an entire array, though this is less common than the
approach where the pointer points to the first element of the array.
When you pass an array to a function, you are actually passing the address of the first element
of the array (the pointer). This means the function can modify the original array.
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Before modification:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
8
modifyArray(arr, 5); // Pass array as pointer
printf("After modification:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation:
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
return 0;
}
Explanation:
arr is a 2D array.
*(arr + 0) gives the address of the first row, and *(arr + 1) gives the address of the
second row.
*(*(arr + i) + j) accesses the element at row i and column j.
In C, dynamic memory allocation allows you to allocate memory during runtime (i.e., when
the program is running), as opposed to statically allocated memory which is fixed at compile
time. This is useful when the size of data structures like arrays is not known at compile time.
The functions used for dynamic memory allocation in C are provided by the standard library
<stdlib.h>. These functions are:
9
malloc(): Allocates a block of memory of the specified size. It does not initialize the
memory.
calloc(): Allocates memory for an array of elements and initializes the memory to
zero.
realloc(): Changes the size of an already allocated memory block. It can be used to
increase or decrease the size.
free(): Deallocates previously allocated memory, releasing it back to the system.
The malloc() function is used to allocate a block of memory of a specified size. It returns a
pointer to the allocated memory, or NULL if the memory allocation fails.
Syntax:
void *malloc(size_t size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}
10
Explanation:
The calloc() function is similar to malloc(), but it initializes the allocated memory to zero.
Syntax:
void *calloc(size_t num, size_t size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}
return 0;
}
Explanation:
calloc(5, sizeof(int)) allocates memory for 5 integers and sets all of them to zero.
It’s particularly useful when you want to ensure that the memory is initialized to zero.
11
3. realloc() (Reallocation)
The realloc() function is used to resize a previously allocated block of memory. It can either
expand or shrink the size of the memory block. If the new memory block is larger, it may
move the block to a different location.
Syntax:
void *realloc(void *ptr, size_t size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}
if (ptr == NULL) {
printf("Reallocation failed\n");
return 1; // Return an error code
}
12
// Assign values to the newly allocated space
for (int i = 3; i < 5; i++) {
ptr[i] = (i + 1) * 10;
}
return 0;
}
Explanation:
The free() function is used to deallocate memory that was previously allocated using
malloc(), calloc(), or realloc(). After calling free(), the pointer becomes dangling and should
not be used again unless it’s reassigned.
Syntax:
void free(void *ptr);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
13
ptr[i] = i * 10;
}
return 0;
}
Explanation:
After using the memory, we call free(ptr) to release the allocated memory.
Important: After calling free(), the pointer ptr becomes invalid. You should not
dereference it, and ideally, set it to NULL to prevent accidental use.
a. Structures
A structure in C is a user-defined data type that allows grouping variables of different types
under a single name.
Example of a structure:
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person p1 = {"John", 30}; // Initializing a structure
return 0;
}
struct Person is a structure that holds a name (array of characters) and an age
(integer).
We can access the structure members using the dot . operator (p1.name, p1.age).
14
Pointer to Structure
We can use pointers with structures to dynamically access and modify their members.
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person p1 = {"Alice", 25};
struct Person *p2 = &p1; // p2 is a pointer to the structure p1
// Accessing structure members using a pointer and the arrow (->) operator
printf("Name: %s\n", p2->name); // Output: Alice
printf("Age: %d\n", p2->age); // Output: 25
return 0;
}
b. Unions
A union is similar to a structure, but all members of a union share the same memory location.
This means a union can store one of its members at a time, and the memory used by the union
is equal to the size of its largest member.
Example of a union:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
// Storing an integer
data.i = 10;
printf("data.i: %d\n", data.i); // Output: 10
// Storing a float
data.f = 3.14;
printf("data.f: %.2f\n", data.f); // Output: 3.14
15
// Storing a string
strcpy(data.str, "Hello, world!");
printf("data.str: %s\n", data.str); // Output: Hello, world!
return 0;
}
Key point: A union can hold only one of its members at a time, and the last stored
member will overwrite any previously stored members.
Structure: Each member has its own memory, so the size of the structure is the sum of
the sizes of all its members.
Union: All members share the same memory, so the size of the union is the size of the
largest member.
struct Person {
int age;
char name[50];
};
union Data {
int i;
float f;
char str[20];
};
int main() {
printf("Size of struct Person: %lu\n", sizeof(struct Person)); // Size depends on the
members
printf("Size of union Data: %lu\n", sizeof(union Data)); // Size equals the size of the
largest member
return 0;
}
The sizeof operator is used to determine the memory size of the structure or union.
16
UNIT V Functions & File Handling
Introduction to Functions, Function Declaration and Definition, Function call Return
Types and Arguments, modifying parameters inside functions using pointers, arrays as
parameters. Scope and Lifetime of Variables, Basics of File Handling
Functions in C allow you to break down a program into smaller, manageable parts, making
the code more modular and easier to maintain. Functions can be used to perform specific
tasks, which can be reused throughout the program. In addition, file handling in C allows for
reading from and writing to files, providing a way to store data persistently.
1. Introduction to Functions in C
A function is a block of code that performs a specific task. It can take input in the form of
parameters and return a result. Functions help make programs more organized and easier to
debug.
Function Declaration (also called function prototype) informs the compiler about the
function's name, return type, and parameters before its actual use.
Function Definition provides the actual implementation of the function.
Example:
#include <stdio.h>
// Function Declaration
int add(int, int);
int main() {
int result = add(5, 3); // Function Call
printf("Sum: %d\n", result);
return 0;
}
// Function Definition
int add(int a, int b) {
return a + b;
}
17
In this example:
The function add() is declared with the prototype int add(int, int);.
It is then defined below with the actual logic return a + b;.
Finally, in the main() function, it is called with arguments 5 and 3.
Function Call: A function is called by passing arguments that match the function's
parameters.
Return Type: The function can return a value of a specific type (e.g., int, float, void).
Arguments: Functions can take parameters (also called arguments), which are used
within the function.
int main() {
float result = multiply(4.5, 2.0); // Function call
printf("Multiplication result: %.2f\n", result);
return 0;
}
In this example:
In C, parameters are passed by value by default, meaning that the function receives a copy of
the value, and changes made inside the function do not affect the original variable. To modify
the original variable, we use pointers.
int main() {
int num = 5;
modifyValue(&num); // Passing the address of num
printf("Modified value: %d\n", num); // Output: 100
return 0;
}
18
In this example:
The modifyValue() function takes a pointer to an int and modifies the value at that
address.
The address of num is passed to the function using the & operator.
Arrays can be passed to functions either by passing the entire array or by passing a pointer to
the array. When an array is passed, the function receives the base address of the array.
include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array and its size
return 0;
}
In this example:
The function printArray() takes an array (int arr[]) and its size (int size).
The array is passed by reference (the base address is passed).
a. Scope:
The scope of a variable determines where it can be accessed (i.e., which functions or
blocks of code it can be used in).
o Local variables: Defined inside a function or block and can only be used
within that function/block.
o Global variables: Defined outside of any function and can be accessed
anywhere in the program.
b. Lifetime:
19
Example:
#include <stdio.h>
void function() {
int localVar = 5; // Local variable
printf("Local variable: %d\n", localVar);
printf("Global variable: %d\n", globalVar);
}
int main() {
function();
printf("Global variable in main: %d\n", globalVar);
return 0;
}
In this example:
globalVar is a global variable and can be accessed in both function() and main().
localVar is local to function() and cannot be accessed outside it.
File handling in C allows you to read from and write to files, which is essential for persistent
data storage. The C standard library provides functions to handle file operations.
a. File Operations in C:
b. Opening a File
FILE *fptr;
fptr = fopen("example.txt", "w"); // "w" mode for writing
if (fptr == NULL) {
printf("Error opening file.\n");
return 1;
}
20
c. Reading from and Writing to Files
#include <stdio.h>
int main() {
FILE *fptr;
char str[] = "Hello, world!";
// Writing to a file
fptr = fopen("example.txt", "w");
if (fptr == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
fprintf(fptr, "%s\n", str);
fclose(fptr);
return 0;
}
d. Closing a File
It is important to always close a file after you are done with it using fclose() to free the
resources associated with the file.
21