Friday, 11 July 2025

Write a program to multiply two matrices.

Write a program to multiply two matrices.

Learn how to multiply two matrices in C programming

matrix_multiplication.c
#include <stdio.h>

int main() {
    int A[10][10], B[10][10], C[10][10];
    int r1, c1, r2, c2, i, j, k;

    // Input dimensions of matrix A
    printf("Enter rows and columns for matrix A: ");
    scanf("%d%d", &r1, &c1);

    // Input dimensions of matrix B
    printf("Enter rows and columns for matrix B: ");
    scanf("%d%d", &r2, &c2);

    // Check multiplication condition
    if(c1 != r2) {
        printf("Matrix multiplication not possible. Columns of A must equal rows of B.\n");
        return 0;
    }

    // Input elements of matrix A
    printf("Enter elements of matrix A:\n");
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c1; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of matrix B
    printf("Enter elements of matrix B:\n");
    for(i = 0; i < r2; i++) {
        for(j = 0; j < c2; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    // Multiply matrices
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            C[i][j] = 0;
            for(k = 0; k < c1; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }

    // Display result matrix
    printf("\nResultant Matrix C (A x B):\n");
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This standard library provides essential functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Basic console I/O operations

๐Ÿ”น Step 2: Declare Matrices and Variables

int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2, i, j, k;
  • A, B, C: 10×10 matrices (2D arrays)
  • r1, c1: Rows and columns of Matrix A
  • r2, c2: Rows and columns of Matrix B
  • i, j, k: Loop counters for matrix operations

๐Ÿ”น Step 3: Input Matrix Dimensions

printf("Enter rows and columns for matrix A: ");
scanf("%d%d", &r1, &c1);

printf("Enter rows and columns for matrix B: ");
scanf("%d%d", &r2, &c2);
  • Gets dimensions for both matrices from user
  • Uses %d%d to read two integers at once
  • Maximum size is 10×10 as declared

๐Ÿ”น Step 4: Check Multiplication Condition

if(c1 != r2) {
    printf("Matrix multiplication not possible.\n");
    return 0;
}
  • Verifies columns of A match rows of B
  • Matrix multiplication requires this condition
  • Exits program if condition fails

๐Ÿ”น Step 5: Input Matrix Elements

for(i = 0; i < r1; i++) {
    for(j = 0; j < c1; j++) {
        scanf("%d", &A[i][j]);
    }
}
  • Nested loops to read each matrix element
  • First for rows, second for columns
  • Same process for both matrices A and B
  • Displays position with each input prompt

๐Ÿ”น Step 6: Multiply Matrices

for(i = 0; i < r1; i++) {
    for(j = 0; j < c2; j++) {
        C[i][j] = 0;
        for(k = 0; k < c1; k++) {
            C[i][j] += A[i][k] * B[k][j];
        }
    }
}

Matrix multiplication algorithm:

  • Outer loops: Iterate through result matrix positions
  • Inner loop: Computes dot product of row from A and column from B
  • Initialization: Sets result position to 0 before accumulation
  • Accumulation: Sums products of corresponding elements

๐Ÿ”น Step 7: Display Result Matrix

for(i = 0; i < r1; i++) {
    for(j = 0; j < c2; j++) {
        printf("%d\t", C[i][j]);
    }
    printf("\n");
}
  • Prints result matrix in tabular format
  • Uses \t for column alignment
  • Uses \n after each row
  • Shows final product of matrix multiplication

๐Ÿงช Sample Output

Enter rows and columns for matrix A: 2 3
Enter rows and columns for matrix B: 3 2
Enter elements of 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
Enter elements of matrix B:
B[0][0]: 7
B[0][1]: 8
B[1][0]: 9
B[1][1]: 10
B[2][0]: 11
B[2][1]: 12

Resultant Matrix C (A x B):
58      64
139     154

๐Ÿ“Œ Key Concepts Covered

Matrix Multiplication
Dot product of rows from first matrix with columns from second matrix
2D Arrays
Used to represent matrices with rows and columns
Triple Nested Loops
Outer two for result matrix positions, inner for multiplication/summation
Dimension Validation
Ensures columns of first matrix match rows of second matrix
Tabular Output
Formatted display of matrix with rows and columns properly aligned

Sort the array into descending order.

Sort the array into descending order.

Learn how to implement Bubble Sort for descending order in C

bubble_sort_descending.c
#include <stdio.h>

int main() {
    int arr[100], n, i, j, temp;

    // Input size of array
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Input elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Sorting using Bubble Sort (Descending Order)
    for(i = 0; i < n - 1; i++) {
        for(j = 0; j < n - i - 1; j++) {
            if(arr[j] < arr[j + 1]) {
                // Swap elements
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Display sorted array
    printf("\nArray in descending order:\n");
    for(i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This standard library provides essential functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Basic console I/O operations

๐Ÿ”น Step 2: Declare Variables and Array

int arr[100], n, i, j, temp;
  • arr[100]: Array that can hold up to 100 integers
  • n: Actual number of elements to be sorted
  • i, j: Loop counters for sorting passes
  • temp: Temporary variable for element swapping

๐Ÿ”น Step 3: Input Size and Elements

printf("Enter the number of elements: ");
scanf("%d", &n);

for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  • First gets the array size (n ≤ 100)
  • Then collects each element from user
  • Stores elements in sequential array positions
  • Displays index with each input prompt

๐Ÿ”น Step 4: Sort the Array (Bubble Sort - Descending)

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

Modified Bubble Sort for descending order:

  • Outer loop: Controls number of passes (n-1 passes needed)
  • Inner loop: Compares adjacent elements in each pass
  • Comparison: Checks if left element is smaller than right
  • Swapping: Exchanges elements if in wrong order
  • With each pass, smallest unsorted element "bubbles down"

๐Ÿ”น Step 5: Display Sorted Array

for(i = 0; i < n; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}
  • Prints all elements in sorted descending order
  • Shows both index and value for each element
  • Verifies the successful sorting
  • Uses newline character for clean output

๐Ÿงช Sample Output

Enter the number of elements: 5
Enter 5 elements:
arr[0]: 25
arr[1]: 40
arr[2]: 10
arr[3]: 60
arr[4]: 30

Array in descending order:
arr[0] = 60
arr[1] = 40
arr[2] = 30
arr[3] = 25
arr[4] = 10

๐Ÿ“Œ Key Concepts Covered

Bubble Sort Algorithm
A simple comparison-based sorting method with O(n²) time complexity, modified for descending order
Descending Order
Arranging elements from largest to smallest value
Array Processing
Storing and manipulating multiple values in a linear data structure
Element Swapping
Using a temporary variable to exchange two array values
Nested Loop Control
Outer loop for passes; inner loop for element comparison and swapping

Sort the array into ascending order.

Sort the array into ascending order.

Learn how to implement Bubble Sort algorithm in C

bubble_sort.c
#include <stdio.h>

int main() {
    int arr[100], n, i, j, temp;

    // Input size of array
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Input elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Sorting using Bubble Sort (Ascending Order)
    for(i = 0; i < n - 1; i++) {
        for(j = 0; j < n - i - 1; j++) {
            if(arr[j] > arr[j + 1]) {
                // Swap elements
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Display sorted array
    printf("\nArray in ascending order:\n");
    for(i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This standard library provides:

  • printf() for output display
  • scanf() for user input
  • Essential I/O functions for console operations

๐Ÿ”น Step 2: Declare Variables and Array

int arr[100], n, i, j, temp;
  • arr[100]: Array with capacity for 100 integers
  • n: Actual number of elements to sort
  • i, j: Loop counters for sorting passes
  • temp: Temporary variable for swapping elements

๐Ÿ”น Step 3: Input Size and Elements

printf("Enter the number of elements: ");
scanf("%d", &n);

for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  • First gets the array size (n ≤ 100)
  • Then collects each element from user
  • Stores elements in sequential array positions
  • Uses formatted input with index display

๐Ÿ”น Step 4: Sort the Array (Bubble Sort)

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

Bubble Sort implementation:

  • Outer loop: Controls number of passes (n-1 passes needed)
  • Inner loop: Compares adjacent elements in each pass
  • Comparison: Checks if elements are in wrong order
  • Swapping: Uses temp variable to exchange elements
  • With each pass, largest unsorted element "bubbles up" to correct position

๐Ÿ”น Step 5: Display Sorted Array

for(i = 0; i < n; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}
  • Prints all elements in sorted order
  • Shows both index and value for each element
  • Verifies the successful sorting
  • Uses newline character for clean output

๐Ÿงช Sample Output

Enter the number of elements: 5
Enter 5 elements:
arr[0]: 30
arr[1]: 10
arr[2]: 50
arr[3]: 20
arr[4]: 40

Array in ascending order:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

๐Ÿ“Œ Key Concepts Covered

Bubble Sort Algorithm
A simple comparison-based sorting method with O(n²) time complexity
Array Manipulation
Storing and processing multiple values in a linear data structure
Nested Loops
Using one loop inside another to implement sorting passes
Element Swapping
Temporary variable technique for exchanging two values
Ascending Order
Arranging elements from smallest to largest value

Thursday, 10 July 2025

Delete an element from the array from user defined position.

Delete an element from the array from user defined position.

Learn how to remove an element from any position in an array

array_deletion.c
#include <stdio.h>

int main() {
    int arr[20], n, i, pos;

    // Input current size of array
    printf("Enter number of elements (max 20): ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Input position to delete
    printf("Enter position to delete (0 to %d): ", n - 1);
    scanf("%d", &pos);

    // Check for valid position
    if(pos < 0 || pos >= n) {
        printf("Invalid position!\n");
    } else {
        // Shift elements to the left
        for(i = pos; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        n--; // Decrease size

        // Display updated array
        printf("\nArray after deletion:\n");
        for(i = 0; i < n; i++) {
            printf("arr[%d] = %d\n", i, arr[i]);
        }
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides essential input/output functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Other standard I/O operations

๐Ÿ”น Step 2: Declare Variables and Array

int arr[20], n, i, pos;
  • arr[20]: Array with maximum capacity of 20 elements
  • n: Current number of elements in the array
  • pos: Position of element to be deleted
  • i: Loop counter variable

๐Ÿ”น Step 3: Input Size and Elements of Array

printf("Enter number of elements (max 20): ");
scanf("%d", &n);

for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  • Gets the current size of the array (n ≤ 20)
  • Collects each element from the user
  • Stores elements sequentially in the array

๐Ÿ”น Step 4: Input Position to Delete

printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &pos);
  • Gets the index of element to be removed
  • Valid positions are between 0 and n-1
  • Shows user the valid range in the prompt

๐Ÿ”น Step 5: Validate the Position

if(pos < 0 || pos >= n) {
    printf("Invalid position!\n");
}
  • Checks if position is negative
  • Checks if position exceeds array bounds
  • Provides error message for invalid input

๐Ÿ”น Step 6: Shift Elements to the Left

for(i = pos; i < n - 1; i++) {
    arr[i] = arr[i + 1];
}
n--;
  • Starts from deletion position
  • Moves each element one position left
  • Overwrites the deleted element
  • Decreases array size counter (n)

๐Ÿ”น Step 7: Display the Updated Array

for(i = 0; i < n; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}
  • Prints all elements after deletion
  • Shows both index and value for each element
  • Verifies the successful deletion

๐Ÿงช Sample Output

Enter number of elements (max 20): 5
Enter 5 elements:
arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50
Enter position to delete (0 to 4): 2

Array after deletion:
arr[0] = 10
arr[1] = 20
arr[2] = 40
arr[3] = 50

๐Ÿ“Œ Key Concepts Covered

Array Operations
Manipulating fixed-size collections of elements in memory
Element Deletion
Removing elements at specific positions by shifting elements
Left Shifting
Moving array elements to lower indices to fill deletion gap
Input Validation
Ensuring position is within valid bounds (0 to current size-1)
Size Management
Tracking and updating the current number of elements in the array

Insert an element into the array at user defined position.

Insert an element into the array at user defined position.

Learn how to insert an element at any position in an array

array_insertion.c
#include <stdio.h>

int main() {
    int arr[20], n, i, pos, value;

    // Input current size of array
    printf("Enter number of elements (max 19): ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Input value and position to insert
    printf("Enter the element to insert: ");
    scanf("%d", &value);
    printf("Enter the position (0 to %d): ", n);
    scanf("%d", &pos);

    // Shift elements to the right
    for(i = n; i > pos; i--) {
        arr[i] = arr[i - 1];
    }

    // Insert the new value
    arr[pos] = value;
    n++;  // increase size

    // Display updated array
    printf("\nArray after insertion:\n");
    for(i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides essential input/output functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Other standard I/O operations

๐Ÿ”น Step 2: Declare Variables and Array

int arr[20], n, i, pos, value;
  • arr[20]: Array with maximum capacity of 20 elements
  • n: Current number of elements in the array
  • pos: Position where new element will be inserted
  • value: The element to be inserted
  • i: Loop counter variable

๐Ÿ”น Step 3: Input Array Elements

printf("Enter number of elements (max 19): ");
scanf("%d", &n);

for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  • First gets the current size of the array (n)
  • Then collects each element from the user
  • Stores elements sequentially in the array
  • Limits to 19 elements to leave space for insertion

๐Ÿ”น Step 4: Input Position and Value to Insert

printf("Enter the element to insert: ");
scanf("%d", &value);
printf("Enter the position (0 to %d): ", n);
scanf("%d", &pos);
  • Gets the new value to be inserted
  • Gets the insertion position (0 to n)
  • Valid positions are between 0 and current size (n)

๐Ÿ”น Step 5: Shift Elements to the Right

for(i = n; i > pos; i--) {
    arr[i] = arr[i - 1];
}
  • Starts from the end of the array
  • Moves each element one position to the right
  • Creates space at the insertion point
  • Works backwards to avoid overwriting data

๐Ÿ”น Step 6: Insert the New Value

arr[pos] = value;
n++;
  • Places the new value at the specified position
  • Increments the array size counter (n)
  • Maintains array integrity

๐Ÿ”น Step 7: Display the Updated Array

for(i = 0; i < n; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}
  • Prints all elements including the new insertion
  • Shows both index and value for each element
  • Verifies the successful insertion

๐Ÿงช Sample Output

Enter number of elements (max 19): 5
Enter 5 elements:
arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50
Enter the element to insert: 99
Enter the position (0 to 5): 2

Array after insertion:
arr[0] = 10
arr[1] = 20
arr[2] = 99
arr[3] = 30
arr[4] = 40
arr[5] = 50

๐Ÿ“Œ Key Concepts Covered

Array Operations
Manipulating fixed-size collections of elements in memory
Element Insertion
Adding new elements at specific positions by shifting existing elements
Right Shifting
Moving array elements to higher indices to create space for insertion
Position Validation
Ensuring insertion position is within valid bounds (0 to current size)
Size Management
Tracking and updating the current number of elements in the array

Create an array of size 10, find the largest value from the array.

Create an array of size 10, find the largest value from the array.

Learn how to find the maximum value in an array using C programming

find_max.c
#include <stdio.h>

int main() {
    int arr[10], i, max;

    // Input elements in the array
    printf("Enter 10 elements:\n");
    for(i = 0; i < 10; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Assume first element is the largest
    max = arr[0];

    // Compare with other elements
    for(i = 1; i < 10; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }

    // Display the largest value
    printf("\nThe largest value in the array is: %d\n", max);

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides essential input/output functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Other standard I/O operations

๐Ÿ”น Step 2: Declare Array and Variables

int arr[10], i, max;
  • arr[10]: Array to store 10 integer values
  • i: Loop counter for array traversal
  • max: Variable to store the maximum value

๐Ÿ”น Step 3: Input Elements in the Array

for(i = 0; i < 10; i++) {
    printf("arr[%d]: ", i);
    scanf("%d", &arr[i]);
}
  • Prompts user to enter 10 values
  • Stores each value in the array
  • Uses %d format specifier for integers
  • Displays current index with arr[%d]

๐Ÿ”น Step 4: Assume First Element as Maximum

max = arr[0];
  • Initializes max with first array element
  • Provides a starting point for comparison
  • Common algorithm pattern for finding max/min

๐Ÿ”น Step 5: Compare and Find the Largest

for(i = 1; i < 10; i++) {
    if(arr[i] > max) {
        max = arr[i];
    }
}
  • Starts loop from index 1 (since index 0 is already in max)
  • Compares each element with current max
  • Updates max if larger value is found
  • Implements linear search algorithm

๐Ÿ”น Step 6: Display the Result

printf("\nThe largest value in the array is: %d\n", max);
  • Prints the final maximum value
  • Uses %d to format the integer output
  • Includes newline characters for clean formatting

๐Ÿงช Sample Output

Enter 10 elements:
arr[0]: 23
arr[1]: 45
arr[2]: 12
arr[3]: 99
arr[4]: 34
arr[5]: 67
arr[6]: 88
arr[7]: 54
arr[8]: 11
arr[9]: 76

The largest value in the array is: 99

๐Ÿ“Œ Key Concepts Covered

Array Declaration
Creating a fixed-size collection of elements with int arr[size]
Linear Search
Sequentially checking each element to find the maximum value
Conditional Logic
Using if statements to compare values
Loop Control
Using for loops to traverse arrays
Variable Initialization
Starting with a sensible default value (first element)

Create arrays A, B of size 3, C of size 6, merge A and B into C.

Create arrays A, B of size 3, C of size 6, merge A and B into C.

Learn how to merge two arrays into a third array in C

merge_arrays.c
#include <stdio.h>

int main() {
    int A[3], B[3], C[6];
    int i;

    // Input elements of array A
    printf("Enter 3 elements of array A:\n");
    for(i = 0; i < 3; i++) {
        printf("A[%d]: ", i);
        scanf("%d", &A[i]);
    }

    // Input elements of array B
    printf("\nEnter 3 elements of array B:\n");
    for(i = 0; i < 3; i++) {
        printf("B[%d]: ", i);
        scanf("%d", &B[i]);
    }

    // Merge A into C
    for(i = 0; i < 3; i++) {
        C[i] = A[i];
    }

    // Merge B into C
    for(i = 0; i < 3; i++) {
        C[i + 3] = B[i];
    }

    // Display merged array C
    printf("\nMerged array C:\n");
    for(i = 0; i < 6; i++) {
        printf("C[%d] = %d\n", i, C[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides:

  • printf() for output display
  • scanf() for user input
  • Standard I/O functions

๐Ÿ”น Step 2: Declare Arrays and Variable

int A[3], B[3], C[6];
int i;
  • A[3] and B[3]: Input arrays (3 elements each)
  • C[6]: Output array for merged result
  • i: Loop counter for array operations

๐Ÿ”น Step 3: Input Elements in Array A

for(i = 0; i < 3; i++) {
    printf("A[%d]: ", i);
    scanf("%d", &A[i]);
}
  • Prompts user for 3 values
  • Stores them in array A
  • Uses %d format for integers

๐Ÿ”น Step 4: Input Elements in Array B

for(i = 0; i < 3; i++) {
    printf("B[%d]: ", i);
    scanf("%d", &B[i]);
}
  • Same process as Step 3
  • Stores values in array B
  • Maintains parallel indexing

๐Ÿ”น Step 5: Merge Array A into C

for(i = 0; i < 3; i++) {
    C[i] = A[i];
}
  • Copies A[0] to C[0]
  • Copies A[1] to C[1]
  • Copies A[2] to C[2]

๐Ÿ”น Step 6: Merge Array B into C

for(i = 0; i < 3; i++) {
    C[i + 3] = B[i];
}
  • Copies B[0] to C[3]
  • Copies B[1] to C[4]
  • Copies B[2] to C[5]
  • Uses index shifting (i + 3)

๐Ÿ”น Step 7: Display Merged Array C

for(i = 0; i < 6; i++) {
    printf("C[%d] = %d\n", i, C[i]);
}
  • Prints all 6 elements of C
  • Shows index and value for each
  • Uses \n for newlines

๐Ÿงช Sample Output

Enter 3 elements of array A:
A[0]: 10
A[1]: 20
A[2]: 30

Enter 3 elements of array B:
B[0]: 40
B[1]: 50
B[2]: 60

Merged array C:
C[0] = 10
C[1] = 20
C[2] = 30
C[3] = 40
C[4] = 50
C[5] = 60

๐Ÿ“Œ Key Concepts Covered

Array Declaration
Creating fixed-size collections of elements with int arr[size]
Array Merging
Combining two arrays by copying elements sequentially
Index Shifting
Using C[i + 3] to place elements after existing ones
for Loop
Iterating through arrays with precise index control
I/O Operations
Using printf() and scanf() for console interaction

Create arrays A, B and C of size 3, perform C = A + B.

Create arrays A, B and C of size 3, perform C = A + B.

Learn how to perform element-wise addition of two arrays in C

array_addition.c
#include <stdio.h>

int main() {
    int A[3], B[3], C[3];
    int i;

    // Input elements of array A
    printf("Enter 3 elements of array A:\n");
    for(i = 0; i < 3; i++) {
        printf("A[%d]: ", i);
        scanf("%d", &A[i]);
    }

    // Input elements of array B
    printf("\nEnter 3 elements of array B:\n");
    for(i = 0; i < 3; i++) {
        printf("B[%d]: ", i);
        scanf("%d", &B[i]);
    }

    // Add elements of A and B, store in C
    for(i = 0; i < 3; i++) {
        C[i] = A[i] + B[i];
    }

    // Display result
    printf("\nResultant array C (A + B):\n");
    for(i = 0; i < 3; i++) {
        printf("C[%d] = %d\n", i, C[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This includes the standard input-output library which provides:

  • printf() for output display
  • scanf() for user input
  • Other essential I/O functions

๐Ÿ”น Step 2: Declare Arrays and Variables

int A[3], B[3], C[3];
int i;
  • A[3] and B[3]: Arrays to store user inputs (3 elements each)
  • C[3]: Array to store the sum of corresponding elements
  • i: Loop counter variable for array traversal

๐Ÿ”น Step 3: Input Values in Array A

for(i = 0; i < 3; i++) {
    printf("A[%d]: ", i);
    scanf("%d", &A[i]);
}

This loop:

  • Runs 3 times (i = 0 to 2)
  • Prompts user for each element with index position
  • Stores input values in array A
  • Uses &A[i] to get memory address for storage

๐Ÿ”น Step 4: Input Values in Array B

for(i = 0; i < 3; i++) {
    printf("B[%d]: ", i);
    scanf("%d", &B[i]);
}

Similar to Step 3, but for array B:

  • Same loop structure
  • Stores values in array B
  • Maintains parallel indexing with array A

๐Ÿ”น Step 5: Add Corresponding Elements

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

Performs element-wise addition:

  • Adds A[0] + B[0] and stores in C[0]
  • Adds A[1] + B[1] and stores in C[1]
  • Adds A[2] + B[2] and stores in C[2]
  • Process is called vector addition

๐Ÿ”น Step 6: Display Result

for(i = 0; i < 3; i++) {
    printf("C[%d] = %d\n", i, C[i]);
}

Outputs the result array C:

  • Prints each element with its index
  • Uses \n for newline between elements
  • Shows the sum of corresponding elements from A and B

๐Ÿงช Sample Output

Enter 3 elements of array A:
A[0]: 2
A[1]: 4
A[2]: 6

Enter 3 elements of array B:
B[0]: 1
B[1]: 3
B[2]: 5

Resultant array C (A + B):
C[0] = 3
C[1] = 7
C[2] = 11

๐Ÿ“Œ Key Concepts Covered

Array
A linear data structure that stores elements of the same type in contiguous memory
Element-wise Addition
Adding corresponding elements from two arrays of the same size
for Loop
Control structure used to traverse and process array elements sequentially
Array Indexing
Accessing individual array elements using their position (0-based index)
I/O Operations
Using printf() and scanf() for formatted output and input

Create an array of size 10, input values and display sum and average of all elements in the array.

Create an array of size 10, input values and display sum and average of all elements in the array.

array_sum_avg.c
#include <stdio.h>

int main() {
    int arr[10], i, sum = 0;  // Step 1: Declare array and variables
    float avg;

    // Step 2: Input elements from user
    printf("Enter 10 integers:\n");
    for(i = 0; i < 10; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }

    // Step 3: Calculate sum
    for(i = 0; i < 10; i++) {
        sum += arr[i];
    }

    // Step 4: Calculate average
    avg = sum / 10.0;

    // Step 5: Display results
    printf("\nSum of all elements = %d", sum);
    printf("\nAverage of all elements = %.2f", avg);

    return 0;
}

๐Ÿง  Step-by-Step Explanation

๐Ÿ”น Step 1: Variable Declaration

int arr[10], i, sum = 0;
float avg;
  • arr[10] creates an integer array with 10 elements
  • sum initialized to 0 to accumulate total
  • avg declared as float for precise division
  • i will be used as loop counter

๐Ÿ”น Step 2: Input Array Elements

for(i = 0; i < 10; i++) {
    scanf("%d", &arr[i]);
}
  • Loop runs 10 times (i = 0 to 9)
  • Prompts user for each element
  • Stores input in array using index i
  • &arr[i] gets memory address for storage

๐Ÿ”น Step 3: Calculate Sum

for(i = 0; i < 10; i++) {
    sum += arr[i];
}
  • Iterates through each array element
  • Adds each element's value to sum
  • After loop completes, sum contains total

๐Ÿ”น Step 4: Calculate Average

avg = sum / 10.0;
  • Divides sum by 10.0 (float division)
  • Using 10.0 instead of 10 ensures decimal result
  • Result stored in avg variable

๐Ÿ”น Step 5: Display Results

printf("\nSum of all elements = %d", sum);
printf("\nAverage of all elements = %.2f", avg);
  • First printf displays integer sum
  • Second printf shows average with 2 decimal places
  • %.2f format specifier controls decimal precision

๐Ÿ–จ️ Sample Output:

Enter 10 integers:
Element 1: 5
Element 2: 10
Element 3: 15
Element 4: 20
Element 5: 25
Element 6: 30
Element 7: 35
Element 8: 40
Element 9: 45
Element 10: 50

Sum of all elements = 275
Average of all elements = 27.50

๐Ÿ’ก Key Concepts:

  • Array Basics: Fixed-size collection of same-type elements
  • Loop Structures: for loops for controlled iteration
  • Type Conversion: Importance of 10.0 for float division
  • I/O Formatting: Using %.2f for decimal precision
  • Memory Management: Array elements stored contiguously

Tuesday, 8 July 2025

Strings and String Operations in Python

Strings and String Operations in Python

๐Ÿ”ถ What is a String?

A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or even triple quotes (''' or """).

✅ Examples:

text1 = 'Hello'
text2 = "Python"
text3 = '''Data Science'''

A string can contain:

  • Letters: 'abc'
  • Numbers: '123' (as characters)
  • Symbols: '@#$'
  • Spaces: 'Data Science'

In Python, a string is immutable, meaning once it's created, it cannot be changed.

๐Ÿ”ถ How to Create a String

๐Ÿ”ธ Using quotes:

name = "Alice"
greeting = 'Hello!'

๐Ÿ”ธ Using str() constructor:

number = 123
string_number = str(number)   # '123'

๐Ÿ”ถ String Indexing and Slicing

✅ Indexing:

Each character in a string has a position called an index. Indexing starts from 0.

word = "Python"
print(word[0])   # 'P'
print(word[3])   # 'h'

You can also use negative indexing:

print(word[-1])  # 'n' (last character)
print(word[-2])  # 'o'

✅ Slicing:

Slicing means getting a part of the string.

word = "DataScience"
print(word[0:4])   # 'Data'
print(word[4:])    # 'Science'
print(word[:4])    # 'Data'
print(word[::2])   # 'Dt cec' (skips every second character)

๐Ÿ”ถ Basic String Operations

Operation Syntax / Example Description
Concatenation "Data" + "Science" Joins two strings → 'DataScience'
Repetition "Python" * 3 Repeats string → 'PythonPythonPython'
Length len("Python") Returns number of characters → 6
Membership 'D' in "Data" Checks if character exists → True
Looping for char in "AI": print(char) Iterates over characters

๐Ÿ”ถ String Methods (Built-in Functions)

Python provides many helpful functions (methods) to work with strings.

๐ŸŸฉ Common String Methods

Method Description Example
.lower() Converts to lowercase 'PYTHON'.lower() → 'python'
.upper() Converts to uppercase 'data'.upper() → 'DATA'
.title() Capitalizes each word 'machine learning'.title()
.strip() Removes spaces from both ends ' data '.strip() → 'data'
.replace(old, new) Replaces a part of the string 'AI'.replace('A','I')
.split(separator) Splits string into list 'a,b,c'.split(',') → ['a','b','c']
.join(list) Joins list into string ','.join(['a','b','c']) → 'a,b,c'
.find(substring) Finds first index of substring 'python'.find('t') → 2
.count(substring) Counts how many times a substring appears 'banana'.count('a') → 3
.startswith(sub) Checks if string starts with sub 'hello'.startswith('he') → True
.endswith(sub) Checks if string ends with sub 'file.txt'.endswith('.txt') → True

๐Ÿ”ถ Escape Characters

Escape characters are used to include special characters in strings.

Escape Code Description Example Output
\n New line Line 1
Line 2
\t Tab (space) Adds tab space
\' Single quote It's Python
\" Double quote He said "Hi"
\\ Backslash \
print("Hello\nWorld")      # prints on two lines
print("She said, \"Yes\"") # uses double quotes inside string

๐Ÿ”ถ String Formatting

Used to insert variables into strings.

✅ 1. Using f-strings (Modern & Preferred)

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

✅ 2. Using format()

print("My name is {} and I am {} years old.".format(name, age))

๐ŸŸฆ Real-life Applications in Data Science

Task How Strings Help
Reading file content File data is read as strings
Preprocessing text (NLP) Clean and format input strings
Parsing CSV/JSON/XML data Split and analyze text-based files
Converting input values Convert raw strings to usable formats
Displaying messages or dashboards Present data using formatted strings

๐Ÿง  Key Points to Remember

  • Strings are sequences of characters and are immutable.
  • You can use indexing and slicing to access parts of a string.
  • There are many built-in string methods to manipulate text.
  • Strings can be formatted using f-strings or .format().
  • Strings play a key role in file handling, web scraping, NLP, and more.

๐Ÿ“ Practice Questions

  1. Take a sentence from user input and count how many words it has.
  2. Write a program to reverse a string using slicing.
  3. Ask the user to enter a name, and check if it starts with a capital letter.
  4. Replace all spaces in a sentence with underscores (_).
  5. Check if a string is a palindrome (same forward and backward).

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...