'Pattern Programming using for loops
with the code I've written below, I'm able to print the following pattern:
#include <stdio.h>
int main(void)
{
int no_rows, rows, column;
printf("Please enter a value: ");
scanf("%d", &no_rows);
for( rows = no_rows; rows >= 1; rows--) {
for(column = 1; column <= rows; column++) {
printf("* ");
}
printf("\n");
}
return 0;
}
So the question is, how can I manipulate my code, so that I can print out the following pattern?
Solution 1:[1]
The idea is just to first print the preceding spaces, and only then the asterisks - so first print row spaces, and only then print the remaining asterisks:
#include <stdio.h>
void print_pattern(const size_t no_rows)
{
size_t rows = 0, column = 0;
for (rows = 0; rows < no_rows; rows += 1)
{
for (column = 0; column < rows; column += 1)
{
printf(" ");
}
for (; column < no_rows; column += 1)
{
printf(" *");
}
puts("");
}
}
int main(void)
{
size_t no_rows = 0;
printf("Please enter a value: ");
scanf("%lu", &no_rows);
print_pattern(no_rows);
return 0;
}
Solution 2:[2]
Little bit more mathematical approach:
char triangle(int x, int y)
{
return x >= y ? '*' : ' ';
}
void print_pattern(int size)
{
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%c ", triangle(x, y));
}
printf("\n");
}
}
If more flexibility is needed, you can add a function pointer argument to print_pattern. With some other modifications, calling code could be something like this:
scanf("%d", &size);
print_pattern(size, triangle);
print_pattern(size, sphere);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | malkaroee |
| Solution 2 | SKi |


