0% found this document useful (0 votes)
6 views35 pages

ArraysString

Download as pdf or txt
0% found this document useful (0 votes)
6 views35 pages

ArraysString

Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

1.

Definition of an Array in C:

An array is a collection of variables of the same type, stored in contiguous memory locations. It is a
data structure that allows storing multiple elements under a single name, making it easier to manage
large amounts of data.

2. Syntax for Declaring an Array:

data_type array_name[array_size];

data_type: Specifies the type of data (e.g., int, char, float).

array_name: The name of the array.

array_size: The number of elements the array can hold.

3. Types of Arrays in C:

a) 1D Array (One-Dimensional Array):

A one-dimensional array is a simple list of elements.

• Example Syntax:

int arr[5];

#include <stdio.h>

int main() {

int arr[5] = {10, 20, 30, 40, 50};

printf("Elements of array are:\n");

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

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

return 0;

b) 2D Array (Two-Dimensional Array):

A two-dimensional array can be thought of as an array of arrays, commonly used for matrices.

• Example Syntax:

int arr[3][3];
Example Program:

#include <stdio.h>

int main() {

int arr[3][3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

printf("Elements of 2D array:\n");

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

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

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

printf("\n");

return 0;

c) Multidimensional Arrays:

You can have arrays with more than two dimensions (3D, 4D, etc.), though it's not commonly used.

• Example Syntax (3D Array):

• int arr[2][3][4];

#include <stdio.h>

int main() {

int arr[2][3][4] = {
{

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}

},

{13, 14, 15, 16},

{17, 18, 19, 20},

{21, 22, 23, 24}

};

printf("Elements of 3D array:\n");

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

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

for (int k = 0; k < 4; k++) {

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

return 0;

d) String Array:

In C, a string is an array of characters. A string ends with a special null character '\0' to mark the end
of the string.

Example Syntax: char str[10];

#include <stdio.h>
int main() {

char str[] = "Hello, World!"; // string initialization

printf("String is: %s\n", str);

return 0;

4. Dynamic Memory Allocation in C:

Dynamic memory allocation allows you to allocate memory at runtime using functions from the
stdlib.h library. It is mainly used when you don't know the exact size of the array in advance.

a) malloc() Function:

The malloc() function is used to allocate a block of memory.

ptr = (data_type*) malloc(size_in_bytes);

Example Syntax: int* arr = (int*) malloc(5 * sizeof(int));

Example Program:

#include <stdio.h>

#include <stdlib.h>

int main() {

int* arr = (int*) malloc(5 * sizeof(int)); // Dynamically allocate memory for 5 integers

if (arr == NULL) {

printf("Memory allocation failed\n");

return 1;

// Initialize array

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


arr[i] = i * 10;

// Print array elements

printf("Dynamically allocated array:\n");

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

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

// Free the allocated memory

free(arr);

return 0;

b) calloc() Function:

The calloc() function allocates memory for an array of elements and initializes the memory to zero.

ptr = (data_type*) calloc(number_of_elements, size_of_each_element);

c) realloc() Function:

The realloc() function is used to resize a previously allocated memory block.

ptr = realloc(ptr, new_size_in_bytes);

d) free() Function:

The free() function deallocates previously allocated memory.

free(ptr);

5. Common Questions and Answers:

Q1: What is an array in C?

• Answer: An array is a collection of elements of the same data type stored in contiguous
memory locations. It is used to store multiple values in a single variable.
Q2: What is the difference between malloc and calloc in C?

• Answer: malloc() allocates memory without initializing it, while calloc() allocates memory
and initializes it to zero.

Q3: Can you change the size of a statically declared array?

• Answer: No, the size of a statically declared array cannot be changed during program
execution. To change the size dynamically, you must use dynamic memory allocation
functions like malloc() or realloc().

Q4: What is a string in C?

• Answer: A string is an array of characters in C, ending with a null character '\0' to indicate
the end of the string.

• 1. Matrix Addition (2D Array)


• Matrix addition is performed by adding corresponding elements from two matrices.

#include <stdio.h>

#define MAX 3 // Defining matrix size (3x3 matrix)

