0% found this document useful (0 votes)
2 views

UNIT-4 (FOP)

Unit IV covers derived data types in programming, focusing on arrays, including their declaration, initialization, and types such as one-dimensional and two-dimensional arrays. It also discusses searching algorithms like linear and binary search, string manipulation functions, and the concept of pointers in C programming. The unit emphasizes the importance of arrays and pointers for efficient data storage and manipulation in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT-4 (FOP)

Unit IV covers derived data types in programming, focusing on arrays, including their declaration, initialization, and types such as one-dimensional and two-dimensional arrays. It also discusses searching algorithms like linear and binary search, string manipulation functions, and the concept of pointers in C programming. The unit emphasizes the importance of arrays and pointers for efficient data storage and manipulation in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Fundamentals of Programming and Problem Solving

UNIT IV

UNIT – 4 DERIVED DATA TYPES

Introduction to Arrays: Declaration, Initialization -One dimensional array -


Two dimensional arrays -Searching- linear and binary search. -String
manipulation- length, compare, concatenate, and copy - Pointers -Pointer
arithmetic -Arrays and pointers - Array of pointers.

INTRODUCTION TO ARRAYS:
Array in C is one of the most used data structures in C programming. It is a simple
and fast way of storing multiple values under a single name.
Array definition:
An array is a data structure with a fixed-size, ordered collection of elements, all of
the same data type. Each element within an array is identified by a unique index,
typically starting from 0. Arrays are widely used in programming for storing,
accessing, and manipulating data efficiently.

Array Declaration
In C, we have to declare the array like any other variable before using it. We can
declare an array by specifying its name, the type of its elements, and the size of its
dimensions. When we declare an array in C, the compiler allocates the memory
block of the specified size to the array name.
Fundamentals of Programming and Problem Solving
UNIT IV

syntax
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];

Example:
#include <stdio.h>
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
Array Initialization
Initialization in C is the process of assigning some initial value to the variable.
When the array is declared or allocated memory, the elements of the array contain
some garbage value. So, we need to initialize the array to some meaningful value.
There are multiple ways in which we can initialize an array in C.
1. Array Initialization with declaration:
In this method, we initialize the array along with its declaration. We use an
initializer list to initialize multiple elements of the array. An initializer list is
the list of values enclosed within braces { } separated by a comma.
Syntax
data_type array_name [size] = {value1, value2, ... valueN};
Fundamentals of Programming and Problem Solving
UNIT IV

2. Array Initialization with declaration without size:


If we initialize an array using an initializer list, we can skip declaring
the size of the array as the compiler can automatically deduce the size of the
array in these cases. The size of the array in these cases is equal to the
number of elements present in the initializer list as the compiler can
automatically deduce the size of the array.
Syntax
data_type array_name[] = {1,2,3,4,5};

3. Array Initialization after declaration (using loops).


We initialize the array after the declaration by assigning the initial value to
each element individually. We can use for loop, while loop, or do-while loop
to assign the value to each element of the array.
Syntax
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example
#include <stdio.h>
int main()
{
// array initialization using an initializer list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}
Fundamentals of Programming and Problem Solving
UNIT IV

Types of Array in C
 One Dimensional Arrays (1D Array)
 Multidimensional Arrays

1. One Dimensional Array in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that
have only one dimension.
Syntax
array_name [size];

Example:
#include <stdio.h>
int main()
{
// 1d array declaration
int arr[5];
// 1d array initialization using for loop
for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}
printf("Elements of Array: ");
// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Output:
Elements of Array: 1 0 1 4 9
Fundamentals of Programming and Problem Solving
UNIT IV

2. Multidimensional Arrays
A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions. They can be visualized in the form of rows and columns organized in
a two-dimensional plane.
Syntax
array_name[size1] [size2];
Here,
size1: Size of the first dimension.
size2: Size of the second dimension.
Example:
#include <stdio.h>
int main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}

