Sunday, 17 August 2025

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

queue_implementation.c
#include <stdio.h>
#define MAX 5   // size of the queue

int queue[MAX];
int front = -1, rear = -1;

// Function to insert an element in queue
void insert(int val) {
    if(rear == MAX - 1) {
        printf("Queue Overflow! Cannot insert %d\n", val);
    } else {
        if(front == -1) front = 0;   // first insertion
        rear++;
        queue[rear] = val;
        printf("%d inserted into the queue.\n", val);
    }
}

// Function to delete an element from queue
void delete() {
    if(front == -1 || front > rear) {
        printf("Queue Underflow! No elements to delete.\n");
    } else {
        printf("%d deleted from the queue.\n", queue[front]);
        front++;
    }
}

// Function to display queue elements
void display() {
    if(front == -1 || front > rear) {
        printf("Queue is empty.\n");
    } else {
        printf("Queue elements: ");
        for(int i = front; i <= rear; i++) {
            printf("%d ", queue[i]);
        }
        printf("\n");
    }
}

// Main function to demonstrate queue
int main() {
    insert(10);
    insert(20);
    insert(30);
    display();

    delete();
    display();

    insert(40);
    insert(50);
    insert(60); // should give overflow
    display();

    delete();
    delete();
    delete();
    delete(); // should give underflow
    display();

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น Queue Structure

  • queue[MAX]: Array to store elements
  • front: Points to first element (initialized to -1)
  • rear: Points to last element (initialized to -1)

๐Ÿ”น Insert Operation

void insert(int val) {
    if(rear == MAX - 1) {
        printf("Queue Overflow! Cannot insert %d\n", val);
    } else {
        if(front == -1) front = 0;
        rear++;
        queue[rear] = val;
    }
}
  • Overflow check: If rear == MAX-1, queue is full
  • First insertion: Sets front to 0 when inserting first element
  • Normal insertion: Increments rear and adds element

๐Ÿ”น Delete Operation

void delete() {
    if(front == -1 || front > rear) {
        printf("Queue Underflow! No elements to delete.\n");
    } else {
        printf("%d deleted from the queue.\n", queue[front]);
        front++;
    }
}
  • Underflow check: If front == -1 or front > rear, queue is empty
  • Normal deletion: Removes element at front and increments front pointer

๐Ÿ”น Display Operation

void display() {
    if(front == -1 || front > rear) {
        printf("Queue is empty.\n");
    } else {
        printf("Queue elements: ");
        for(int i = front; i <= rear; i++) {
            printf("%d ", queue[i]);
        }
        printf("\n");
    }
}
  • Displays all elements from front to rear
  • Shows empty message if queue is empty

๐Ÿ–จ️ Example Run (Sample Output)

10 inserted into the queue.
20 inserted into the queue.
30 inserted into the queue.
Queue elements: 10 20 30
10 deleted from the queue.
Queue elements: 20 30
40 inserted into the queue.
50 inserted into the queue.
Queue Overflow! Cannot insert 60
Queue elements: 20 30 40 50
20 deleted from the queue.
30 deleted from the queue.
40 deleted from the queue.
50 deleted from the queue.
Queue Underflow! No elements to delete.
Queue is empty.

๐Ÿ“Œ Key Concepts Covered

FIFO Principle
First-In-First-Out behavior of queues
Array Implementation
Using array with front and rear pointers
Overflow/Underflow
Handling queue full and empty conditions
Basic Operations
Insert (enqueue), Delete (dequeue), and Display
Pointer Management
Proper handling of front and rear pointers

Write a program to find Minimum and Maximum numbers from the given array using Recursion.

Write a program to find Minimum and Maximum numbers from the given array using Recursion.

min_max_recursion.c
#include <stdio.h>

// Recursive function to find maximum
int findMax(int arr[], int n) {
    if(n == 1) 
        return arr[0];   // base case
    
    int maxRest = findMax(arr, n - 1); // recursion on n-1 elements
    
    return (arr[n - 1] > maxRest) ? arr[n - 1] : maxRest;
}

// Recursive function to find minimum
int findMin(int arr[], int n) {
    if(n == 1) 
        return arr[0];   // base case
    
    int minRest = findMin(arr, n - 1); // recursion on n-1 elements
    
    return (arr[n - 1] < minRest) ? arr[n - 1] : minRest;
}

int main() {
    int n, i;
    printf("Enter size of array: ");
    scanf("%d", &n);

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

    int max = findMax(arr, n);
    int min = findMin(arr, n);

    printf("Maximum element = %d\n", max);
    printf("Minimum element = %d\n", min);

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น 1. Input Array

  • User enters array size and elements
  • Example: arr = [5, 8, 2, 9, 1]

๐Ÿ”น 2. Recursive Max Function

int findMax(int arr[], int n) {
    if(n == 1) return arr[0];
    int maxRest = findMax(arr, n - 1);
    return (arr[n - 1] > maxRest) ? arr[n - 1] : maxRest;
}
  • Base case: When only one element remains, return it
  • Recursive case: Compare current element with max of remaining elements
  • Example: For [5,8,2,9,1], compares 1 with max of [5,8,2,9], etc.

๐Ÿ”น 3. Recursive Min Function

int findMin(int arr[], int n) {
    if(n == 1) return arr[0];
    int minRest = findMin(arr, n - 1);
    return (arr[n - 1] < minRest) ? arr[n - 1] : minRest;
}
  • Same logic as max function but compares for smaller values
  • Example: For [5,8,2,9,1], compares 1 with min of [5,8,2,9], etc.

๐Ÿ”น 4. Result Output

  • Prints the final minimum and maximum values
  • Example output: Maximum = 9, Minimum = 1

๐Ÿ–จ️ Example Run

Input:

Enter size of array: 5
Enter 5 elements: 5 8 2 9 1

Output:

Maximum element = 9
Minimum element = 1

๐Ÿ“Œ Key Concepts Covered

Recursion
Functions calling themselves with smaller subproblems
Base Case
Termination condition for recursive calls
Divide & Conquer
Breaking problem into smaller subproblems (n-1 elements)
Comparison Logic
Ternary operator used to compare elements
Array Processing
Handling array elements recursively

Write a program to find the factorial of a given integer number using stack.

Write a program to find the factorial of a given integer number using stack.

factorial_stack.c
#include <stdio.h>
#define MAX 100

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

// Function to push an element
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        stack[++top] = val;
    }
}

