Binary Triangle is a Triangle formed with 1’s and 0’s.Number of rows in the binary triangle is obtained from the user.
Here is source code of the C# Program to Print a Binary Triangle.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
static void Main(string[] args) { int p, lastInt = 0, input; Console.WriteLine("Enter the Number of Rows : "); input = int.Parse(Console.ReadLine()); for (int i = 1; i <= input; i++) { for (p = 1; p <= i; p++) { if (lastInt == 1) { Console.Write("0"); lastInt = 0; } else if (lastInt == 0) { Console.Write("1"); lastInt = 1; } } Console.Write("\n"); } Console.ReadLine(); } |
Output:
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
static void Main(string[] args) { int i, j, k, numOfLines; Console.Write("Enter the number of lines:"); numOfLines = Convert.ToInt32(Console.ReadLine()); for (i = 1; i <= numOfLines; i++) { for (k = numOfLines - i; k >= 1; k--) { Console.Write(" "); } if (i % 2 != 0) { for (j = 1; j <= i; j++) { if (j % 2 == 0) { Console.Write("0 "); } else { Console.Write("1 "); } } } else if (i % 2 == 0) { for (j = 1; j <= i; j++) { if (j % 2 == 0) { Console.Write("1 "); } else { Console.Write("0 "); } } } Console.WriteLine(); } Console.ReadKey(); } |
Output: