Sunday, 17 August 2025

Write a program to find GCD of two numbers.

Write a program to find GCD of two numbers.

gcd_calculator.c
#include <stdio.h>

int main() {
    int a, b, i, gcd;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    // Find the minimum of a and b
    int min = (a < b) ? a : b;

    for(i = 1; i <= min; i++) {
        if(a % i == 0 && b % i == 0) {
            gcd = i;
        }
    }

    printf("GCD of %d and %d is %d\n", a, b, gcd);

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น 1. Input

  • User enters two numbers (say a = 48, b = 18)
  • scanf() reads both integers from standard input

๐Ÿ”น 2. Find the smaller number

  • GCD can never be greater than the smaller number
  • Ternary operator (a < b) ? a : b determines the minimum

๐Ÿ”น 3. Check common divisors

for(i = 1; i <= min; i++) {
    if(a % i == 0 && b % i == 0) {
        gcd = i;
    }
}
  • Loop from 1 to the smaller number
  • Modulo operator % checks divisibility
  • When both numbers are divisible by i, update gcd

๐Ÿ”น 4. Output

  • After the loop ends, gcd holds the largest common divisor
  • printf() displays the final result

๐Ÿ–จ️ Example Run

Input:

Enter two numbers: 48 18

Output:

GCD of 48 and 18 is 6

๐Ÿ“Œ Key Concepts Covered

Loop (for)
To check all possible divisors from 1 to the smaller number
Modulo operator %
To test divisibility of both numbers by the current index
Decision making (if)
Conditional statement to update GCD when common divisor found
Basic I/O
scanf() for input and printf() for output
Ternary operator
Compact conditional to find minimum of two numbers

Friday, 1 August 2025

Write a program to print strings in reverse order using stack.

Write a program to print strings in reverse order using stack. C

reverse_string_stack.c
#include <stdio.h>
#include <string.h>
#define MAX 100

// Stack structure
char stack[MAX];
int top = -1;

// Push operation
void push(char ch) {
    if (top >= MAX - 1)
        printf("Stack Overflow\n");
    else
        stack[++top] = ch;
}

// Pop operation
char pop() {
    if (top == -1) {
        printf("Stack Underflow\n");
        return '\0';
    } else {
        return stack[top--];
    }
}

int main() {
    char str[MAX];
    int i;

    printf("Enter a string: ");
    fgets(str, MAX, stdin);
    str[strcspn(str, "\n")] = '\0'; // remove newline if present

    // Push all characters to stack
    for (i = 0; str[i] != '\0'; i++) {
        push(str[i]);
    }

    // Pop all characters to print in reverse
    printf("Reversed string: ");
    while (top != -1) {
        printf("%c", pop());
    }

    printf("\n");
    return 0;
}

๐Ÿชœ Step-by-Step Explanation

๐Ÿ”น 1. User Input

fgets(str, MAX, stdin);
str[strcspn(str, "\n")] = '\0';
  • fgets() reads a complete string including spaces
  • MAX limits input size to prevent buffer overflow
  • strcspn() removes the trailing newline character

๐Ÿ”น 2. Push Characters onto Stack

for (i = 0; str[i] != '\0'; i++) {
    push(str[i]);
}
  • Iterates through each character of the string
  • Pushes each character onto the stack using push()
  • Last character ends up at the top of the stack
  • Stack grows with each character pushed

๐Ÿ”น 3. Pop Characters to Reverse

while (top != -1) {
    printf("%c", pop());
}
  • Continues until stack is empty (top == -1)
  • Pops characters from stack using pop()
  • Prints each character immediately
  • Due to LIFO (Last In First Out), characters print in reverse order

Visualization of Stack Operations

Pushing "hello":

Push 'h' → ['h']
Push 'e' → ['h','e']
Push 'l' → ['h','e','l']
Push 'l' → ['h','e','l','l']
Push 'o' → ['h','e','l','l','o']

Popping for reversal:

Pop → 'o' (stack: ['h','e','l','l'])
Pop → 'l' (stack: ['h','e','l'])
Pop → 'l' (stack: ['h','e'])
Pop → 'e' (stack: ['h'])
Pop → 'h' (stack: [])

๐Ÿ–จ️ Sample Output

Input:

Enter a string: hello

Output:

Reversed string: olleh

๐Ÿ“Œ Key Concepts Covered

Stack
LIFO (Last In First Out) data structure where last element pushed is first popped
Push and Pop
Basic stack operations used to insert and remove elements
Manual Stack in C
Implemented using an array and top variable to track position
String Reversal
Natural result of stack's LIFO behavior when popping elements
Buffer Safety
fgets() used instead of scanf() for safe string input

Thursday, 31 July 2025

Write a program to find out the factorial of a number using recursion (stack).

Write a program to find out the factorial of a number using recursion (stack).

factorial_recursion.c
#include <stdio.h>

// Function to calculate factorial using recursion
int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

int main() {
    int num;
    printf("Enter a number to find its factorial: ");
    scanf("%d", &num);

    if (num < 0)
        printf("Factorial is not defined for negative numbers.\n");
    else {
        int result = factorial(num);
        printf("Factorial of %d is: %d\n", num, result);
    }

    return 0;
}

๐Ÿชœ Step-by-Step Explanation

๐Ÿ”น Step 1: Input from User

printf("Enter a number to find its factorial: ");
scanf("%d", &num);
  • Takes an integer input from the user (e.g., num = 5)
  • Uses scanf() to read the input value
  • Stores the value in variable num

๐Ÿ”น Step 2: Factorial Function Definition

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

This is a recursive function with:

  • Base case: If n is 0 or 1, return 1 (stopping condition)
  • Recursive case: Returns n multiplied by factorial(n - 1)
  • Each call reduces the problem size until reaching the base case

๐Ÿ”น Step 3: Understanding Stack Behavior (Recursion)

Each recursive call is pushed onto the call stack:

factorial(5)
    => 5 * factorial(4)
        => 4 * factorial(3)
            => 3 * factorial(2)
                => 2 * factorial(1)
                    => 1 (base case returns 1)

Then the stack unwinds with results:

factorial(1) = 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120

๐Ÿ–จ️ Sample Output

Input:

Enter a number to find its factorial: 5

Output:

Factorial of 5 is: 120

๐Ÿ“Œ Key Concepts Covered

Recursion
Function calling itself with reduced input size
Base Case
Condition that stops recursion when n == 0 || n == 1
Call Stack
Each function call is stored in stack memory until it returns
Factorial Definition
n! = n × (n-1) × (n-2) × ... × 1
Validation
Handles case for negative input (factorial undefined)

Implement stack using array with following operations: push, pop, print, peek, peep, change, exit.

Implement stack using array with following operations: push, pop, print, peek, peep, change, exit.

stack_operations.c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int stack[MAX];
int top = -1;

// Push operation
void push(int value) {
    if (top >= MAX - 1) {
        printf("Stack Overflow! Cannot push.\n");
    } else {
        top++;
        stack[top] = value;
        printf("%d pushed to stack.\n", value);
    }
}

// Pop operation
int pop() {
    if (top == -1) {
        printf("Stack Underflow! Cannot pop.\n");
        return -1;
    } else {
        return stack[top--];
    }
}

// Peek operation
void peek() {
    if (top == -1) {
        printf("Stack is empty!\n");
    } else {
        printf("Top element is: %d\n", stack[top]);
    }
}

// Peep operation
void peep(int position) {
    int index = top - position + 1;
    if (index < 0 || index > top) {
        printf("Invalid position! Cannot peep.\n");
    } else {
        printf("Element at position %d from top is: %d\n", position, stack[index]);
    }
}

// Change operation
void change(int position, int value) {
    int index = top - position + 1;
    if (index < 0 || index > top) {
        printf("Invalid position! Cannot change.\n");
    } else {
        stack[index] = value;
        printf("Element at position %d changed to %d.\n", position, value);
    }
}

// Print operation
void print() {
    if (top == -1) {
        printf("Stack is empty!\n");
    } else {
        printf("Stack elements (top to bottom):\n");
        for (int i = top; i >= 0; i--) {
            printf("%d\n", stack[i]);
        }
    }
}

int main() {
    int choice, value, position;

    while (1) {
        printf("\n\n***** STACK OPERATIONS MENU *****\n");
        printf("1. Push\n2. Pop\n3. Peek\n4. Peep\n5. Change\n6. Print\n7. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter value to push: ");
                scanf("%d", &value);
                push(value);
                break;

            case 2:
                value = pop();
                if (value != -1)
                    printf("Popped value: %d\n", value);
                break;

            case 3:
                peek();
                break;

            case 4:
                printf("Enter position from top to peep: ");
                scanf("%d", &position);
                peep(position);
                break;

            case 5:
                printf("Enter position from top to change: ");
                scanf("%d", &position);
                printf("Enter new value: ");
                scanf("%d", &value);
                change(position, value);
                break;

            case 6:
                print();
                break;

            case 7:
                printf("Exiting program...\n");
                exit(0);

            default:
                printf("Invalid choice! Please try again.\n");
        }
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Stack Initialization

int stack[MAX];
int top = -1;
  • stack[MAX]: Array to store stack elements (MAX = 100)
  • top: Index of top element, initialized to -1 (empty stack)

๐Ÿ”น Push Operation

void push(int value) {
    if (top >= MAX - 1) {
        printf("Stack Overflow! Cannot push.\n");
    } else {
        top++;
        stack[top] = value;
        printf("%d pushed to stack.\n", value);
    }
}
  • Checks for stack overflow (when stack is full)
  • Increments top and adds new element
  • Provides feedback about the operation

๐Ÿ”น Pop Operation

int pop() {
    if (top == -1) {
        printf("Stack Underflow! Cannot pop.\n");
        return -1;
    } else {
        return stack[top--];
    }
}
  • Checks for stack underflow (when stack is empty)
  • Returns top element and decrements top
  • Returns -1 if stack is empty

๐Ÿ”น Peek Operation

void peek() {
    if (top == -1) {
        printf("Stack is empty!\n");
    } else {
        printf("Top element is: %d\n", stack[top]);
    }
}
  • Displays the top element without removing it
  • Checks if stack is empty first

๐Ÿ”น Peep Operation

void peep(int position) {
    int index = top - position + 1;
    if (index < 0 || index > top) {
        printf("Invalid position! Cannot peep.\n");
    } else {
        printf("Element at position %d from top is: %d\n", position, stack[index]);
    }
}
  • Views element at specific position from top
  • Calculates index using top - position + 1
  • Validates position is within bounds

๐Ÿ”น Change Operation

void change(int position, int value) {
    int index = top - position + 1;
    if (index < 0 || index > top) {
        printf("Invalid position! Cannot change.\n");
    } else {
        stack[index] = value;
        printf("Element at position %d changed to %d.\n", position, value);
    }
}
  • Modifies element at specific position from top
  • Uses same position calculation as peep operation
  • Provides feedback about the change

๐Ÿ”น Print Operation

void print() {
    if (top == -1) {
        printf("Stack is empty!\n");
    } else {
        printf("Stack elements (top to bottom):\n");
        for (int i = top; i >= 0; i--) {
            printf("%d\n", stack[i]);
        }
    }
}
  • Displays all stack elements from top to bottom
  • Checks if stack is empty first
  • Uses reverse loop to show top element first

๐Ÿงช Sample Output

***** STACK OPERATIONS MENU *****
1. Push
2. Pop
3. Peek
4. Peep
5. Change
6. Print
7. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack.

Enter your choice: 1
Enter value to push: 20
20 pushed to stack.

Enter your choice: 3
Top element is: 20

Enter your choice: 4
Enter position from top to peep: 2
Element at position 2 from top is: 10

Enter your choice: 5
Enter position from top to change: 2
Enter new value: 15
Element at position 2 changed to 15.

Enter your choice: 6
Stack elements (top to bottom):
20
15

Enter your choice: 2
Popped value: 20

Enter your choice: 7
Exiting program...

๐Ÿ“Œ Key Concepts Covered

Stack
LIFO (Last In First Out) data structure
Array Implementation
Using static memory allocation with fixed size
Core Operations
Push, Pop, Peek, Peep, Change, Print
Position Calculation
top - position + 1 for peep/change operations
Error Handling
Stack overflow and underflow conditions checked

Wednesday, 16 July 2025

Write a simple java program to display message.

Write a simple java program to display message.

Write a simple java program to display message.

Learn how to create your first Java program with detailed explanation

The Java Program

Here's the complete code for our simple Java program that displays a welcome message:

// Simple Java Program to Display a Message

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Welcome to MCA Java Programming!");
    }
}

