Arrays and Sorting
Arrays and Sorting
same data type. Arrays are used to organize and manipulate collections of data efficiently.
In declaration, we specify then name and the size of the 1d array.
elements_type array_name[array_size];
Accessing Elements
Array elements are accessed using their index, which starts from 0 for the first element.
int first_number = numbers[0]; // Accesses the first element
numbers[1] = 100; // Modifies the second element
EXAMPLE:
#include <stdio.h>
int main() {
int grades[5] = {90, 85, 78, 95, 88};
int sum = 0;
• The subscript represents the array's size. For example, when the size is set to 10,
programmers can store ten elements.
• An array index always begins with 0. For example, if an array variable is declared
as array[10], the index can take values between 0 and 9.
A 2D array can be initialized during declaration using nested braces, or element-wise later in
the code. For example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
The string handling functions are defined in the header file string.h. This header file must be
included in the C program to use the string handling functions.
The following are the string functions in C:
Function Description
strcmp() It compares two strings and returns 0 if the strings are the same.
The strlwr() function takes a single string as its argument. The function is used to convert the
passed string into lowercase.
strlwr() Syntax
strlwr(string1);
The strupr() function takes a single string as its argument. The function is used to convert the
passed string into uppercase.
strupr()
Syntax
strupr(string1);
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
OUTPUT:
[1, 5, 7, 8, 9, 10]
CODE FOR BUBBLE SORT:
#include <stdio.h>
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
// Swap if elements are in wrong order
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}
OUTPUT: Sorted array:
11 12 22 25 34 64 90
int main() {
int arr[] = {20,12,10,15,2};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}