0% found this document useful (0 votes)
2 views12 pages

Unit 2

The document provides a comprehensive overview of arrays and strings in C, detailing their declaration, initialization, types, and operations. It covers one-dimensional and two-dimensional arrays, string manipulation functions, sorting algorithms, and searching techniques. Additionally, it includes example programs for better understanding of these concepts.

Uploaded by

pramilar.aiml
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 views12 pages

Unit 2

The document provides a comprehensive overview of arrays and strings in C, detailing their declaration, initialization, types, and operations. It covers one-dimensional and two-dimensional arrays, string manipulation functions, sorting algorithms, and searching techniques. Additionally, it includes example programs for better understanding of these concepts.

Uploaded by

pramilar.aiml
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

Arrays in C

An array in C is a collection of variables of the same data type that are stored in contiguous
memory locations. Each element of an array can be accessed using an index.

Initialization and Declaration of Arrays in C

1. Declaration:

It defines the array’s name, type, and size. It doesn't initialize the array with any values.

 Syntax:

datatype array_name[size];

o Example:

int arr[5]; // Declares an integer array of size 5

2. Initialization:

It assigns values to the elements of the array at the time of declaration.

 Syntax:

datatype array_name[size] = {value1, value2, ..., valueN};

o Example:

int arr[5] = {1, 2, 3, 4, 5}; // Initializes array with 5


values

o Partial Initialization: If fewer values are provided than the size, the
remaining elements are initialized to 0.

int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}

o No Initialization: If no initial values are provided, C will not automatically


initialize array elements in local arrays (they will have garbage values).
However, for static arrays, the elements are initialized to zero.

int arr[5]; // Values are uninitialized (garbage values for


local arrays)

Types of Arrays in C

1. One Dimensional Array (1D)

A one-dimensional array is a list of elements that can be accessed by a single index. It


represents a linear collection of elements.
 Declaration and Initialization:

int arr[5]; // Declaration of a 1D array of size 5


int arr[5] = {1, 2, 3, 4, 5}; // Initialization

 Accessing Elements: Elements in a 1D array are accessed using an index starting


from 0.

printf("%d", arr[2]); // Accesses the 3rd element (3)

 Example of Iteration:

for (int i = 0; i < 5; i++) {


printf("%d ", arr[i]);
}

2. Two Dimensional Array (2D)

A two-dimensional array is an array of arrays, where each element is itself an array. It is


often used to represent matrices or tables.

 Declaration and Initialization:

int arr[3][4]; // Declares a 2D array with 3 rows and 4 columns


int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; //
Initialization

 Accessing Elements: A 2D array is accessed using two indices: one for the row and
one for the column.

printf("%d", arr[1][2]); // Accesses the element in the 2nd row, 3rd


column (7)

 Example of Iteration: You can use nested loops to iterate over a 2D array:

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 4; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

Memory Representation

In C, arrays are stored in contiguous memory locations, meaning the memory addresses of the
elements in an array are consecutive. This enables efficient access to array elements using the
index.

Memory Layout Example for a 1D Array

Consider the array int arr[3] = {10, 20, 30};:


Memory Address: 1000 1004 1008
Values: 10 20 30

 arr[0] is stored at address 1000, arr[1] at 1004, and so on.

Memory Layout Example for a 2D Array

For int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};:

Memory Address: 1000 1004 1008 1012 1016 1020


Values: 1 2 3 4 5 6

 arr[0][0] is stored at 1000, arr[0][1] at 1004, and so on.

Summary of Array Types

Type Description Example


One Dimensional A linear array with a single int arr[5] = {1, 2, 3, 4, 5};
Array index.
Two Dimensional An array of arrays, usually for int arr[3][4] = {{1, 2, 3, 4}, {5,
Array matrix or table data. 6, 7, 8}, {9, 10, 11, 12}};

Differences Between 1D and 2D Arrays

Aspect One-Dimensional Array Two-Dimensional Array


Structure Single row of elements. Array of rows, each row is an array.
Access Accessed using one index. Accessed using two indices (row, column).
Use Case For storing lists or sequences. For storing tables, matrices, grids, etc.

Strings in C

In C, a string is an array of characters terminated by a special character called the null character ('\
0'). It is used to represent textual data.

1. Declaration and Initialization of Strings:

 Declaration: A string can be declared as an array of characters.

char str[20]; // Declares a string of size 20 characters

 Initialization: A string can be initialized by assigning a string literal, which includes the null
character '\0' automatically.

char str[] = "Hello"; // "Hello" is stored as {'H', 'e', 'l', 'l',


'o', '\0'}

 String with a Specified Size:

char str[10] = "Hello"; // Allocates space for 10 characters (with


the rest being '\0')
2. String Operations in C

There are several standard functions provided by the C library to perform operations on strings,
which are declared in the string.h header file. These include functions to copy, concatenate,
compare, and manipulate strings.

1. String Length (strlen):

Returns the length of a string (excluding the null character '\0').

 Syntax:

size_t strlen(const char *str);

 Example:

char str[] = "Hello";


printf("Length: %zu", strlen(str)); // Output: Length: 5
2. String Copy (strcpy):

Copies the content of one string into another.

 Syntax:

char* strcpy(char *dest, const char *src);

 Example:

char src[] = "Hello";


char dest[20];
strcpy(dest, src); // Copies "Hello" into dest
printf("Copied String: %s", dest); // Output: Copied String: Hello
3. String Concatenation (strcat):

Appends the content of one string to the end of another.

 Syntax:

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

 Example:

char str1[20] = "Hello ";


char str2[] = "World";
strcat(str1, str2); // Concatenates "World" to "Hello "
printf("Concatenated String: %s", str1); // Output: Concatenated
String: Hello World
4. String Comparison (strcmp):

Compares two strings lexicographically.

 Syntax:
int strcmp(const char *str1, const char *str2);

 Example:

char str1[] = "Apple";


char str2[] = "Banana";
int result = strcmp(str1, str2); // Compares "Apple" and "Banana"
printf("Comparison Result: %d", result); // Output: Negative value
because "Apple" < "Banana"
5. String Search (strchr):

Searches for a character in a string.

 Syntax:

char* strchr(const char *str, int c);

 Example:

char str[] = "Hello World";


char *ptr = strchr(str, 'o'); // Finds the first occurrence of 'o'
printf("Found: %s", ptr); // Output: Found: o World
6. String Tokenization (strtok):

Splits a string into tokens based on delimiters.

 Syntax:

char* strtok(char *str, const char *delim);

 Example:

char str[] = "Hello World C Programming";


char *token = strtok(str, " "); // Tokenizes the string by spaces
while (token != NULL) {
printf("%s\n", token); // Prints each word separately
token = strtok(NULL, " ");
}

3. String Arrays

An array of strings is essentially an array where each element is a string (character array). It is
typically used to store multiple strings.

 Declaration: You can declare an array of strings like this:

char str[3][20]; // Array of 3 strings, each with a maximum size of


20 characters

 Initialization: You can initialize an array of strings as follows:

char str[3][20] = {"Hello", "World", "C Programming"};


 Accessing Strings: Each string in the array can be accessed by specifying the row index.

printf("%s", str[0]); // Output: Hello

 Example of Iteration: You can loop through the array of strings using a for loop:

char str[3][20] = {"Hello", "World", "C Programming"};


for (int i = 0; i < 3; i++) {
printf("%s\n", str[i]); // Output: Hello, World, C Programming
}

Example Program for String Operations and String Arrays:


#include <stdio.h>
#include <string.h>

int main() {
// String Initialization and Operations
char str1[] = "Hello";
char str2[] = "World";
char str3[50];

// String Length
printf("Length of str1: %zu\n", strlen(str1));

// String Copy
strcpy(str3, str1);
printf("Copied String: %s\n", str3);

// String Concatenation
strcat(str1, " ");
strcat(str1, str2);
printf("Concatenated String: %s\n", str1);

// String Comparison
int cmp = strcmp(str1, str2);
if (cmp < 0) {
printf("str1 is less than str2\n");
} else if (cmp > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}

// Array of Strings
char strArray[3][20] = {"Apple", "Banana", "Cherry"};
printf("\nArray of Strings:\n");
for (int i = 0; i < 3; i++) {
printf("%s\n", strArray[i]);
}

return 0;
}
Summary of Common String Functions:

Function Description

strlen Returns the length of the string (excluding null character).

strcpy Copies one string into another.

strcat Concatenates one string to another.

strcmp Compares two strings lexicographically.

strchr Searches for the first occurrence of a character in a string.

strtok Tokenizes a string based on delimiters.

Sorting in C

Sorting refers to arranging elements in a specific order (ascending or descending). In C,


sorting can be done using various algorithms such as Bubble Sort, Selection Sort, Insertion
Sort, Quick Sort, and Merge Sort.

Bubble Sort (Ascending Order)

Bubble sort works by repeatedly stepping through the list, comparing adjacent elements, and
swapping them if they are in the wrong order.

Program:

#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);

printf("Unsorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

bubbleSort(arr, n);
printf("\nSorted array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Selection Sort (Ascending Order)

Selection sort selects the minimum element from the unsorted part and swaps it with the first
unsorted element.

Program:

#include <stdio.h>

void selectionSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);

printf("Unsorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

selectionSort(arr, n);

printf("\nSorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

2. Searching in C

Searching refers to finding an element in a collection. The most common search algorithms
are Linear Search and Binary Search.

Linear Search
Linear search checks each element of the array one by one until the desired element is found.

Program:

#include <stdio.h>

int linearSearch(int arr[], int n, int key) {


for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return index of the found element
}
}
return -1; // If element is not found
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr)/sizeof(arr[0]);
int key = 30;

int result = linearSearch(arr, n, key);


if (result != -1) {
printf("Element found at index %d", result);
} else {
printf("Element not found");
}

return 0;
}

Binary Search (Requires Sorted Array)

Binary search works by repeatedly dividing the search interval in half. If the value of the
search key is less than the value in the middle, the interval is halved to the left, otherwise to
the right.

Program:

#include <stdio.h>

int binarySearch(int arr[], int left, int right, int key) {


while (left <= right) {
int mid = left + (right - left) / 2;

// Check if the key is present at mid


if (arr[mid] == key) {
return mid;
}

// If key is greater, ignore left half


if (arr[mid] < key) {
left = mid + 1;
}
// If key is smaller, ignore right half
else {
right = mid - 1;
}
}
return -1; // Key not found
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;

int result = binarySearch(arr, 0, n - 1, key);


if (result != -1) {
printf("Element found at index %d", result);
} else {
printf("Element not found");
}

return 0;
}

3. Matrix Operations in C

Matrix operations include addition, subtraction, multiplication, and transpose of matrices.

Matrix Addition

#include <stdio.h>

void addMatrices(int A[3][3], int B[3][3], int result[3][3]) {


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
}

int main() {
int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3];

addMatrices(A, B, result);

printf("Matrix A + B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

Matrix Multiplication

#include <stdio.h>

void multiplyMatrices(int A[3][3], int B[3][3], int result[3][3]) {


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0;
for (int k = 0; k < 3; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
}

int main() {
int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3];

multiplyMatrices(A, B, result);

printf("Matrix A * B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

4. Preprocessor Directives in C

Preprocessor directives are instructions processed before the compilation of the code begins.
Common preprocessor directives include:

 #define: Defines constants or macros.

#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))

 #include: Includes external files (headers).

#include <stdio.h> // Standard input-output library


#include "myheader.h" // User-defined header file

 #ifdef, #ifndef, #endif: Conditional compilation.

#define DEBUG

#ifdef DEBUG
printf("Debugging is enabled.\n");
#endif

 #if, #else, #elif: Conditional compilation based on expressions.

#if defined(WINDOWS)
printf("Windows OS\n");
#else
printf("Non-Windows OS\n");
#endif

You might also like