๐Ÿงฉ Step-by-Step Explanation

1. The Comment Line
// Simple Java Program to Display a Message

This is a single-line comment that describes the purpose of the program. Comments are ignored by the compiler but help humans understand the code.

2. Class Declaration
public class HelloWorld {

This defines a class named HelloWorld, which is required because every Java program must be inside a class.

Important: The class name HelloWorld must exactly match the filename HelloWorld.java.

3. The Main Method
public static void main(String[] args) {

This is the main method, which acts as the entry point for the program. Let's break down its components:

  • public: Makes the method accessible from anywhere
  • static: Allows the method to be called without creating an object
  • void: Indicates the method doesn't return any value
  • String[] args: Parameter that accepts command-line arguments
4. Output Statement
System.out.println("Welcome to MCA Java Programming!");

This prints the message to the console followed by a newline. Breaking it down:

  • System.out: The standard output stream
  • println(): Prints the message and moves to the next line

To display a different message, replace the text inside the quotation marks.

5. Closing Braces
}

These closing braces mark the end of the main method and the class block.

๐Ÿ–ฅ️ Sample Output

When you run this program, you'll see the following output in your console:

Welcome to MCA Java Programming!

๐Ÿง  Key Concepts Covered

Concept Description
Class Definition All Java code must be within a class
Main Method The program starts execution from main()
Output Statement System.out.println() is used to display output
Comments Improve readability; ignored during execution
Java Syntax Use of semicolons, method structure, and curly braces

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

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() ...