int main() {

int A[MAX][MAX], B[MAX][MAX], sum[MAX][MAX];

// Input for Matrix A

printf("Enter elements for matrix A:\n");

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

for (int j = 0; j < MAX; j++) {

printf("A[%d][%d]: ", i, j);

scanf("%d", &A[i][j]);

// Input for Matrix B

printf("Enter elements for matrix B:\n");

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

for (int j = 0; j < MAX; j++) {


printf("B[%d][%d]: ", i, j);

scanf("%d", &B[i][j]);

// Matrix Addition

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

for (int j = 0; j < MAX; j++) {

sum[i][j] = A[i][j] + B[i][j];

// Display the result

printf("\nMatrix A + Matrix B = \n");

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

for (int j = 0; j < MAX; j++) {

printf("%d ", sum[i][j]);

printf("\n");

return 0;

Enter elements for matrix A:

A[0][0]: 1

A[0][1]: 2

A[0][2]: 3

A[1][0]: 4

A[1][1]: 5

A[1][2]: 6

A[2][0]: 7
A[2][1]: 8

A[2][2]: 9

Enter elements for matrix B:

B[0][0]: 9

B[0][1]: 8

B[0][2]: 7

B[1][0]: 6

B[1][1]: 5

B[1][2]: 4

B[2][0]: 3

B[2][1]: 2

B[2][2]: 1

Matrix A + Matrix B =

10 10 10

10 10 10

10 10 10

2. Matrix Multiplication (2D Array)

Matrix multiplication involves multiplying rows of the first matrix with columns of the second
matrix.

#include <stdio.h>

#define MAX 3

int main() {

int A[MAX][MAX], B[MAX][MAX], product[MAX][MAX] = {0};

// Input for Matrix A


printf("Enter elements for matrix A:\n");

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

for (int j = 0; j < MAX; j++) {

printf("A[%d][%d]: ", i, j);

scanf("%d", &A[i][j]);

// Input for Matrix B

printf("Enter elements for matrix B:\n");

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

for (int j = 0; j < MAX; j++) {

printf("B[%d][%d]: ", i, j);

scanf("%d", &B[i][j]);

// Matrix Multiplication

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

for (int j = 0; j < MAX; j++) {

for (int k = 0; k < MAX; k++) {

product[i][j] += A[i][k] * B[k][j];

// Display the result

printf("\nMatrix A * Matrix B = \n");

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

for (int j = 0; j < MAX; j++) {

printf("%d ", product[i][j]);


}

printf("\n");

return 0;

Enter elements for matrix A:

A[0][0]: 1

A[0][1]: 2

A[0][2]: 3

A[1][0]: 4

A[1][1]: 5

A[1][2]: 6

A[2][0]: 7

A[2][1]: 8

A[2][2]: 9

Enter elements for matrix B:

B[0][0]: 9

B[0][1]: 8

B[0][2]: 7

B[1][0]: 6

B[1][1]: 5

B[1][2]: 4

B[2][0]: 3

B[2][1]: 2

B[2][2]: 1

Matrix A * Matrix B =

30 24 18

84 69 54
138 114 90

3. Matrix Transpose (2D Array)

Matrix transpose involves swapping the rows and columns of the matrix.

#include <stdio.h>

#define MAX 3

int main() {

int matrix[MAX][MAX], transpose[MAX][MAX];

// Input for Matrix

printf("Enter elements for the matrix:\n");

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

for (int j = 0; j < MAX; j++) {

printf("Matrix[%d][%d]: ", i, j);

scanf("%d", &matrix[i][j]);

// Matrix Transpose

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

for (int j = 0; j < MAX; j++) {

transpose[j][i] = matrix[i][j];

// Display Transposed Matrix

printf("\nTransposed Matrix:\n");

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


for (int j = 0; j < MAX; j++) {

printf("%d ", transpose[i][j]);

printf("\n");

return 0;

Enter elements for the matrix:

Matrix[0][0]: 1

Matrix[0][1]: 2

Matrix[0][2]: 3

Matrix[1][0]: 4

Matrix[1][1]: 5

Matrix[1][2]: 6

Matrix[2][0]: 7

Matrix[2][1]: 8

Matrix[2][2]: 9

Transposed Matrix:

147

258

369

4. Reverse a String (1D Array / String)

This program reverses a string entered by the user.

#include <stdio.h>

#include <string.h>
void reverseString(char str[]) {

int start = 0, end = strlen(str) - 1;

char temp;

while (start < end) {

temp = str[start];

str[start] = str[end];

str[end] = temp;

start++;

end--;

int main() {

char str[100];

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Remove the newline character

str[strcspn(str, "\n")] = '\0';

reverseString(str);

printf("Reversed String: %s\n", str);

return 0;

Enter a string: Hello

Reversed String: olleH


5. Recursion Example (Factorial Calculation)

A simple program to compute the factorial of a number using recursion.

#include <stdio.h>

int factorial(int n) {

if (n == 0 || n == 1) {

return 1;

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

printf("Factorial of %d is: %d\n", num, factorial(num));

return 0;

Enter a number: 5

Factorial of 5 is: 120


1. Linear Search (1D Array)

This program demonstrates how to perform a linear search on a one-dimensional array to find an
element.

#include <stdio.h>

int linearSearch(int arr[], int size, int target) {

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

if (arr[i] == target) {

return i; // Return the index if found

return -1; // Return -1 if not found

int main() {

int arr[] = {10, 20, 30, 40, 50};

int size = sizeof(arr) / sizeof(arr[0]);

int target, result;

printf("Enter the element to search: ");

scanf("%d", &target);

result = linearSearch(arr, size, target);

if (result != -1) {

printf("Element found at index %d\n", result);

} else {

printf("Element not found\n");

}
return 0;

Enter the element to search: 30

Element found at index 2

2. Binary Search (1D Array)

Binary search works only on a sorted array and is much faster than linear search. Here’s an
example program for binary search.

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {

int low = 0, high = size - 1, mid;

while (low <= high) {

mid = (low + high) / 2;

if (arr[mid] == target) {

return mid; // Return the index if found

} else if (arr[mid] < target) {

low = mid + 1;

} else {

high = mid - 1;

return -1; // Return -1 if not found

int main() {
int arr[] = {10, 20, 30, 40, 50};

int size = sizeof(arr) / sizeof(arr[0]);

int target, result;

printf("Enter the element to search: ");

scanf("%d", &target);

result = binarySearch(arr, size, target);

if (result != -1) {

printf("Element found at index %d\n", result);

} else {

printf("Element not found\n");

return 0;

Enter the element to search: 40

Element found at index 3

3. Bubble Sort (1D Array)

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to compare
adjacent elements and swap them if necessary.

#include <stdio.h>

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

for (int i = 0; i < size-1; i++) {

for (int j = 0; j < size-i-1; j++) {

if (arr[j] > arr[j+1]) {


// Swap the elements

int temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

void printArray(int arr[], int size) {

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

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

printf("\n");

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Unsorted array: ");

printArray(arr, size);

bubbleSort(arr, size);

printf("Sorted array: ");

printArray(arr, size);

return 0;

}
Unsorted array: 64 34 25 12 22 11 90

Sorted array: 11 12 22 25 34 64 90

4. String Length (Without Using strlen function)

This program calculates the length of a string manually without using the built-in strlen() function.

#include <stdio.h>

int stringLength(char str[]) {

int length = 0;

while (str[length] != '\0') {

length++;

return length;

int main() {

char str[100];

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Remove the newline character if present

str[strcspn(str, "\n")] = '\0';

printf("Length of the string is: %d\n", stringLength(str));

return 0;

}
Enter a string: Hello, World!

Length of the string is: 13

5. Palindrome Check (String)

This program checks whether a string is a palindrome, i.e., it reads the same forwards and
backwards.

#include <stdio.h>

#include <string.h>

#include <ctype.h>

int isPalindrome(char str[]) {

int start = 0, end = strlen(str) - 1;

while (start < end) {

if (tolower(str[start]) != tolower(str[end])) {

return 0; // Not a palindrome

start++;

end--;

return 1; // Palindrome

int main() {

char str[100];

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

// Remove the newline character if present

str[strcspn(str, "\n")] = '\0';


if (isPalindrome(str)) {

printf("The string is a palindrome.\n");

} else {

printf("The string is not a palindrome.\n");

return 0;

Enter a string: madam

The string is a palindrome.

7. Matrix Multiplication (2D Array)

Matrix multiplication is an important concept when working with 2D arrays.

#include <stdio.h>

#define MAX 3

int main() {

int A[MAX][MAX], B[MAX][MAX], product[MAX][MAX] = {0};

// Input for Matrix A

printf("Enter elements for matrix A:\n");

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

for (int j = 0; j < MAX; j++) {

printf("A[%d][%d]: ", i, j);

scanf("%d", &A[i][j]);

}
// Input for Matrix B

printf("Enter elements for matrix B:\n");

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

for (int j = 0; j < MAX; j++) {

printf("B[%d][%d]: ", i, j);

scanf("%d", &B[i][j]);

// Matrix Multiplication

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

for (int j = 0; j < MAX; j++) {

for (int k = 0; k < MAX; k++) {

product[i][j] += A[i][k] * B[k][j];

// Display the result

printf("\nMatrix A * Matrix B = \n");

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

for (int j = 0; j < MAX; j++) {

printf("%d ", product[i][j]);

printf("\n");

return 0;

Enter elements for matrix A:

A[0][0]: 1
A[0][1]: 2

A[0][2]: 3

A[1][0]: 4

A[1][1]: 5

A[1][2]: 6

A[2][0]: 7

A[2][1]: 8

A[2][2]: 9

Enter elements for matrix B:

B[0][0]: 1

B[0][1]: 2

B[0][2]: 3

B[1][0]: 4

B[1][1]: 5

B[1][2]: 6

B[2][0]: 7

B[2][1]: 8

B[2][2]: 9

Matrix A * Matrix B =

30 36 42

66 81 96

102 126 150

8. Find Maximum Element in Array (1D Array)

This program finds the maximum element in an array.

#include <stdio.h>

int findMax(int arr[], int size) {


int max = arr[0];

for (int i = 1; i < size; i++) {

if (arr[i] > max) {

max = arr[i];

return max;

int main() {

int arr[] = {10, 20, 50, 30, 40};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Maximum element in the array: %d\n", findMax(arr, size));

return 0;

Maximum element in the array: 50

1. Sorting an Array of Strings (Alphabetical Order)

This program sorts an array of strings in alphabetical order using the Bubble Sort algorithm.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS 5

#define MAX_LENGTH 100

void bubbleSort(char arr[MAX_STRINGS][MAX_LENGTH], int n) {


char temp[MAX_LENGTH];

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (strcmp(arr[j], arr[j + 1]) > 0) {

// Swap the strings

strcpy(temp, arr[j]);

strcpy(arr[j], arr[j + 1]);

strcpy(arr[j + 1], temp);

int main() {

char arr[MAX_STRINGS][MAX_LENGTH];

printf("Enter %d strings:\n", MAX_STRINGS);

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

fgets(arr[i], MAX_LENGTH, stdin);

// Remove the newline character

arr[i][strcspn(arr[i], "\n")] = '\0';

bubbleSort(arr, MAX_STRINGS);

printf("\nStrings in alphabetical order:\n");

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

printf("%s\n", arr[i]);

return 0;
}

Enter 5 strings:

apple

banana

grape

orange

kiwi

Strings in alphabetical order:

apple

banana

grape

kiwi

orange

2. Counting Vowels in an Array of Strings

This program counts the number of vowels in each string of an array of strings.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS 5

#define MAX_LENGTH 100

int countVowels(char str[]) {

int count = 0;

for (int i = 0; str[i] != '\0'; i++) {

char c = str[i];

if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||

c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {

count++;
}

return count;

int main() {

char arr[MAX_STRINGS][MAX_LENGTH];

printf("Enter %d strings:\n", MAX_STRINGS);

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

fgets(arr[i], MAX_LENGTH, stdin);

// Remove the newline character

arr[i][strcspn(arr[i], "\n")] = '\0';

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

printf("String: %s | Vowel count: %d\n", arr[i], countVowels(arr[i]));

return 0;

Enter 5 strings:

apple

banana

orange

grape

kiwi

String: apple | Vowel count: 2

String: banana | Vowel count: 3


String: orange | Vowel count: 3

String: grape | Vowel count: 2

String: kiwi | Vowel count: 2

3. Reversing Each String in an Array of Strings

This program reverses each string in an array of strings.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS 5

#define MAX_LENGTH 100

void reverseString(char str[]) {

int start = 0;

int end = strlen(str) - 1;

char temp;

while (start < end) {

temp = str[start];

str[start] = str[end];

str[end] = temp;

start++;

end--;

int main() {

char arr[MAX_STRINGS][MAX_LENGTH];

printf("Enter %d strings:\n", MAX_STRINGS);


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

fgets(arr[i], MAX_LENGTH, stdin);

// Remove the newline character

arr[i][strcspn(arr[i], "\n")] = '\0';

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

reverseString(arr[i]);

printf("Reversed string: %s\n", arr[i]);

return 0;

Enter 5 strings:

hello

world

apple

banana

kiwi

Reversed string: olleh

Reversed string: dlrow

Reversed string: elppa

Reversed string: ananab

Reversed string: iwik

4. Concatenating Two Arrays of Strings

This program demonstrates how to concatenate two arrays of strings into a single array.

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

#define MAX_STRINGS 5

#define MAX_LENGTH 100

int main() {

char arr1[MAX_STRINGS][MAX_LENGTH], arr2[MAX_STRINGS][MAX_LENGTH];

char result[MAX_STRINGS * 2][MAX_LENGTH]; // Array to hold concatenated strings

printf("Enter %d strings for the first array:\n", MAX_STRINGS);

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

fgets(arr1[i], MAX_LENGTH, stdin);

// Remove the newline character

arr1[i][strcspn(arr1[i], "\n")] = '\0';

printf("Enter %d strings for the second array:\n", MAX_STRINGS);

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

fgets(arr2[i], MAX_LENGTH, stdin);

// Remove the newline character

arr2[i][strcspn(arr2[i], "\n")] = '\0';

// Concatenate the arrays

int k = 0;

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

strcpy(result[k], arr1[i]);

k++;

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


strcpy(result[k], arr2[i]);

k++;

printf("\nConcatenated array of strings:\n");

for (int i = 0; i < MAX_STRINGS * 2; i++) {

printf("%s\n", result[i]);

return 0;

Enter 5 strings for the first array:

hello

world

apple

banana

kiwi

Enter 5 strings for the second array:

cat

dog

elephant

tiger

lion

Concatenated array of strings:

hello

world

apple

banana
kiwi

cat

dog

elephant

tiger

lion

5. Finding the Longest String in an Array of Strings

This program finds the longest string in an array of strings.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS 5

#define MAX_LENGTH 100

int main() {

char arr[MAX_STRINGS][MAX_LENGTH];

char longest[MAX_LENGTH];

int maxLength = 0;

printf("Enter %d strings:\n", MAX_STRINGS);

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

fgets(arr[i], MAX_LENGTH, stdin);

// Remove the newline character

arr[i][strcspn(arr[i], "\n")] = '\0';

int len = strlen(arr[i]);

if (len > maxLength) {

maxLength = len;

strcpy(longest, arr[i]);
}

printf("\nThe longest string is: %s\n", longest);

return 0;

Enter 5 strings:

hello

world

applepie

banana

kiwi

The longest string is: applepie

6. String Comparison Between Two Arrays of Strings

This program compares two arrays of strings and checks if they are identical.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS 5

#define MAX_LENGTH 100

int compareStrings(char arr1[MAX_STRINGS][MAX_LENGTH], char


arr2[MAX_STRINGS][MAX_LENGTH]) {

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

if (strcmp(arr1[i], arr2[i]) != 0) {

return 0; // Strings are not identical


}

return 1; // Strings are identical

int main() {

char arr1[MAX_STRINGS][MAX_LENGTH], arr2[MAX_STRINGS][MAX_LENGTH];

printf("Enter %d strings for the first array:\n", MAX_STRINGS);

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

fgets(arr1[i], MAX_LENGTH, stdin);

arr1[i][strcspn(arr1[i], "\n")] = '\0';

printf("Enter %d strings for the second array:\n", MAX_STRINGS);

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

fgets(arr2[i], MAX_LENGTH, stdin);

arr2[i][strcspn(arr2[i], "\n")] = '\0';

if (compareStrings(arr1, arr2)) {

printf("\nBoth arrays are identical.\n");

} else {

printf("\nArrays are not identical.\n");

return 0;

Enter 5 strings for the first array:

apple

banana
cherry

date

fig

Enter 5 strings for the second array:

apple

banana

cherry

date

fig

Both arrays are identical.

You might also like