Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print a diamond using nested loop using C#?
A diamond pattern is a common programming exercise that demonstrates the use of nested loops in C#. The diamond shape consists of two parts: an upper triangle that expands and a lower triangle that contracts.
To create a diamond pattern, you need to consider three key elements −
Number of rows (determines diamond size) Characters to display (commonly $ or *) Leading spaces for alignment
Algorithm
The diamond pattern algorithm works as follows −
-
Upper half: Start with maximum spaces and minimum characters, then decrease spaces and increase characters for each row.
-
Lower half: Increase spaces and decrease characters for each row, creating the mirror effect.
-
Use a condition to switch between the upper and lower halves at the middle row.
Example
using System;
namespace Program {
public class Demo {
public static void Main(String[] args) {
int i, j, r, d, e;
// rows = 5 (half of diamond height)
r = 5;
// display dollar sign count
d = 1;
// empty space count
e = r - 1;
for (i = 1; i < r * 2; i++) {
// display leading spaces
for (j = 1; j <= e; j++)
Console.Write(" ");
// display dollar signs
for (j = 1; j < d * 2; j++)
Console.Write("$");
Console.WriteLine();
// adjust spaces and characters for next row
if (i < r) {
e--; // decrease spaces (upper half)
d++; // increase characters
} else {
e++; // increase spaces (lower half)
d--; // decrease characters
}
}
}
}
}
The output of the above code is −
$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
Using Different Characters
using System;
class DiamondPattern {
public static void Main() {
int rows = 4;
char symbol = '*';
// Upper half including middle
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
Console.Write(" ");
}
// Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
Console.Write(symbol);
}
Console.WriteLine();
}
// Lower half
for (int i = rows - 1; i >= 1; i--) {
// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
Console.Write(" ");
}
// Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
Console.Write(symbol);
}
Console.WriteLine();
}
}
}
The output of the above code is −
* *** ***** ******* ***** *** *
Conclusion
Creating diamond patterns in C# demonstrates effective use of nested loops and conditional logic. The key is managing the relationship between leading spaces and character count, where spaces decrease as characters increase in the upper half, and the pattern reverses in the lower half.
