Printing Pattern Using Loops HackerRank Solution

The given C code is designed to take an integer input 'n' and generate a pyramid pattern of numbers. The pattern starts with 'n' at the top and decreases to 1 towards the middle row. After the middle row, the pattern increases back to 'n'. The pattern is symmetric about the middle row.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Printing Pattern Using Loops HackerRank Solution HackerRank solution using CodeRankGPT:

The solution approach involves using nested loops to generate the pattern. The outer loop iterates over the rows of the pyramid, while the inner loops handle the printing of the numbers in each row. The first inner loop prints decreasing numbers from 'n' to 'n - i', the second inner loop prints the same number 'n - i' multiple times, and the third inner loop prints increasing numbers from 'n - i + 1' to 'n'. After the middle row, the pattern is repeated with slight modifications to handle the increasing numbers.


#include 
#include 
#include 
#include 

int main()
{
    int n;
    scanf("%d", &n);

    // Solution starts here
    int num = n * 2 - 1;

    for (int i = 0; i < n; i++) {
        int val = n;
        int counter = (n - i) * 2;
        int increase = n - i;

        while (val > n - i && val > 0)
            printf("%d ", val--);

        while (counter > 1 && n - i > 0) {
            counter--;
            printf("%d ", n - i);
        }

        while (increase < n)
            printf("%d ", ++increase);

        printf("\n");
    }

    // This is for the repeated values after the middle row
    int two = 0;

    for (int i = 1; i < n; i++) {
        int val = 0, counter = 0;

        while (val + i < n) {
            printf("%d ", n - val);
            val++;
        }

        while (++counter < 3 + two) {
            printf("%d ", i + 1);
        }

        two += 2;

        int increase = i + 1;
        while (increase < n) {
            printf("%d ", ++increase);
        }

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

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform