I'm trying to make a program that takes input number of rows from the user and prints this type of pattern for example if "number of rows: 5", then it should print this pattern OUTPUT I WANT
I wrote this C code,
#include <stdio.h>
int main() {
int rows, i, j, k;
// Take input for the number of rows
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
k = 'A';
for (j = 1; j <= 2 * rows - 1; j++) {
// Adjusted condition to reduce one space in all rows
if ((j <= rows - i || j >= rows + i) && !(i == 1 && j == rows)) {
printf("%c", k);
j < rows ? k++ : k--;
} else {
if (j != rows) {
printf(" ");
}
if (j == rows) {
k--;
}
}
}
printf("\n");
}
return 0;
}
And after execution of this above code I'm getting this type of answer UNDESIRED RESULT
Reduce complexity. Break down what your program actually has to do into smaller steps.
For an input of N, your function has to print N lines.
On the first line you need to print N letters in the sequence from
AtoZand zero spaces. On the second line you need to print N - 1 letters and one space. And so on.Output so far:
Now, you just need to reverse these steps to print the end of each line.
Output:
With some math those two loops to print the spaces can now be reduced to one.
Which could further be reduced to:
Alternatively, if we create strings representing the forward and backwards parts of the string, we can use
printfto control printing much as we did with the spaces in the previous snippet.Note: as both
strandrevare always being printed with a width specifier, you could eliminate the null terminators on both arrays.