Searching
Searching is the fundamental process of locating a specific element or item
within a collection of data. This collection of data can take various forms, such as
arrays, lists, trees, or other structured representations. The primary objective of
searching is to determine whether the desired element exists within the data, and if
so, to identify its precise location or retrieve it. It plays an important role in various
computational tasks and real-world applications, including information retrieval,
data analysis, decision-making processes, and more.
Fundamentals of Programming and Problem Solving
UNIT IV

Applications:
 Information Retrieval.
 Database Systems.
 E-commerce.
 Networking.
 Artificial Intelligence.
 Pattern Recognition.

Linear searching
Linear search is a method for searching for an element in a collection of elements.
In linear search, each element of the collection is sequentially visited one by one to
find the desired element. Linear search is also known as sequential search.
Algorithm:
1. Start: Begin at the first element of the collection of elements.
2. Compare: Compare the current element with the desired element.
3. Found: If the current element is equal to the desired element, return true or
index to the current element.
4. Move: Otherwise, move to the next element in the collection.
5. Repeat: Repeat steps 2-4 until we have reached the end of collection.
6. Not found: If the end of the collection is reached without finding the desired
element, return that the desired element is not in the array.
Example:
#include <stdio.h>
{
int main() {
int arr[] = {5, 3, 8, 4, 2}; // Example array
int target, found = -1; // Variable to store target and result
int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of the array

// Prompt user for input


printf("Enter the number to search: ");
scanf("%d", &target);

// Perform linear search


for (int index = 0; index < size; index++) {
Fundamentals of Programming and Problem Solving
UNIT IV

if (arr[index] == target) {
found = index; // Store index if found
break; // Exit loop once found
}
}
// Output result
if (found != -1) {
printf("Element found at index %d.\n", found);
} else {
printf("Element not found.\n");
} return 0;
}
Applications:
 Unsorted Lists.
 Small Data Sets.
 Searching Linked Lists.
 Simple Implementation.
Advantages
 Linear search can be used irrespective of whether the array is sorted or not.
It can be used on arrays of any data type.
 Does not require any additional memory.
 It is a well-suited algorithm for small datasets.
Disadvantage
 Linear search has a time complexity of O(N), which in turn makes it slow
for large datasets.
 Not suitable for large arrays.

Binary Searching:
Fundamentals of Programming and Problem Solving
UNIT IV

Binary search is a search algorithm used to find the position of a target value
within a sorted array. It works by repeatedly dividing the search interval in half
until the target value is found or the interval is empty. The search interval is halved
by comparing the target element with the middle value of the search space.
Algorithm
1. Compare key with the middle element of the array.
2. If key matches with the middle element, we return the index of the middle
element.
3. Else if key is greater than the middle element, it means that key can only lie
in the right half subarray after the middle element. So we repeat steps 1 to 4
for the right half subarray and leave the left half subarray.
4. Else if key is smaller than the middle element, it means that target can only
lie in the left half subarray before the middle element. So, we repeat steps 1
to 4 for the left half subarray.
5. We will keep doing that till we find key or there is no element left in the
subarray being considered.
Example:
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int size, int target) {
int left = 0; // Starting index
int right = size - 1; // Ending index
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate middle index

if (arr[mid] == target) {
return mid; // Target found
}

if (arr[mid] < target) {


left = mid + 1; // Ignore left half
} else {
right = mid - 1; // Ignore right half
}
}
Fundamentals of Programming and Problem Solving
UNIT IV

return -1; // Target not found


}

int main() {
int arr[] = {2, 3, 4, 5, 8}; // Sorted array
int target; // Variable to store the target value
int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of the array

// Prompt user for input


printf("Enter the number to search: ");
scanf("%d", &target);

// Perform binary search


int result = binarySearch(arr, size, target);

// Output result
if (result != -1) {
printf("Element found at index %d.\n", result);
} else {
printf("Element not found.\n");
}
return 0;
}
Applications
 Binary search can be used as a building block for more complex algorithms
used in machine learning, such as algorithms for training neural networks or
finding the optimal hyper parameters for a model.
 It can be used for searching in computer graphics such as algorithms for ray
tracing or texture mapping.
 It can be used for searching a database.
Advantages
 Binary search is faster than linear search, especially for large arrays.
 More efficient than other searching algorithms with a similar time
complexity, such as interpolation search or exponential search.
Fundamentals of Programming and Problem Solving
UNIT IV

 Binary search is well-suited for searching large datasets that are stored in
external memory, such as on a hard drive or in the cloud.
Disadvantages
 The array should be sorted.
 Binary search requires that the data structure being searched be stored in
contiguous memory locations.
 Binary search requires that the elements of the array be comparable,
meaning that they must be able to be ordered.

String manipulation
 String length
The strlen() function returns the length of a string, which is the
number of characters up to the first null terminating character. This is
smaller than the amount of memory that is reserved for the string, which can
be measured using the size of the operator instead.

Syntax
strlen(char * str);

Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length: %lu\n", strlen(str));
return 0;
}
 String Compare
C strcmp() is a built-in library function that is used for string
comparison. This function takes two strings (array of characters) as
arguments, compares these two strings lexicographically, and then returns
0,1, or -1 as the result.
Syntax
strcmp(first_str, second_str );
Fundamentals of Programming and Problem Solving
UNIT IV

Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2);
if (result < 0) {
printf("%s is less than %s\n", str1, str2);
} else if (result > 0) {
printf("%s is greater than %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
return 0;
}
 String concatenate
In C, strcat() function appends the copy of the given source string to another
destination string with a NULL character at the end. It is defined inside
<string.h> header file in C. It means that the source string characters will be
copied to the end of the destination string.

Syntax
char *strcat(char *dest, const char *src);

Example:
#include <stdio.h>
#include <string.h>
int main() {
// Declare and initialize the strings
char str1[50] = "Hello"; // Ensure str1 has enough space for the
concatenated result
char str2[] = " World";

// Concatenate str2 onto str1


Fundamentals of Programming and Problem Solving
UNIT IV

strcat(str1, str2);

// Print the result


printf("%s\n", str1); // Output: Hello World

return 0;
}

 String Copy
The C strcpy() function copies the content of a string to another. The
content of the destination string will be replaced with that of the source
string by the strcpy() function. It is defined inside <string.h> header file.

Syntax
char* strcpy(char* destination, const char* source);

Example:
#include <stdio.h>
#include <string.h>
int main() {
// Declare and initialize the source string
char source[] = "Hello, World!";

// Declare a destination string with enough space


char destination[50];
// Copy the source string to the destination
strcpy(destination, source);
// Print the result
printf("Source: %s\n", source); // Output: Hello, World!
printf("Destination: %s\n", destination); // Output: Hello, World!
return 0;
}
Pointer
Pointers are one of the core components of the C programming language. A
pointer can be used to store the memory address of other variables, functions, or
Fundamentals of Programming and Problem Solving
UNIT IV

even other pointers. The use of pointers allows low-level memory access, dynamic
memory allocation, and many other functionalities in C.

Syntax
datatype * ptr;

Pointer steps:
 Pointer Declaration
 Pointer Initialization
 Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example:
int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the ( &: ampersand ) address of the operator to
get the memory address of a variable and then store it in the pointer variable.
Example:
int var = 10;
int * ptr;
ptr = &var;
3.Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the
memory address specified in the pointer.

Types of pointer
1. Integer Pointers
2. Array Pointer
3. Structure Pointer
Fundamentals of Programming and Problem Solving
UNIT IV

4. Function Pointers
5. Double Pointers
6. NULL Pointer
7. Void Pointer
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer
values.
Syntax
int *ptr;
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is
the pointer to its first element. They are also known as Pointer to Arrays. We can
create a pointer to an array using the given syntax.
Syntax
char *ptr = &array_name;

3. Structure Pointer
The pointer pointing to the structure type is called a Structure Pointer or
Pointer to Structure. It can be declared in the same way as we declare the other
primitive data types.
Syntax
struct struct_name *ptr;

4. Function Pointers
Function pointers point to the functions. They are different from the rest of
the pointers in the sense that instead of pointing to the data, they point to the code.
Syntax
int (*ptr)(int, char);

5. Double Pointers
In C language, we can define a pointer that stores the memory address of
another pointer. Such pointers are called double-pointers or pointers-to-pointer.
Instead of pointing to a data value, they point to another pointer.
Fundamentals of Programming and Problem Solving
UNIT IV

Syntax
datatype ** pointer_name;

6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory
location. They can be created by assigning a NULL value to the pointer. A pointer
of any type can be assigned the NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL

7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do
not have any associated data type. They are also called generic pointers as they can
point to any type and can be type cast to any type.
Syntax
void * pointer_name;

Pointer Arithmetic
Pointer Arithmetic is the set of valid arithmetic operations that can be
performed on pointers. The pointer variables store the memory address of another
variable. It doesn’t store any value.
These operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers

1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer
is incremented, it increments by the number equal to the size of the data type for
which it is a pointer.
Fundamentals of Programming and Problem Solving
UNIT IV

Decrement: It is a condition that also comes under subtraction. When a


pointer is decremented, it decrements by the number equal to the size of the data
type for which it is a pointer.

2. Addition of integer to a pointer


When a pointer is added with an integer value, the value is first multiplied
by the size of the data type and then added to the pointer.
Subtraction of integer to a pointer
When a pointer is subtracted with an integer value, the value is first
multiplied by the size of the data type and then subtracted from the pointer similar
to addition.

3. Subtracting two pointers of the same type


The subtraction of two pointers is possible only when they have the same
data type. The result is generated by calculating the difference between the
addresses of the two pointers and calculating how many bits of data it is according
to the pointer data type. The subtraction of two pointers gives the increments
between the two pointers.
4. Comparison of pointers
We can compare the two pointers by using the comparison operators in C.
We can implement this by using all operators in C >, >=, <, <=, ==, !=. It returns
true for the valid condition and returns false for the unsatisfied condition.
Step 1: Initialize the integer values and point these integer values to the pointer.
Step 2: Now, check the condition by using comparison or relational operators on
pointer variables.
Step 3: Display the output.

Arrays and Pointers


#include <stdio.h>
Fundamentals of Programming and Problem Solving
UNIT IV

// Function to print the array using pointers


void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i)); // Accessing elements using pointer arithmetic
}
printf("\n");
}

// Function to modify the array using pointers


void modifyArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
*(arr + i) += 5; // Increment each element by 5
}
}

int main() {
// Declare and initialize an array
int arr[5] = {1, 2, 3, 4, 5};

// Print the original array


printf("Original array: ");
printArray(arr, 5);

// Modify the array


modifyArray(arr, 5);

// Print the modified array


printf("Modified array: ");
printArray(arr, 5);

// Demonstrating pointer usage


int *ptr = arr; // Pointer to the first element of the array
printf("Accessing array elements using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i)); // Access elements using pointer
Fundamentals of Programming and Problem Solving
UNIT IV

return 0;
}

Output:
Original array: 1 2 3 4 5
Modified array: 6 7 8 9 10
Accessing array elements using pointer:
Element 0: 6
Element 1: 7
Element 2: 8
Element 3: 9
Element 4: 10

Array of Pointers.
#include <stdio.h>
int main() {
// Step 1: Declare and initialize an array of string literals
const char *strArray[] = {
"Hello, World!",
"C Programming",
"Array of Pointers",
"Example Program"
};

// Step 2: Determine the number of strings


int numStrings = sizeof(strArray) / sizeof(strArray[0]);

// Step 3: Print the strings using the array of pointers


printf("Printing strings from the array of pointers:\n");
for (int i = 0; i < numStrings; i++) {
printf("String %d: %s\n", i + 1, strArray[i]);
}
Fundamentals of Programming and Problem Solving
UNIT IV

// Step 4: Modifying strings (not directly possible with string literals)


// If we had dynamic memory or arrays, we could modify the content.

return 0;
}
Output:
Printing strings from the array of pointers:
String 1: Hello, World!
String 2: C Programming
String 3: Array of Pointers
String 4: Example Program
Fundamentals of Programming and Problem Solving
UNIT IV

You might also like