How to print a diamond using nested loop using C#?


With C#, you can easily display the following diamond shape.

$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$

To display a diamond shape, you need to focus on the following points −

Number of rows
Dollar sign to be displayed
Empty spaces

Considering the above you can easily create the diamond shape as shown in the below code −

Example

 Live Demo

using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {
         int i, j, r, d, e;

         // rows = 5
         r = 5;

         // display dollar sign
         d = 1;

         // empty space
         e = r - 1;

         for (i = 1; i < r * 2; i++) {
            // display empty space
            for (j = 1; j <= e; j++)
            Console.Write(" ");

            for (j = 1; j < d * 2; j++)
            Console.Write("$");

            Console.WriteLine();

            if (i < r) {
               e--;
               d++;
            } else {
               e++;
               d--;
            }
         }

      }
   }
}

Output

$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements