C program to print diamond pattern

python tutorials and learn python

Created with Sketch.

 

C program to print diamond pattern

The diamond pattern in C language: This code prints a diamond pattern of stars. The diamond shape is as follows:

  *
 ***
*****
 ***
  *

C programming code

#include <stdio.h>

int main()
{
int n, c, k, space = 1;

printf(“Enter number of rows\n“);
scanf(“%d”, &n);

space = n – 1;

for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(” “);

space–;

for (c = 1; c <= 2*k–1; c++)
printf(“*”);

printf(“\n“);
}

space = 1;

for (k = 1; k <= n – 1; k++)
{
for (c = 1; c <= space; c++)
printf(” “);

space++;

for (c = 1 ; c <= 2*(n–k)–1; c++)
printf(“*”);

printf(“\n“);
}

return 0;
}

Output of program:
Diamond pattern C program output

 

C program to print diamond using recursion

#include <stdio.h>

void print (int);

int main () {
int rows;

scanf(“%d”, &rows);

print(rows);

return 0;
}

void print (int r) {
int c, space;
static int stars = –1;

if (r <= 0)
return;

space = r – 1;
stars += 2;

for (c = 0; c < space; c++)
printf(” “);

for (c = 0; c < stars; c++)
printf(“*”);

printf(“\n“);

print(—r);

space = r + 1;
stars -= 2;

for (c = 0; c < space; c++)
printf(” “);

for (c = 0; c < stars; c++)
printf(“*”);

printf(“\n“);
}

Leave a Reply

Your email address will not be published. Required fields are marked *