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

CsharpProgrammingServer Side Programming

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

$
$$$
$$$$$
$$$$$$$
$$$$$$$$$
$$$$$$$
$$$$$
$$$
$
raja
Published on 20-Aug-2018 16:42:16
Advertisements