C Programming

Solved Example

Practice Questions

Exercise Question

C program to print a diamond pattern

Objective

Write a program to input the number of rows and print a diamond pattern. The diamond pattern is also called a water image pattern of a triangle pattern as given below...

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

Program

#include "stdio.h"
int main() {
	int n, i, j, k;
	printf("Enter the rows to print: ");
	scanf("%d",&n);
	
	//Rotate loop for n rows
	for(i = 1; i <= n; i++) {
		
		//loop for spaces
		for(j = 1; j <= n - i; j++) {
			printf("%c",32);
		}
		//loop for printing *
		for(k = 1; k <= 2 * i - 1; k++) {
			printf("*");
		}
		
		
		//switch to new line in each row
		printf("\n");
	}
	for(i = n - 1; i >= 1; i--) {
		//loop for spaces
		for(j = 1; j <= n - i; j++) {
			printf("%c",32);
		}
		//loop for printing *
		for(k = 1; k <= 2 * i - 1; k++) {
			printf("*");
		}
		
		
		//switch to new line in each row
		printf("\n");
	}
	return 0;
}

Sample Output

Enter the rows to print: 5
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *