Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

Concentric Square Number Pattern In C

๐Ÿ”ข C Program: Concentric Square Number Pattern

#include <stdio.h>

int main() {
    int n;
    printf("Enter the number of layers: ");
    scanf("%d", &n);

    int size = 2 * n - 1;

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

            printf("%d ", n - min);
        }
        printf("\n");
    }

    return 0;
}
  

๐Ÿ“ Explanation:

This C program prints a concentric number pattern in the form of a square matrix. Each layer of the square is filled with a decreasing number from the outermost layer to the center.

  • Input: The user enters the number of layers (n).
  • Matrix size: It is calculated using 2 * n - 1. This ensures we have n layers on each side (top, bottom, left, right).
  • Two nested loops: These go through each cell (i, j) of the matrix.
  • Finding the minimum distance: We calculate the minimum number of steps required to reach the border from cell (i, j). This is done using 4 comparisons:
    • i → distance from top
    • j → distance from left
    • size - 1 - i → distance from bottom
    • size - 1 - j → distance from right
  • Print value: The value to print is n - min which gives the correct number for that concentric layer.

๐Ÿ’ก Sample Output:

Enter the number of layers: 4

4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
  

Comments

Popular Posts

๐ŸŒ™