C program to print diamond pattern

 C program to print diamond pattern
  *
 ***
*****
 ***
  *

#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;
}
======================================================================================

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");
}

Comments

Popular posts from this blog

C Program to Display the ATM Transaction

Java programming language

Python Program to Print all Prime Numbers in an Interval