How to print a BinaryTriangle using C#?

CsharpProgrammingServer Side Programming

Binary triangle is formed with 0s and 1s. To create one, you need to work around a nestes for loop and display 0s and 1s till the row entered.

for (int i = 1; i <= n; i++) {

   for (j = 1; j <= i; j++) {
      if (a == 1) {
         Console.Write("0");
         a = 0;
      } else if (a == 0) {
         Console.Write("1");
         a = 1;
      }
   } Console.Write("\n");
}

Above, “0” displays when the value of a is 1, whereas if a is 0, then 1 gets printed. In this way, if the rows are set as 7 i.e. the value of n in the for loop, then the following binary triangle would be visible.

1
01
010
1010
10101
010101
0101010

Example

using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {

         int j;
         int a = 0, n = 7;
         // looping from 1 to 7
         for (int i = 1; i <= n; i++) {
            for (j = 1; j <= i; j++) {
               if (a == 1) {
                  Console.Write("0");
                  a = 0;
               } else if (a == 0) {
                  Console.Write("1");
                  a = 1;
               }
            } Console.Write("\n");
         }
         Console.ReadLine();
      }
   }
}
raja
Published on 20-Aug-2018 13:05:46
Advertisements