// Function to pop an element
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        return stack[top--];
    }
}

int main() {
    int n, i;
    long long fact = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    if(n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 0;
    }

    // Step 1: Push all numbers from n to 1
    for(i = n; i >= 1; i--) {
        push(i);
    }

    // Step 2: Pop all numbers and multiply
    while(top != -1) {
        fact *= pop();
    }

    printf("Factorial of %d is %lld\n", n, fact);

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น 1. Input Validation

if(n < 0) {
    printf("Factorial is not defined for negative numbers.\n");
    return 0;
}
  • Checks for negative input immediately
  • Exits program if input is invalid

๐Ÿ”น 2. Push Numbers to Stack

for(i = n; i >= 1; i--) {
    push(i);
}
  • Pushes numbers from n down to 1 onto the stack
  • Example: n=5 → stack becomes [5,4,3,2,1]

๐Ÿ”น 3. Pop and Multiply

while(top != -1) {
    fact *= pop();
}
  • Pops each number and multiplies with the running product
  • LIFO property ensures correct multiplication order
  • Example: 1 × 2 × 3 × 4 × 5 = 120

๐Ÿ”น 4. Result Output

  • Prints the final factorial result
  • Uses %lld format specifier for long long to handle large numbers

๐Ÿ–จ️ Example Runs

Example 1:

Enter a positive integer: 5
Factorial of 5 is 120

Example 2:

Enter a positive integer: 7
Factorial of 7 is 5040

๐Ÿ“Œ Key Concepts Covered

Stack Operations
Implementation of push/pop functions with error checking
LIFO Principle
Last-In-First-Out behavior used for multiplication order
Factorial Algorithm
n! = n × (n-1) × ... × 1 implemented using stack
Input Validation
Handling edge case for negative numbers
Data Types
Using long long to handle large factorial results

Write a program to find the power of a given number using stack.

Write a program to find the power of a given number using stack.

stack_exponent.c
#include <stdio.h>
#define MAX 100

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

// Function to push an element onto stack
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = val;
    }
}

