+92 332 4229 857 99ProjectIdeas@Gmail.com

Diamond With Two Loops (C#.net)



The following code shows you diamond with two loops only. User can input, to how many lines should be the diamond hold and a character that displays the diamond. See the output of the program.



Code

public static void Main(string[] args)
{

    int rows;
    char chr1;

    Console.Write("Enter the number of lines of diamond: ");
    rows = int.Parse(Console.ReadLine());

    if (rows % 2 != 0) // if lines are ODD then print diamond
    {
        Console.Write("Enter character to be displayed: ");
        chr1 = char.Parse(Console.ReadLine());

        printDiamond(rows, chr1); //Call to print function after taking input
    }
    else // if lines are even then gives the following message
    {
        Console.WriteLine("Lines Should Be Odd");
    }
}

// Function which prints Diamond
public void printDiamond(int lines, char displayChar)
{
    int mid, temp, j;
            
    mid = lines / 2 + 1;
    temp = mid;


    for (int i = 1; i <= lines; i++)
    {
       j = 1;

         while (j <= temp)
         {

            if (j <= Math.Abs(mid - i))
            {
               Console.Write(" ");
            }
            else
            {
               Console.Write(displayChar);
            }

              j += 1;
         }

       Console.WriteLine();

          if (i < mid)
          {
            temp += 1;
          }
          else
          {
            temp -= 1;
          }
    }       
}

Output of the program is:

Enter number of lines of diamond: 12
  Lines Should Be Odd

Enter number of lines of diamond : 27
Enter character to be displayed : *

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



0 comments: