Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print the stars in Diamond pattern using C language?
Here, to print stars in diamond pattern, we are using nested for loops.
The logic that we use to print stars in diamond pattern is shown below −
//For upper half of the diamond the logic is:
for (j = 1; j <= rows; j++){
for (i = 1; i <= rows-j; i++)
printf(" ");
for (i = 1; i<= 2*j-1; i++)
printf("*");
printf("
");
}
Suppose let us consider rows=5, it prints the output as follows −
* *** ***** ******* *********
//For lower half of the diamond the logic is:
for (j = 1; j <= rows - 1; j++){
for (i = 1; i <= j; i++)
printf(" ");
for (i = 1 ; i <= 2*(rows-j)-1; i++)
printf("*");
printf("
");
}
Suppose row=5, the following output will be printed −
******* ***** *** *
Example
#include <stdio.h>
int main(){
int rows, i, j;
printf("Enter no of rows
");
scanf("%d", &rows);
for (j = 1; j <= rows; j++){
for (i = 1; i <= rows-j; i++)
printf(" ");
for (i = 1; i<= 2*j-1; i++)
printf("*");
printf("
");
}
for (j = 1; j <= rows - 1; j++){
for (i = 1; i <= j; i++)
printf(" ");
for (i = 1 ; i <= 2*(rows-j)-1; i++)
printf("*");
printf("
");
}
return 0;
}
Output
Enter no of rows 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Advertisements