// Function to pop an element from stack
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        int val = stack[top];
        top--;
        return val;
    }
}

int main() {
    int base, exp, i;
    long long result = 1;

    printf("Enter base number: ");
    scanf("%d", &base);
    printf("Enter exponent: ");
    scanf("%d", &exp);

    // Step 1: Push 'base' onto stack 'exp' times
    for(i = 0; i < exp; i++) {
        push(base);
    }

    // Step 2: Pop elements and multiply
    for(i = 0; i < exp; i++) {
        result *= pop();
    }

    printf("%d^%d = %lld\n", base, exp, result);

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น 1. Stack Implementation

  • Array stack[MAX] stores elements
  • Integer top tracks the top position
  • push() adds elements with overflow check
  • pop() removes elements with underflow check

๐Ÿ”น 2. Push Phase

for(i = 0; i < exp; i++) {
    push(base);
}
  • Pushes the base number onto stack 'exp' times
  • Example: base=3, exp=4 → stack becomes [3,3,3,3]

๐Ÿ”น 3. Pop and Multiply Phase

for(i = 0; i < exp; i++) {
    result *= pop();
}
  • Pops each element and multiplies with result
  • LIFO property ensures correct multiplication order
  • Example: 3 × 3 × 3 × 3 = 81

๐Ÿ”น 4. Result Output

  • Prints the final exponentiation result
  • Uses %lld format specifier for long long result

๐Ÿ–จ️ Example Runs

Example 1:

Enter base number: 2
Enter exponent: 5
2^5 = 32

Example 2:

Enter base number: 3
Enter exponent: 4
3^4 = 81

๐Ÿ“Œ Key Concepts Covered

Stack Operations
LIFO principle implemented with push/pop functions
Exponentiation
Calculating powers through repeated multiplication
Error Handling
Stack overflow/underflow detection
Data Types
Using long long for larger results
Algorithm Design
Creative use of stack for arithmetic operations

Write a program to find the Smallest Common Divisor of a given number.

Write a program to find the Smallest Common Divisor of a given number.

smallest_divisor.c
#include <stdio.h>

int main() {
    int n, i;

    printf("Enter a number: ");
    scanf("%d", &n);

    if(n <= 1) {
        printf("Smallest divisor is not defined for %d\n", n);
    } else {
        for(i = 2; i <= n; i++) {
            if(n % i == 0) {
                printf("Smallest divisor of %d is %d\n", n, i);
                break;   // stop at the first divisor found
            }
        }
    }

    return 0;
}

✅ Step-by-Step Explanation

๐Ÿ”น 1. Input a number

  • User enters a number (example: n = 28)
  • scanf() reads the integer input

๐Ÿ”น 2. Check for valid input

if(n <= 1) {
    printf("Smallest divisor is not defined for %d\n", n);
}
  • Numbers ≤ 1 don't have proper divisors
  • Program handles this edge case immediately

๐Ÿ”น 3. Find smallest divisor

for(i = 2; i <= n; i++) {
    if(n % i == 0) {
        printf("Smallest divisor of %d is %d\n", n, i);
        break;
    }
}
  • Loop starts from 2 (first possible proper divisor)
  • Modulo operator % checks divisibility
  • break exits loop after first divisor found

๐Ÿ–จ️ Example Runs

Composite Number Example:

Enter a number: 28
Smallest divisor of 28 is 2

Prime Number Example:

Enter a number: 37
Smallest divisor of 37 is 37

(37 is prime, so its smallest divisor is itself)

๐Ÿ“Œ Key Concepts Covered

For Loop
Iterates from 2 to n to check possible divisors
Modulo Operator %
Tests if n is divisible by current number (n % i == 0)
Break Statement
Exits loop immediately after finding first divisor
Edge Case Handling
Special handling for numbers ≤ 1
Prime Number Logic
If no divisors found before n, the number is prime

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

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